http://stackoverflow.com/q/49329326
tagged with: python-import
score: 3
upvote count: 3
answer count: 0
downvote count: 0
tagged with: european-data-format
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
type: UnansweredQuestion
tagged with: python
has title: Using pyedflib to write csv to EDF+
has body: Wanted to know is it possible to just directly read in data from csv file and print everything into a EDF file using PYEDFLIB? The biggest challenge is that PYEDFLIB code on their website doesnt support large Data Link for reference about pyedflib http://pyedflib.readthedocs.io/en/latest/
has comment: http://stackoverflow.com/comment/128217606

http://stackoverflow.com/a/49333772
score: 2
answers question: http://stackoverflow.com/q/49333662
upvote count: 2
downvote count: 0
has body: Google has geocoding services but they pass data using JSON responses. You will have to parse the JSON schema. import requests url = 'https://maps.googleapis.com/maps/api/geocode/json' p = {'address:' 'New York'} r = requests.get(url, params=p).json() results = r['results'] results will hold your location. You simply have to retrieve what's needed. Hope that helps. If there are any problems let me know
type: Answer

http://stackoverflow.com/comment/85777472
score: 0
has text: I handle the communication with files. I'm just trying to understand why the children are shut down instead of becoming orphans..
type: Comment
comment on: http://stackoverflow.com/q/49351121
type: QuestionComment

http://stackoverflow.com/q/49317237
has comment: http://stackoverflow.com/comment/85636123
type: Question
type: UnansweredQuestion
tagged with: swagger
tagged with: swagger-codegen
tagged with: python
has title: Swagger-Codegen outputing broken python code
has comment: http://stackoverflow.com/comment/85650098
score: 0
answer count: 0
tagged with: yaml
has body: Description Attempting to create a python module for using the Royal Mail rest API. Swagger output the module, and pip install . works fine. Importing the newly created module results in ImportError: No module named 'rm_tracking.models.inline_response200_error' Which is because the path should be: rm_tracking.models.inline_response_200_error Swagger-codegen version 2.3.1 Swagger declaration file content or url --- swagger: "2.0" info: title: Tracking API (REST) description: "Tracking API provides the functionality to enquire on the tracking status of mail items. The API provides the latest tracking information, the tracking history, and the proof of delivery information (minus the signature image) for a single mail item. The API provides an alternative mechanism to using the track and trace function on the Royal Mail website (http://www.royalmail.com/track-trace). \n \nThere are no costs to customers for using the Tracking API services, however development costs must be covered by the customer. Royal Mail will not accept any responsibility for these development, implementation and testing costs.\n \nCustomers should address initial inquiries regarding development of systems for these purposes to their account handler." version: 1.0.0-live x-ibm-name: tracking-api-rest basePath: /mailPieces schemes: - https x-ibm-configuration: enforced: true phase: realized testable: true externalDocs: [] tags: [] securityDefinitions: Client ID: description: "" in: header name: X-IBM-Client-Id type: apiKey Client Secret: type: apiKey name: X-IBM-Client-Secret in: header description: "" paths: /{trackingNumber}/proofOfDelivery: get: description: Provides the details captured at the point of delivery as proof that delivery has occurred. Note that a proof of delivery is only captured by the delivery track for those service offerings that require a signature on delivery. Please also note that for data protection reasons the API does not currently supply the signature image captured at t…

http://stackoverflow.com/comment/85596497
score: 0
type: Comment
type: AnswerComment
has text: You can connect to any node, including one you run yourself.
comment on: http://stackoverflow.com/a/49297031

http://stackoverflow.com/q/49407711
downvote count: 8
has answer: http://stackoverflow.com/a/49407868
score: -8
tagged with: range
tagged with: python
has body: I am having an issue with a list that I have split from some text by using the comma delimiter. The list has 4-5 items but when I try to get the 4th-5th item in the list, it says out of range. Not sure why it's happening. import re import requests r = requests.get('https://halalhmc.org/outlets-by-name/') from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'outlet-content'}) records = [] for result in results: name = result.find('h3').text fullAddress = result.find('p', attrs={'class':'outlet-address'}).text split_address = fullAddress.split(',') address1 = split_address[0] city = split_address[1] city1 = split_address[2] validPcode = re.match("[A-Z]{2}[0-9] [0-9][A-Z]{2}",split_address[3]) if validPcode: postCode = split_address[3] else: county = split_address[3] postCode = split_address[4] records.append((name,address1[10:],city,city1,postCode)) print records[2] When I do print len(split_address) and remove print records[1], I get 5 as the length. Why is this happening?
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85816684
has comment: http://stackoverflow.com/comment/85819043
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85820757
has title: index out of range but is in fact in range
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/85816664
has comment: http://stackoverflow.com/comment/85819225
accepted answer: http://stackoverflow.com/a/49407868
has comment: http://stackoverflow.com/comment/85816550
upvote count: 0

http://stackoverflow.com/comment/85739995
comment on: http://stackoverflow.com/q/49369342
type: QuestionComment
has text: Yes I did using the ipdb. The file is in the memory but doesn't get to my folder.
score: 0
type: Comment

http://stackoverflow.com/a/49345114
has comment: http://stackoverflow.com/comment/85690492
has body: Selenium is a module, and it doesn't have a document attribute, you need to use the webdriver to locate the element. document.getElementById is not a Python syntax anyway, its JavaScript. Try username = driver.find_element_by_id('username') Keep in mind that the search is case sensitive, username is all in lowercase letters.
accepted answer of: http://stackoverflow.com/q/49344994
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85690541
score: 2
answers question: http://stackoverflow.com/q/49344994
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49289539
upvote count: 7
has body: I am trying to run a subquery inside a case statement in Pyspark and it is throwing an exception. I am trying to create a new flag if id in one table is present in a different table. Is this even possible in pyspark? temp_df=spark.sql("select *, case when key in (select distinct key from Ids) then 1 else 0 end as flag from main_table") Here is the error: AnalysisException: 'Predicate sub-queries can only be used in a Filter I am using Spark 2.2.1.
has comment: http://stackoverflow.com/comment/85605230
favorite count: 0
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
has title: Pyspark- Subquery in a case statement
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49346390
score: 7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49346390
has comment: http://stackoverflow.com/comment/85589630

http://stackoverflow.com/comment/85846478
has text: @Strawberry int is 4 bytes, mediumint is 3 bytes, bigint is 8 bytes. Number in string consumes number of digits + 2 or 4 bytes for string size. So for 1000 digit number it's 1000 times slower ;)
comment on: http://stackoverflow.com/q/49420039
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49433700
tagged with: python
has answer: http://stackoverflow.com/a/49433830
has comment: http://stackoverflow.com/comment/85869542
has body: I have a directory with several types of files. How can I count the number of files in a directory with 2 types of extensions (.txt and .csv)? In my search I found how to count with only one certain extension
type: Question
type: AnsweredQuestion
has title: How to count files with 2 types of extensions in a directory in python?
accepted answer: http://stackoverflow.com/a/49433993
possible better answer: http://stackoverflow.com/a/49433765
has answer: http://stackoverflow.com/a/49433993
favorite count: 0
has answer: http://stackoverflow.com/a/49433765
score: 2
upvote count: 2
downvote count: 0
answer count: 3

http://stackoverflow.com/q/49307401
has comment: http://stackoverflow.com/comment/85616902
has comment: http://stackoverflow.com/comment/85616916
has comment: http://stackoverflow.com/comment/85618216
tagged with: unicode
tagged with: skulpt
has title: Are triple quotation marks unicode characters according to python
has comment: http://stackoverflow.com/comment/85616982
has comment: http://stackoverflow.com/comment/85616903
score: 1
has answer: http://stackoverflow.com/a/60294381
answer count: 1
has comment: http://stackoverflow.com/comment/85617243
downvote count: 1
has comment: http://stackoverflow.com/comment/85618854
favorite count: 0
has comment: http://stackoverflow.com/comment/85616933
type: Question
has comment: http://stackoverflow.com/comment/85617139
has comment: http://stackoverflow.com/comment/85617047
has comment: http://stackoverflow.com/comment/85617003
upvote count: 2
has comment: http://stackoverflow.com/comment/85617072
has comment: http://stackoverflow.com/comment/85616931
has comment: http://stackoverflow.com/comment/85616873
has body: I'm trying to use triple quotes to designate a large comment, but I'm getting a new error that says SyntaxError: invalid string (possibly contains a unicode character) on line 2 Here's the code. """ Write a program that asks the user how many names they have. (If they have a first name, two middle names, and a last name, for example, they would type 4.) Then, using a for loop, ask the user for each of their names. Finally, print their full name. """ The triple quotes that I'm having a problem with are the ones at the top. With that information out of the way, my question is "Are triple quotation marks unicode characters according to python?" If this is a repeat post, feel free to move it.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85617039
has comment: http://stackoverflow.com/comment/85617018
tagged with: python

http://stackoverflow.com/comment/85712709
score: 0
type: Comment
type: QuestionComment
has text: Yes, the numbers must be unique.
comment on: http://stackoverflow.com/q/49356294

http://stackoverflow.com/q/49416470
score: 1
has answer: http://stackoverflow.com/a/49417686
has body: I'm adapting this tutorial here so I can train a ConvNet in my own set of images. So I made this function to try and get batches, though it does not create batches (yet): def training_batch(batch_size): images = trainpaths for i in range(len(images)): # converting the path to an image image = mpimg.imread(images[i]) images[i] = image # Create batches X, Y = images, trainlabels return X, Y And this function is called here: def optimize(num_iterations): global total_iterations for i in range(total_iterations, total_iterations + num_iterations): # Get a batch of training examples. # x_batch now holds a batch of images and # y_true_batch are the true labels for those images. x_batch, y_true_batch = training_batch(train_batch_size) # Put the batch into a dict with the proper names # for placeholder variables in the TensorFlow graph. feed_dict_train = {x: x_batch, y_true: y_true_batch} # Run the optimizer using this batch of training data. # TensorFlow assigns the variables in feed_dict_train # to the placeholder variables and then runs the optimizer. session.run(optimizer, feed_dict=feed_dict_train) (...) thing is if I run this if I run this code I get Traceback (most recent call last): File "scr.py", line 405, in &lt;module&gt; optimize(1) File "scr.py", line 379, in optimize session.run(optimizer, feed_dict=feed_dict_train) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 905, in run run_metadata_ptr) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1116, in _run str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (2034, 218, 178, 3) for Tensor u'x:0', which has shape '(?, 116412)' Can someone shine some light on how to fix this?
tagged with: python
has title: ValueError - Feeding an array of images into a dictionary
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49417686
has answer: http://stackoverflow.com/a/49417543
accepted answer: http://stackoverflow.com/a/49417543
tagged with: machine-learning
tagged with: dictionary
type: AnsweredQuestion
tagged with: conv-neural-network
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85744135
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49371536
type: AnswerComment
has text: I see - I guess I misunderstood how `after` worked. I will take another crack at it. I don't want `process_message` to ever stop, since the pause ends eventually. During the pause I just want `queue_message` to stop adding things to the queue. I have edited with a tweak to the pause_and_empty function based on your feedback. It seems to work as intended now. Can you confirm/deny?

http://stackoverflow.com/comment/86275549
has text: @Jean-FrançoisFabre - in my test with cmd.exe/notepad (xp-win10) this work well. of course can litle change code, for use instead apc completion, event completion in overlapped. but this not affect result
type: AnswerComment
comment on: http://stackoverflow.com/a/49631900
score: 0
type: Comment

http://stackoverflow.com/comment/85807234
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49401303
has text: But if I define tokens = self.ris.split("|") outside from testCode, in the classe Source. And then if I add token in testCode arguments. It does not work. Is it normal ?
score: 0

http://stackoverflow.com/comment/85697309
has text: Two adjacent items or two any distinct items?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49348792

http://stackoverflow.com/q/49310303
possible better answer: http://stackoverflow.com/a/49311351
favorite count: 0
has body: I want to create a dataframe that has historical values with the values I calculated with. I have df1 as below: df1: A B 0 2.0 3.0` 1 4.0 6.0 2 6.0 9.0 I calculated mean of df1 as below: m1 = df1.mean(axis=0) m1: A 4.0 B 6.0 'm1' is mean of entire data series from 0 to 2 (index). Instead of getting m1, what I want is to get a dataframe of mean for historical period. For example, I want to get mean value of every two periods (two consecutive indexes) and create them as a dataframe. The output I want is as below: # I want mean of two consecutive periods of each column as below. df2: A B 0 3.0 4.5 1 5.0 7.5 Can you help me on this? Thanks.
type: Question
has title: How to create a historical dataframe with calculated data?
has answer: http://stackoverflow.com/a/49310331
has answer: http://stackoverflow.com/a/49311351
answer count: 2
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49310331
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python

http://stackoverflow.com/q/49401124
tagged with: parquet
answer count: 0
has comment: http://stackoverflow.com/comment/85805283
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85838831
has comment: http://stackoverflow.com/comment/85809154
upvote count: 1
tagged with: google-bigquery
favorite count: 0
has comment: http://stackoverflow.com/comment/85812475
type: Question
has comment: http://stackoverflow.com/comment/85810655
has body: I have a Bigquery table of the following format: "Device", "t", "BedOccupancy", and "Raw". The table consists of ~300,000 lines and is intended for millions in the future. See example here: Each line in the table corresponds to a second of a bed-mounted sensor measurements. The field "Raw" contains the sensor data which are 1000 integers encoded as comma-separated values in one long string. When I query the table for selecting fields other than "Raw", results are good, for example: SELECT Device, t FROM [table:table1.RawData] WHERE BedOccupancy == 1 ORDER BY t But when I also SELECT "Raw" field, I get the following error: Resources exceeded during query execution: The query could not be executed in the allotted memory.. Any ideas how to tackle this? UPDATE #1: Also without the "order by t", when I SELECT all four fields, I get the following error: Response too large to return It seems the "Raw" field is doing a hard time for BigQuery. Is there a more efficient way of storing these 1000 values per each line? I don't need to query them, just keep the whole chunk of values per each line.
has comment: http://stackoverflow.com/comment/85805860
has comment: http://stackoverflow.com/comment/85844147
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85806429
has title: BigQuery resources exceeded error
tagged with: python
has comment: http://stackoverflow.com/comment/86071819
has comment: http://stackoverflow.com/comment/85804884

http://stackoverflow.com/a/61513746
score: -2
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/49436155
has body: Are you using the windows command prompt or the anaconda bash prompt? You can enter into a conda env with a windows command prompt but it will not let you create a new notebook. If you go to "anaconda prompt" from the programs menu and go into "bash" you get permissions
type: Answer

http://stackoverflow.com/q/49299808
upvote count: 5
tagged with: swagger
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/68376312
tagged with: client
has answer: http://stackoverflow.com/a/68376312
type: Question
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/49308552
has title: How do I get the Swagger-generated Python client to work?
has answer: http://stackoverflow.com/a/49308552
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
has body: I have generated the python client and server from https://editor.swagger.io/ - and the server runs correctly with no editing, but I can't seem to get the client to communicate with it - or with anything. I suspect I'm doing something really silly but the examples I've found on the Internet either don't work or appear to be expecting that I understand how to craft the object. Here's my code (I've also tried sending nothing, a string, etc): import time import swagger_client import json from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: petstore_auth swagger_client.configuration.access_token = 'special-key' # create an instance of the API class api_instance = swagger_client.PetApi() d = '{"id": 0,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"], "tags": [ { "id": 0, "name": "string" } ], "status": "available"}' python_d = json.loads(d) print( json.dumps(python_d, sort_keys=True, indent=4) ) body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store try: # Add a new pet to the store api_instance.add_pet(body) except ApiException as e: print("Exception when calling PetApi-&gt;add_pet: %s\n" % e) I'm using python 3.6.4 and when the above runs I get: Traceback (most recent call last): File "petstore.py", line 14, in &lt;module&gt; body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 69, in __init__ self.name = name File "/Users/bombcar/mef/petstore/python-client/swagger_client/models/pet.py", line 137, in name raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 ValueError: Invalid value for `name`, must not be `None` I feel I'm making an incredibly basic mistake, but I've literally copied the JSON from https://editor.swagger.io/ - but since I can't find an actually working example I don't know w…

sympy
tags question: http://stackoverflow.com/q/49351180
tags question: http://stackoverflow.com/q/49398913
tags question: http://stackoverflow.com/q/49288714
tags question: http://stackoverflow.com/q/49367869
tag name: sympy
tags question: http://stackoverflow.com/q/49306092
tags question: http://stackoverflow.com/q/49320273
type: Tag
tags question: http://stackoverflow.com/q/49292151
tags question: http://stackoverflow.com/q/49330548
tags question: http://stackoverflow.com/q/49393692

http://stackoverflow.com/comment/85733560
score: 0
comment on: http://stackoverflow.com/q/49366378
type: Comment
has text: I understand. But if I want to have alternative implementation what can it be? How can I achieve such a result?
type: QuestionComment

http://stackoverflow.com/q/49350385
accepted answer: http://stackoverflow.com/a/49351366
downvote count: 0
has title: Improve performance mapping certain elements within a dataframe based on other values
has answer: http://stackoverflow.com/a/49351366
answer count: 1
favorite count: 0
has body: I have a large csv sheet containing data along the lines of the following: clients id products type1 type2 value_x value_y 0 bob 111 pen A X 100 5 1 zoe 112 glue A Y 33 3 2 alex 113 glue B Y 50 1 3 alex 114 pen A X 100 5 4 bob 115 pen B Y 70 1 My goal is to map comparable ids from each client within a new dataframe that would look like this: bob zoe alex id 111 111 NaN 114 112 NaN 112 NaN 113 NaN NaN 113 114 111 NaN 114 115 115 NaN NaN I map these ids by comparing the fields products, type1, type2, value_x, value_y. The only issue is that I am currently doing this by iterating through every row, which takes about 30 min due to the size of the real dataframe. Furthermore, while the values for products, type1, and type2 are fixed, value_x and value_y can contain a degree of tolerance which I would set with df.value_x.between(lower, upper)(not in my example below for simplicity). Is there a way to speed up this process, or some other way of mapping these comparable values? code used: data = {'type1': ['A', 'A', 'B', 'A', 'B'], 'type2': ['X', 'Y', 'Y', 'X', 'Y'], 'value_x': [100, 33, 50, 100, 70], 'value_y': [5, 3, 1, 5, 1], 'clients': ['bob', 'zoe', 'alex', 'alex', 'bob'], 'id': ['111', '112', '113', '114', '115'], 'products': ['pen', 'glue', 'glue', 'pen', 'pen']} df = pd.DataFrame(data) df_mapped = pd.DataFrame(index=df.id, columns=df.clients.unique()) for row in df.itertuples(): row_client = row[1] row_id = row[2] row_product = row[3] row_type1 = row[4] row_type2 = row[5] row_value_x = row[6] row_value_y = row[7] for client in df_mapped.columns: try: comparable_id = df[(df.clients == client) &amp; (df.type1 == row_type1) &amp; (df.type2 == row_type2) &amp; (df.value_x == row_value_x) &amp; (df.value_y == row_value_y) &amp; (df.products == row_product)]['id'].iloc[0] except IndexError: comparable_id = np.nan df_mapped.loc[row_id, client] = comparable_id print df_mapped
tagged with: performance
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
tagged with: python-2.7
tagged with: pandas
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/49387718
has body: I've figured it out - these details only appear when pulling an invoice one by one or paginated in the line items column.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49382835

http://stackoverflow.com/comment/85976604
type: Comment
score: 0
type: AnswerComment
has text: can i contact you privat for more questions, because i think i dont understand Basic things and i dont want to spam here
comment on: http://stackoverflow.com/a/49412681

http://stackoverflow.com/a/49395852
has comment: http://stackoverflow.com/comment/85793588
upvote count: 1
has comment: http://stackoverflow.com/comment/85794269
has body: I found the answer. math.sin() and presumably all other functions in the math module automatically run class-based input objects through float(), which checks for the special method Class.__float__(self). For instance, math.sin() also converts the following class: class Test: def __init__(self, x): self.x = x def __float__(self): return self.x math.sin(Test(1.0)) Interesting... Another dark corner of python.
has comment: http://stackoverflow.com/comment/85793746
answers question: http://stackoverflow.com/q/49395851
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/57371635
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49360888
has body: You can load your data as numpy array (.npy format) and use flow method instead of flow_from_directory. Colab provides 25GB RAM ,so even for big data-sets you can load your entire data into memory. The speed up was found to be aroud 2.5x, with the same data generation steps!!! (Even faster than data stored in colab local disk i.e '/content' or google drive. Since colab provides only a single core CPU (2 threads per core), there seems to be a bottleneck with CPU-GPU data transfer (say K80 or T4 GPU), especially if you use data generator for heavy preprocessing or data augmentation. You can also try setting different values for parameters like 'workers', 'use_multiprocessing', 'max_queue_size ' in fit_generator method ...
type: Answer
has comment: http://stackoverflow.com/comment/102501184
score: 2

http://stackoverflow.com/comment/85839691
comment on: http://stackoverflow.com/q/49419056
score: 0
has text: First, what is the problem you're trying to solve? Without running this code, there doesn't seem to be anything obviously wrong with it. If there's a bug somewhere, tell us what it is—does it raise an exception, or output different results than you expected? If there's a missing part that you don't know how to write, where is it missing, what is it supposed to do, and what are you stuck on?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85818541
comment on: http://stackoverflow.com/q/49408627
score: 0
type: Comment
type: QuestionComment
has text: Apparently you have a blank line at the end of the file. Either remove that line or add `if line.strip():` before splitting.

http://stackoverflow.com/q/49430178
has answer: http://stackoverflow.com/a/49430423
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49430659
has body: I'm using Tensorflow to generate a transformation matrix for a set of input vectors (X) to target vectors (Y). To minimize the error between the transformed input and the target vector samples I'm using a gradient descent algorithm. Later on I want to use the generated matrix to transform vectors coming from the same source as the training input vectors so that they look like the corresponding target vectors. Linear regression, pretty much, but with 3-dimensional targets. I can assume that the input and target vectors are in cartesian space. Thus, the transformation matrix should consist of a rotation and a translation. I'm working solely with unit vectors, so I can also safely assume that there's no translation, only rotation. So, in order to get a valid rotation matrix that I can turn into a rotation quaternion I understand that I have to make sure the matrix is orthogonal. Thus, the question is, is it possible to give Tensorflow some kind of constraint so that the matrix it tries to converge to is guaranteed to be orthogonal? Can be a parameter, a mathematical constraint, a specific optimizer, whatever. I just need to make sure the algorithm converges to a valid rotation matrix.
tagged with: tensorflow
favorite count: 0
type: Question
has title: Is it possible to force Tensorflow to generate orthogonal matrix?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85578951
has text: @PaulCornelius indeed
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49287707

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49316327
tags question: http://stackoverflow.com/q/49401840
tags question: http://stackoverflow.com/q/49280168
tags question: http://stackoverflow.com/q/49394039
tags question: http://stackoverflow.com/q/49302478
tags question: http://stackoverflow.com/q/49286614
tags question: http://stackoverflow.com/q/49371790
tags question: http://stackoverflow.com/q/49285187
tags question: http://stackoverflow.com/q/49381132
tags question: http://stackoverflow.com/q/49301699
tags question: http://stackoverflow.com/q/49357893
tags question: http://stackoverflow.com/q/49380416
tags question: http://stackoverflow.com/q/49287794
tags question: http://stackoverflow.com/q/49341267
tags question: http://stackoverflow.com/q/49288731
tags question: http://stackoverflow.com/q/49431528
tags question: http://stackoverflow.com/q/49414976
tags question: http://stackoverflow.com/q/49414862
tags question: http://stackoverflow.com/q/49313301
tags question: http://stackoverflow.com/q/49323188
tags question: http://stackoverflow.com/q/49435647
tags question: http://stackoverflow.com/q/49347266
tags question: http://stackoverflow.com/q/49428252
tags question: http://stackoverflow.com/q/49358581
tags question: http://stackoverflow.com/q/49285546
type: Tag

http://stackoverflow.com/a/59498385
upvote count: 2
answers question: http://stackoverflow.com/q/49414841
has body: found on other page. interpreter: python 3.8 cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") this solved issue for me. i was getting SIGSEGV with 2.7, upgraded my python to 3.8 then got different error with OpenCV. and found answer on OpenCV 4.0.0 SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set. but eventually one line of code fixed it.
downvote count: 3
type: Answer
score: -1

http://stackoverflow.com/q/49430498
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49430576
has comment: http://stackoverflow.com/comment/85863064
has title: print function is from which module
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49430563
has body: As a beginner, what I understood is that Python Standard Library (PSL) provides a lot of modules which provide a lot of functionalities, but still if I want to use those then I have to import the module, for example, sys, os etc. are PSL modules but still those need to be imported. Now, I wonder if that is the case then how without importing anything I am able to use functions like print, list, len etc.? Is it that their "support is built-in into the interpreter"?
possible better answer: http://stackoverflow.com/a/49430589
has comment: http://stackoverflow.com/comment/85862695
type: Question
has answer: http://stackoverflow.com/a/49430589
has answer: http://stackoverflow.com/a/49430576
has comment: http://stackoverflow.com/comment/85862842
score: 5
upvote count: 5
answer count: 3
linked to: http://stackoverflow.com/q/49416732
favorite count: 0
has comment: http://stackoverflow.com/comment/85862724

http://stackoverflow.com/comment/85917469
type: Comment
type: QuestionComment
has text: Iteration is very pythonic; that's how lists are processed all the time. MATLAB used to require 'vectorization' in the same sense as `numpy`; but they've since added `jit` compilation, that reduces the need to think in terms of whole arrays. ``numba` and `cython` can be used to the same effect.
comment on: http://stackoverflow.com/q/49434319
score: 0

http://stackoverflow.com/comment/85616258
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49307004
score: 0
has text: The only thing different between those two snippets is that in the second one you are inserting `size` spaces, correct? Can you explain the logic behind using `size =(num_rows + 3)`?

http://stackoverflow.com/q/49360617
upvote count: 0
tagged with: machine-learning
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49361424
type: Question
linked to: http://stackoverflow.com/q/11952706
has body: I am working on dataset with more than 230 variables among which I have about 60 categorical var with more than 6 six levels (no way to make preference ordering, example: Color) My question is about any function that can help me to recode these variables without doing it by hand which requires a lot of work and time with a risk to make many mistakes! I can work with R and python, so feel free to suggest the most efficient function that can do the job. let's say, I have the dataset called df and the set of factorial columns is clm=(clm1, clm2,clm3,....,clm60) all of them are factors with a lot of levels: (min=2, max=not important [may be 10, 30 or 100...etc]) Your help is much appreciated!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85721500
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85721591
linked to: http://stackoverflow.com/q/12843456
has answer: http://stackoverflow.com/a/49363877
tagged with: http://stackoverflow.com/tag/r
has title: Recoding factor variables with a lot of levels into dummies?
has comment: http://stackoverflow.com/comment/85721422
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49360769

http://stackoverflow.com/comment/85820710
has text: emmet02, you're right, the index was off for the last row in the existing was different. Thanks!
comment on: http://stackoverflow.com/q/49409350
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85798375
type: Comment
score: 0
has text: Anyway: (1) It's not an operator here, it's [keyword splatting, part of the function call syntax](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists0. They're no more the same thing than the parentheses around the tuple `(1, 2)`, the parentheses around the subexpression in `2 * (3 + 4)`, and the parentheses in the function call `spam(42)` are the same thing.
type: QuestionComment
comment on: http://stackoverflow.com/q/49398463

http://stackoverflow.com/q/49427002
has title: pythonic way to manipulate nested dict from dotted path?
upvote count: 3
tagged with: nested
has comment: http://stackoverflow.com/comment/85855391
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85855574
has answer: http://stackoverflow.com/a/60627359
has answer: http://stackoverflow.com/a/49427967
has comment: http://stackoverflow.com/comment/117040193
accepted answer: http://stackoverflow.com/a/49427712
tagged with: python
answer count: 6
tagged with: dictionary
has answer: http://stackoverflow.com/a/49427714
has answer: http://stackoverflow.com/a/76147690
has answer: http://stackoverflow.com/a/49427712
possible better answer: http://stackoverflow.com/a/60627359
has comment: http://stackoverflow.com/comment/85859261
has body: I have a nested dictionary, an encryption function and a dotted path, I want to apply my encryption function to encrypt specific field. Example: mydict {"a":{ ... "b":{ ... "c":"value" } } } field path: a.b.c I want to execute encryption function on c value and modify my dict. What's the most efficent and pythonic way?
score: 2
has answer: http://stackoverflow.com/a/49427178

http://stackoverflow.com/q/49330698
possible better answer: http://stackoverflow.com/a/49331051
has answer: http://stackoverflow.com/a/49331051
has comment: http://stackoverflow.com/comment/85664035
has comment: http://stackoverflow.com/comment/86009236
tagged with: python
has comment: http://stackoverflow.com/comment/85663494
type: AnsweredQuestion
has title: Return Line exporting in .txt
answer count: 2
upvote count: 2
score: 1
has body: I try to generate 300k urls with python in a text file: with open(r'somefile.txt') as f_out: for i in range(100, 120): f_out.write(r'www.website.com/{}\n'.format(i)) But the result is: www.website.com/ 101www.websitecom/ 102www.website.com/ etc
has comment: http://stackoverflow.com/comment/85664002
accepted answer: http://stackoverflow.com/a/49330894
downvote count: 1
has comment: http://stackoverflow.com/comment/85673246
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49330894

http://stackoverflow.com/a/49631900
has comment: http://stackoverflow.com/comment/86276421
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86284717
downvote count: 0
has comment: http://stackoverflow.com/comment/86276938
has comment: http://stackoverflow.com/comment/86275549
answers question: http://stackoverflow.com/q/49408302
has comment: http://stackoverflow.com/comment/86284907
has comment: http://stackoverflow.com/comment/86276745
has comment: http://stackoverflow.com/comment/86277183
type: Answer
has comment: http://stackoverflow.com/comment/86285087
has body: if we not want let to child process process user input, but simply kill it in this case, solution can be next: start child process with redirected stdin to pipe. pipe server end we create in asynchronous mode and main set pipe buffer to 0 size before start child - write 1 byte to this pipe. because pipe buffer is 0 size - operation not complete, until another side not read this byte after we write this 1 byte and operation in progress (pending) - start child process. finally begin wait what complete first: write operation or child process ? if write complete first - this mean, that child process begin read from stdin - so kill it at this point one possible implementation on c++: struct ReadWriteContext : public OVERLAPPED { enum OpType : char { e_write, e_read } _op; BOOLEAN _bCompleted; ReadWriteContext(OpType op) : _op(op), _bCompleted(false) { } }; VOID WINAPI OnReadWrite(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, OVERLAPPED* lpOverlapped) { static_cast&lt;ReadWriteContext*&gt;(lpOverlapped)-&gt;_bCompleted = TRUE; DbgPrint("%u:%x %p\n", static_cast&lt;ReadWriteContext*&gt;(lpOverlapped)-&gt;_op, dwErrorCode, dwNumberOfBytesTransfered); } void nul(PCWSTR lpApplicationName) { ReadWriteContext wc(ReadWriteContext::e_write), rc(ReadWriteContext::e_read); static const WCHAR pipename[] = L"\\\\?\\pipe\\{221B9EC9-85E6-4b64-9B70-249026EFAEAF}"; if (HANDLE hPipe = CreateNamedPipeW(pipename, PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, 1, 0, 0, 0, 0)) { static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE }; PROCESS_INFORMATION pi; STARTUPINFOW si = { sizeof(si)}; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = CreateFileW(pipename, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 0, &amp;sa, OPEN_EXISTING, 0, 0); if (INVALID_HANDLE_VALUE != si.hStdInput) { char buf[256]; if (WriteFileEx(hPipe, "\n", 1, &amp;wc, OnReadWrite)) { si.hStdError = si.hStdOutput = si.hStdInput; if (CreateProcessW(lpApplicationName, 0, 0, 0, TRUE, CREATE…
score: 4
accepted answer of: http://stackoverflow.com/q/49408302
upvote count: 4
has comment: http://stackoverflow.com/comment/86276063
has comment: http://stackoverflow.com/comment/86273569
has comment: http://stackoverflow.com/comment/86276027

http://stackoverflow.com/a/49373981
has comment: http://stackoverflow.com/comment/85764359
score: 0
has body: This looks like a weird bug, probably arising from some opengl issue around binding the texture ids. Do Kivy apps from the play store have this kind of issue? And have you only run this in qpython? It might be interesting to try with Kivy master, as qpython's Kivy version may be (certainly used to be) quite old.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49352732
answers question: http://stackoverflow.com/q/49352732
type: Answer

http://stackoverflow.com/comment/85839928
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49419243
has text: `break` can only break **one** layer of loop.

http://stackoverflow.com/comment/85828461
has text: True. But that is your algorithm. You need to implement the remaining rules of Tic-tac-toe. I am merely allowing the possible the game board update to take place.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49389882

http://stackoverflow.com/comment/85780786
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49389555
score: 0
has text: Use proper indentation please

http://stackoverflow.com/q/49374120
has title: How to split a string by character by one or larger index
has answer: http://stackoverflow.com/a/49374160
tagged with: python
type: AnsweredQuestion
score: 0
has body: The split method for strings only takes a parameter for the delimiter, but how do I easily split by every (or every other, etc) letter? This method works to split by every letter, but seems clumsy for a simple task. a=' '.join(string.ascii_lowercase).split() I suppose a function could do this: def split_index(string,index=1): split=[] while string: try: sect = string[:index] string = string[index:] split.append(sect) except IndexError: split.append(string) return split print(split_index('testing')) # ['t', 'e', 's', 't', 'i', 'n', 'g'] print(split_index('testing',2)) # ['te', 'st', 'in', 'g'] I am surprised if no one has wished for this before, or if there is not a simpler built in method. But I have been wrong before. If such a thing is not worth much, or I have missed a detail, the question can be deleted/removed.
answer count: 2
accepted answer: http://stackoverflow.com/a/49374143
linked to: http://stackoverflow.com/q/312443
has comment: http://stackoverflow.com/comment/85749676
has answer: http://stackoverflow.com/a/49374143
has comment: http://stackoverflow.com/comment/85793135
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/312443
tagged with: split
possible better answer: http://stackoverflow.com/a/49374160
has comment: http://stackoverflow.com/comment/85793276

http://stackoverflow.com/a/49420122
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49419512
score: 1
has body: I do not think that it keeps moving in the same path. I tried running your code and it keeps giving the turtle a new forward amount and rotation. If you wait long enough it will eventually move from that spot. The reason it appears that it is not moving in the spot is that it keeps attempting to go to a new spot, but it has a very high chance of picking a random value which puts the turtle outside the screen bounds again. I would maybe guide the turtle to the opposite angle direction of the bounds if it goes outside the bounds because right now it is just repeatedly choosing random values.
upvote count: 1
has comment: http://stackoverflow.com/comment/85841706
has comment: http://stackoverflow.com/comment/85841778

http://stackoverflow.com/comment/85608627
has text: `sorted(word_count.items(), key=lambda x: x[1], reverse=True)`
comment on: http://stackoverflow.com/q/49303230
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49358578
has comment: http://stackoverflow.com/comment/85717161
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/42558133
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85717400
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/85717120
has comment: http://stackoverflow.com/comment/85717200
has comment: http://stackoverflow.com/comment/85717055
score: 0
answer count: 0
has body: I think my Python / PIP environment on a Ubuntu 16.04 machine is broken. I just want to install a program using PIP using this command: pip3 install --user ocrmypdf But it doesn't work. When running pip3 --version I get this error: Traceback (most recent call last): File "/usr/local/bin/pip3", line 7, in &lt;module&gt; from pip import main File "/usr/lib/python3/dist-packages/pip/__init__.py", line 59, in &lt;module&gt; from pip.log import logger File "/usr/lib/python3/dist-packages/pip/log.py", line 9, in &lt;module&gt; import colorama, pkg_resources File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 656, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 626, in _load_backward_compatible File "/usr/share/python-wheels/setuptools-3.3-py2.py3-none-any.whl/pkg_resources.py", line 1479, in &lt;module&gt; register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' Python itself seems to work: root@host /usr/lib # python -V Python 3.6.3
has title: Python / PIP broken on Ubuntu 16.04
has comment: http://stackoverflow.com/comment/85721069
tagged with: pip
has comment: http://stackoverflow.com/comment/85733300

http://stackoverflow.com/comment/85594280
comment on: http://stackoverflow.com/q/49295890
score: 0
has text: I already have the Frequent words stored in a list. I'll update the question with list F values @ManishSaraswat
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49382761
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/85767060
tagged with: radio-button
has comment: http://stackoverflow.com/comment/85767121
answer count: 1
has body: Please see that, I had referred to similar related answers too on this topics 1) What are the cases, that StringVar() / IntVar() would return blank / 0 value resp.? 2) Below is my smaller part of code applied to one of the functionalities in my app. Please do tell me what am I missing in my code to retrieve the expected output. from tkinter import * class App(Frame): def __init__(self,master): Frame.__init__(self,master) self.pack() Label(self,text="Choose timer options:").pack() self.delayvar = IntVar() self.delayradio1 = Radiobutton(self,text="Hours",variable=self.delayvar,value=1,command=self.delayfunc) self.delayradio1.pack() self.delayradio2 = Radiobutton(self,text="Minutes",variable=self.delayvar,value=2,command=self.delayfunc) self.delayradio2.pack() self.delayradio3 = Radiobutton(self,text="Seconds",variable=self.delayvar,value=3,command=self.delayfunc) self.delayradio3.pack() def delayfunc(self): self.delayvarvalue = self.delayvar.get() self.delayentryvar = StringVar() # or IntVar() self.delayent = Entry(self,textvariable=self.delayentryvar) self.delayent.pack() if self.delayvarvalue == 1: Button(self,text="save delay",command=self.delayfunc1).pack() self.delayentry = self.delayent.get() #self.delayentryvar.get() print(self.delayentry) def delayfunc1(self): self.delval = Text(self,height=1, width=10) self.delval.pack() self.delval.insert(END,self.delayentry) if __name__ == '__main__' : root = Tk() App(root) root.title("Delay Timer") root.geometry("200x200") root.mainloop()
tagged with: tkinter-entry
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/49383355
upvote count: 2
has comment: http://stackoverflow.com/comment/85766859
linked to: http://stackoverflow.com/q/47334885
type: UnansweredQuestion
has title: StringVar() / IntVar() not returning the value
downvote count: 2

http://stackoverflow.com/q/49304423
upvote count: 2
type: UnansweredQuestion
has title: How can I use Pillow (python library) in an R script?
downvote count: 0
tagged with: python
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
score: 2
has body: How can I use Pillow (python library) in an R script ? In this R Script the use of pillow is necessary for ... , but it throws an error at me ! ("The Pillow Python package is required to load images") Help needed .... library(keras) library(abind) # get some image img_path &lt;- system.file('extdata', 'produce.png', package = 'lime') # load a predefined image classifier model &lt;- application_vgg16(weights = "imagenet", include_top = TRUE) Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5 553467904/553467096 [==============================] - 273s 0us/step # create a function that prepare images for the model img_preprocess &lt;- function(x) { arrays &lt;- lapply(x, function(path) { img &lt;- image_load(path, target_size = c(224,224)) # &lt;-- this is what generates the error ! x &lt;- image_to_array(img) x &lt;- array_reshape(x, c(1, dim(x))) x &lt;- imagenet_preprocess_input(x) }) do.call(abind, c(arrays, list(along = 1))) } # Create an explainer (lime recognise the path as an image) explainer &lt;- lime(img_path, as_classifier(model, unlist(labels)), img_preprocess) # Explain the model (can take a long time depending on your system) explanation &lt;- lime::explain(img_path, explainer, n_labels = 2, n_features = 10, n_superpixels = 70) Error in image_load(path, target_size = c(224, 224)) : The Pillow Python package is required to load images But ho can I use the Python Pillow library in this R script ? Thank you for your attention.
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/85663937
has comment: http://stackoverflow.com/comment/85613289
type: Question
answer count: 0

http://stackoverflow.com/q/49324980
score: 0
accepted answer: http://stackoverflow.com/a/49325143
answer count: 1
has answer: http://stackoverflow.com/a/49325143
has title: Django : "detail": "Authentication credentials were not provided."
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85652036
has comment: http://stackoverflow.com/comment/85652086
has body: I'm using django rest framework. These are my settings for REST FRAMEWORK, REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ) # 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', # ), } When I post to a simple endpoint, I get the following error, { "detail": "Authentication credentials were not provided." } What am I doing wrong here. Any help appreciated.
tagged with: django
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49405243
tags question: http://stackoverflow.com/q/49407514
tags question: http://stackoverflow.com/q/49328148
tags question: http://stackoverflow.com/q/49418905
tags question: http://stackoverflow.com/q/49289835
tags question: http://stackoverflow.com/q/49383135
tags question: http://stackoverflow.com/q/49339025
tags question: http://stackoverflow.com/q/49432583
tags question: http://stackoverflow.com/q/49403664
tags question: http://stackoverflow.com/q/49349520
tags question: http://stackoverflow.com/q/49412383
tags question: http://stackoverflow.com/q/49288674
tags question: http://stackoverflow.com/q/49306186
tags question: http://stackoverflow.com/q/49363360
tags question: http://stackoverflow.com/q/49396765
tags question: http://stackoverflow.com/q/49431089
tags question: http://stackoverflow.com/q/49340467
tags question: http://stackoverflow.com/q/49283580
tags question: http://stackoverflow.com/q/49280265
tags question: http://stackoverflow.com/q/49406403
tags question: http://stackoverflow.com/q/49335486
tags question: http://stackoverflow.com/q/49423350
tags question: http://stackoverflow.com/q/49438074
tags question: http://stackoverflow.com/q/49386039
tags question: http://stackoverflow.com/q/49404977
tags question: http://stackoverflow.com/q/49431548
tags question: http://stackoverflow.com/q/49371264
tags question: http://stackoverflow.com/q/49417693
tags question: http://stackoverflow.com/q/49385525
tags question: http://stackoverflow.com/q/49334963
tags question: http://stackoverflow.com/q/49326873
tags question: http://stackoverflow.com/q/49401730
tags question: http://stackoverflow.com/q/49384161
tags question: http://stackoverflow.com/q/49414376
tags question: http://stackoverflow.com/q/49306741
tags question: http://stackoverflow.com/q/49404485
tag name: pyqt
tags question: http://stackoverflow.com/q/49307970
tags question: http://stackoverflow.com/q/49377049
tags question: http://stackoverflow.com/q/49306865
tags question: http://stackoverflow.com/q/49336469
tags question: http://stackoverflow.com/q/49416790
tags question: http://stackoverflow.com/q/49383369
tags question: http://stackoverflow.com/q/49304411
tags question: http://stackoverflow.com/q/49358862
tags question: http://stackoverflow.com/q/49421560
tags question: http://stackoverflow.com/q/49403638
tags question: http://stackoverflow.com/q/49309034
tags question: http://stackoverflow.com/q/49331513

http://stackoverflow.com/a/49410058
answers question: http://stackoverflow.com/q/49409766
type: Answer
has body: You can try below code to get required output: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver.get(link) links = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.LINK_TEXT, "LEIA ESTA EDIÇÃO"))) references = [link.get_attribute("href") for link in links]
has comment: http://stackoverflow.com/comment/85826842
score: 3
has comment: http://stackoverflow.com/comment/85825839
has comment: http://stackoverflow.com/comment/85823043
upvote count: 3
has comment: http://stackoverflow.com/comment/85823467
downvote count: 0
has comment: http://stackoverflow.com/comment/85823386
has comment: http://stackoverflow.com/comment/85826885
has comment: http://stackoverflow.com/comment/85825709

http://stackoverflow.com/comment/86279745
score: 1
type: Comment
type: AnswerComment
has text: GollyJer: Glad to hear that. One of your main take-ways from this is ought to be how the `grouper()` generator function, which is one of many given in the `itertools` module's [**Itertools Recipes**](https://docs.python.org/3/library/itertools.html#itertools-recipes) section, simplified solving the problem.
comment on: http://stackoverflow.com/a/49417272

http://stackoverflow.com/comment/85840364
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49419351
has text: Have you run the exact code you posted?
type: Comment

http://stackoverflow.com/q/49416776
has comment: http://stackoverflow.com/comment/85835706
tagged with: python
has comment: http://stackoverflow.com/comment/85835635
has title: Remove line through points in matplotlib plot
has body: I have the following matplotlib snippet: fig, ax = plt.subplots(figsize=(6,6)) values = np.random.normal(loc=0, scale=1, size=10) ax.plot(range(10), values, 'r^', markersize=15, alpha=0.4); which produces as planned. I'd like to make the line invisible where it overlaps with the points so that the points look more joined by the line rather than lying on top of the line. It is possible to do this by either making the line invisible where they overlap or to create a new line object that simply links the points rather than traces them? To be explicit, I do not want the entire line removed, just the sections that overlap with the points.
linked to: http://stackoverflow.com/q/4981815
has comment: http://stackoverflow.com/comment/85835543
has answer: http://stackoverflow.com/a/49417758
answer count: 2
has answer: http://stackoverflow.com/a/49426451
score: 1
tagged with: matplotlib
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85835988
type: Question
has comment: http://stackoverflow.com/comment/85836106
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85835700

http://stackoverflow.com/comment/85875582
score: 0
type: Comment
type: QuestionComment
has text: I'd pass a batch size to `numpy_input_fn` which divides your dataset evenly if it's important that the returned predictions have exactly the same number of elements (default is 128). You could also just trim away the repeated predictions (last 32).
comment on: http://stackoverflow.com/q/49389898

python-3.x
tags question: http://stackoverflow.com/q/49433693
tags question: http://stackoverflow.com/q/49361665
tags question: http://stackoverflow.com/q/49293905
tags question: http://stackoverflow.com/q/49343699
tags question: http://stackoverflow.com/q/49311839
tags question: http://stackoverflow.com/q/49404921
tags question: http://stackoverflow.com/q/49302514
tags question: http://stackoverflow.com/q/49418746
tags question: http://stackoverflow.com/q/49312557
tags question: http://stackoverflow.com/q/49351396
tags question: http://stackoverflow.com/q/49416170
tags question: http://stackoverflow.com/q/49419367
tags question: http://stackoverflow.com/q/49338242
tags question: http://stackoverflow.com/q/49396155
tags question: http://stackoverflow.com/q/49384111
tags question: http://stackoverflow.com/q/49403652
tags question: http://stackoverflow.com/q/49355589
tags question: http://stackoverflow.com/q/49304496
tags question: http://stackoverflow.com/q/49341670
tags question: http://stackoverflow.com/q/49332765
tags question: http://stackoverflow.com/q/49390202
tags question: http://stackoverflow.com/q/49325164
tags question: http://stackoverflow.com/q/49358578
tags question: http://stackoverflow.com/q/49386849
tags question: http://stackoverflow.com/q/49326259
tags question: http://stackoverflow.com/q/49352549
tags question: http://stackoverflow.com/q/49322891
tags question: http://stackoverflow.com/q/49286657
tags question: http://stackoverflow.com/q/49358826
tags question: http://stackoverflow.com/q/49327610
tags question: http://stackoverflow.com/q/49414693
tags question: http://stackoverflow.com/q/49371614
tags question: http://stackoverflow.com/q/49294578
tags question: http://stackoverflow.com/q/49308201
tags question: http://stackoverflow.com/q/49387871
tags question: http://stackoverflow.com/q/49352249
tags question: http://stackoverflow.com/q/49296780
tags question: http://stackoverflow.com/q/49381132
tags question: http://stackoverflow.com/q/49289575
tags question: http://stackoverflow.com/q/49286876
tags question: http://stackoverflow.com/q/49384233
tags question: http://stackoverflow.com/q/49287489
tags question: http://stackoverflow.com/q/49403677
tags question: http://stackoverflow.com/q/49339129
tags question: http://stackoverflow.com/q/49343908
tags question: http://stackoverflow.com/q/49380849
tags question: http://stackoverflow.com/q/49324988
tags question: http://stackoverflow.com/q/49364196
tags question: http://stackoverflow.com/q/49439055
tags question: http://stackoverflow.com/q/49379069
tags question: http://stackoverflow.com/q/49358650
tags question: http://stackoverflow.com/q/49314033
tags question: http://stackoverflow.com/q/49293306
tags question: http://stackoverflow.com/q/49396489
tags question: http://stackoverflow.com/q/49289685
tags question: http://stackoverflow.com/q/49327192
tags question: http://stackoverflow.com/q/49330548
tags question: http://stackoverflow.com/q/49417524
tags question: http://stackoverflow.com/q/49335183
tags question: http://stackoverflow.com/q/49354615
tags question: http://stackoverflow.com/q/49310922
tags question: http://stackoverflow.com/q/49391431
tags question: http://stackoverflow.com/q/49399374
tags question: http://stackoverflow.com/q/49307030
tags question: http://stackoverflow.com/q/49296346
tags question: http://stackoverflow.com/q/49324828
tags question: http://stackoverflow.com/q/49368730
tags question: http://stackoverflow.com/q/49415625
tags question: http://stackoverflow.com/q/49351509
tags question: http://stackoverflow.com/q/49396415
tags question: http://stackoverflow.com/q/49392396
tags question: http://stackoverflow.com/q/49311848
tags question: http://stackoverflow.com/q/49360709
tags question: http://stackoverflow.com/q/49412811
tags question: http://stackoverflow.com/q/49427936
tags question: http://stackoverflow.com/q/49327509
tags question: http://stackoverflow.com/q/49394396
tags question: http://stackoverflow.com/q/49343043
tags question: http://stackoverflow.com/q/49283439
tags question: http://stackoverflow.com/q/49309310

http://stackoverflow.com/q/49391687
tagged with: python
has answer: http://stackoverflow.com/a/49769098
has body: I was trying to display the status of processing to the user on the front end when I was using StreamingHttpResponse. I was able to get the current status but it is being appended to the previous one. I want the response template to contain only the current yield. views.py from django.shortcuts import render from django.http import StreamingHttpResponse,HttpResponse import time def f1(): x = 0 while x<5: time.sleep(1) x = x+1 code = """ {} """.format(x) yield code def home(request): return StreamingHttpResponse(f1()) output in the browser 1 2 3 4 expected output 1st: 1 2nd: 2 instead of 1 2 3rd: 3 instead of 1 2 3 4th: 4 instead of 1 2 3 4 instead of appending the previous yield I want the template to be filled with the current yield.
score: 12
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49400015
tagged with: python-requests
linked to: http://stackoverflow.com/q/7740646
has answer: http://stackoverflow.com/a/49400015
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/15116881
tagged with: python-3.x
upvote count: 12
has title: Render current status only on template in StreamingHttpResponse in Django
accepted answer: http://stackoverflow.com/a/49769098
tagged with: django

http://stackoverflow.com/q/49410722
has answer: http://stackoverflow.com/a/51459077
type: AnsweredQuestion
answer count: 2
linked to: http://stackoverflow.com/q/48792788
score: 1
has title: Monitoring on aws lambda
has comment: http://stackoverflow.com/comment/85823517
downvote count: 0
upvote count: 1
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49413692
possible better answer: http://stackoverflow.com/a/51459077
has body: My python3 lambda functions process records from dynamodb. I am printing every step of my lambda execution in cloudwatch. Now I am at a stage of deploying and monitoring my lambdas in production. Is there a way I can know which records are executed by lambda as a whole in consolidated way? I am also using X-ray to understand how much time and errors that my lambdas are taking. Besides, measuring the duration, invocation, errors. I want a way to know how many records are executed? thanks.
has answer: http://stackoverflow.com/a/49413692
tagged with: python

http://stackoverflow.com/comment/85681306
comment on: http://stackoverflow.com/a/49332132
score: 0
has text: I don't see anything in the comments concerning this setting, and trying to put it in my user settings as is or as a string causes errors.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85869523
comment on: http://stackoverflow.com/q/49433462
has text: I'm not sure what you need to know. You want to know the code to "get from ... to ...". Do you merely want to list the names of the new columns? See the code the encoder uses to generate new column names? "See the assignment" confuses the issue,as those columns are *not* "assigned to" the original columns; they are derived from the original columns, and no longer have a data-flow connection..
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49333662
has body: How to get the address of any hotel,restaurant,place,mall using python? I have already used geopy package which works for some specific places but not for all.Is there any other way out.
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
has title: Google search for address using python
has answer: http://stackoverflow.com/a/49333772
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85668953
favorite count: 0
type: Question

http://stackoverflow.com/a/49367347
has comment: http://stackoverflow.com/comment/85735718
has comment: http://stackoverflow.com/comment/85735792
has comment: http://stackoverflow.com/comment/85735514
has body: A couple of ways. Either use groupby and use count, or create a tuple column and apply value_counts. Both methods provide results that can be indexed via tuples. Setup import pandas as pd d = {'id': [1, 2, 1], 'service': [3, 4, 3], 'name': ['Joe', 'Bob', 'Mark']} df = pd.DataFrame(d) Groupby method As suggested by @Dark: res = df.groupby(['id', 'service']).count() # name # id service # 1 3 2 # 2 4 1 Tuple column method df['id_service'] = list(zip(df.id, df.service)) res = df['id_service'].value_counts() # (1, 3) 2 # (2, 4) 1 # Name: id_service, dtype: int64
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49367161
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49367161
type: AcceptedAnswer

http://stackoverflow.com/a/49383355
upvote count: 1
has comment: http://stackoverflow.com/comment/85767765
type: Answer
has comment: http://stackoverflow.com/comment/85770606
has body: "What are the cases, that StringVar() / IntVar() would return blank / 0 value resp.?" First of all, by return, I have to assume you mean the return of the get method on them, because if not, the answer is always and never(they always return None and that is not equal to 0) may vary respectively, as they ideally objects of the respective classes, or they fail to do so in which case I'd suspect they return None. The cases for the both of get methods return the respective values are the same, they're either never been set('' and 0 are their default values) or they're set explicitly to the default values. Below is my smaller part of code applied to one of the functionalities in my app. Please do tell me what am I missing in my code to retrieve the expected output. It's not obvious to me what your expected output would be but I can point some of the aspects of the code that looks troublesome. self.delayvar is instantiated exactly as it should be and is working correctly, whereas: self.delayentryvar currently serves no purpose, it is completely redundant. That is mainly because Entry object already has a get method that works exactly the same way as that of StringVar object's, hence if that's the heart of needing StringVar, then it has no use. self.delayent.get() and: self.delayentryvar.get() are practically the same thing as explained above and in the code OP provided will always return ''. That is because they're the returns of the current value of an Entry object that was first created almost an instant ago. The Entry isn't inserted anything either, hence they return None or ''. Add: self.delayent.insert('end', 'TEST') inside delayfunc somewhere before: self.delayentry = self.delayent.get() #self.delayentryvar.get() to have a better understanding of what's happening.
has comment: http://stackoverflow.com/comment/85767933
score: 1
answers question: http://stackoverflow.com/q/49382761
downvote count: 0

http://stackoverflow.com/a/49287160
downvote count: 0
score: 6
has body: You can always use csr internals: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy import sparse &gt;&gt;&gt; &gt;&gt;&gt; x = sparse.csr_matrix([[0, 1, 1], [2, 3, 0]]) &gt;&gt;&gt; &gt;&gt;&gt; x.data = x.data / np.repeat(np.add.reduceat(x.data, x.indptr[:-1]), np.diff(x.indptr)) &gt;&gt;&gt; x &lt;2x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 4 stored elements in Compressed Sparse Row format&gt; &gt;&gt;&gt; x.A array([[0. , 0.5, 0.5], [0.4, 0.6, 0. ]])
has comment: http://stackoverflow.com/comment/85579179
answers question: http://stackoverflow.com/q/49286903
has comment: http://stackoverflow.com/comment/85577412
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49286903
type: AcceptedAnswer

http://stackoverflow.com/a/49369212
has comment: http://stackoverflow.com/comment/85765738
has comment: http://stackoverflow.com/comment/85766097
has comment: http://stackoverflow.com/comment/85739500
accepted answer of: http://stackoverflow.com/q/49367406
has comment: http://stackoverflow.com/comment/85766942
has body: You have stumbled upon a file containing several non-conformities to the DICOM standard. The one that's most critical is the lack of a file meta header, which would include the file's transfer syntax. It also includes primitive identifier values (such as 15FDA64-7746-46CF-98DB-003CE051B9F3.5131.16754.61956), which are not valid UIDs (due to the presence of hyphens), along with some other inconsistencies. This makes it inevitable harder to manipulate using open, standard-conforming tools and libraries. Once a transfer syntax is unknown, external assumptions need to be made one way or another. But all is not lost in this particular case. The dcmdump tool, by detecting ExplicitVRLittleEndian as the transfer syntax, has managed to recover some attributes (some parts removed for brevity): # Dicom-File-Format # Dicom-Meta-Information-Header # Used TransferSyntax: Unknown Transfer Syntax # Dicom-Data-Set # Used TransferSyntax: Little Endian Explicit (0008,0018) UI [15FDA64-7746-46CF-98DB-003CE051B9F3.5131.16754.61956] # 52, 1 SOPInstanceUID [...] (0008,0060) CS [OCT] # 4, 1 Modality [...] (0028,0002) US 1 # 2, 1 SamplesPerPixel (0028,0004) CS [MONOCHROME2] # 12, 1 PhotometricInterpretation (0028,0010) US 240 # 2, 1 Rows (0028,0011) US 320 # 2, 1 Columns (0028,0034) IS [1\1] # 4, 2 PixelAspectRatio (0028,0100) US 8 # 2, 1 BitsAllocated (0028,0101) US 8 # 2, 1 BitsStored (0028,0102) US 7 # 2, 1 HighBit (0028,0103) US 0 # 2, 1 PixelRepresentation [...] (7fe0,0010) OW 0000\0c00\506a\2020\0a0d\0a87\0000\1800\7466\7079\706a\2078\0000... # 19404, 1 PixelData The necessary details to retrieve the pixel data appear to be present at first glance. However, the PixelData has a length of 19404 bytes, whereas a raw 320x240x1 bitmap would require 76800 bytes. This is where pydicom ultimately fails, as it attempts to read the pixel data as an uncompressed array of pixels. At this point we can assume that the image data is in some other encoding. Writing the DICOM element value to a separa…
has comment: http://stackoverflow.com/comment/85765352
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/85765880
answers question: http://stackoverflow.com/q/49367406
type: Answer
has comment: http://stackoverflow.com/comment/85765036
has comment: http://stackoverflow.com/comment/85765469
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49280281
has title: Get data out MySQL is very slow
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85563356
tagged with: mysql
has comment: http://stackoverflow.com/comment/85563467
has comment: http://stackoverflow.com/comment/85564297
has comment: http://stackoverflow.com/comment/85564082
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49281687
type: UnansweredQuestion
has body: I need to get some data from MySQL workbench into Python so I can make graphs. But when I try to insert it and try to print the values, this is with pymysql (see code). It runs very slow. So I think when I'm doing live graphs and more stuff the program will freeze... Does someone have a solution? My code: import pymysql conn= pymysql.connect(host='127.0.0.1', port= 3306, user= 'root', passwd= '******', db= 'energie' ) a = conn.cursor() sql1 = 'SELECT `VarValue`, `VarName` from `gasmeter1`;' a.execute(sql1) gasmeter1 = a.fetchone() sql2 = 'SELECT `VarValue` from `gasmeter2`;' a.execute(sql2) gasmeter2 = a.fetchone() sql3 = 'SELECT `VarValue` from `gasmeter349`;' a.execute(sql3) gasmeter349 = a.fetchone() sql4 = 'SELECT `VarValue` from `binnentemp ahu3010`;' a.execute(sql4) Binnentemperatuur = a.fetchone() sql5 = 'SELECT `VarValue` from `buiten temp241`;' a.execute(sql5) Buitentemperatuur = a.fetchone() print (gasmeter1[0] , gasmeter2[0] , gasmeter349[0] , Buitentemperatuur[0] , Binnentemperatuur[0]) It is just a simple code but it is very slow. Someone suggestions? Time: code: import pymysql import time conn= pymysql.connect(host='127.0.0.1', port= 3306, user= 'root', passwd= 'ohdecg', db= 'energie' ) a = conn.cursor() t1 = time.time() sql1 = 'SELECT `VarValue` from `gasmeter1`;' a.execute(sql1) gasmeter1 = a.fetchone () sql2 = 'SELECT `VarValue` from `gasmeter2`;' a.execute(sql2) gasmeter2 = a.fetchone () sql3 = 'SELECT `VarValue` from `gasmeter349`;' a.execute(sql3) gasmeter349 = a.fetchone () sql4 = 'SELECT `VarValue` from `binnentemp ahu3010`;' a.execute(sql4) Binnentemperatuur = a.fetchone() sql5 = 'SELECT `VarValue` from `buiten temp241`;' a.execute(sql5) Buitentemperatuur = a.fetchone() t2 = time.time() print("The SQL statement took : {} s".format(t2 - t1)) #print (gasmeter1[0] , gasmeter2[0], gasmeter349[0]) &gt;&gt;&gt; ========================= RESTART: C:\Python27\j.py ========================= The SQL statement took : 32.0269999504 s &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/85564322

http://stackoverflow.com/a/49427978
score: 0
accepted answer of: http://stackoverflow.com/q/49427372
type: Answer
has comment: http://stackoverflow.com/comment/85869378
has body: I hope this is what you want. testwebsitetendersaved="" #Table is very ugly formated in a span tag and tables within tables testwebsite_container = page_soup.find("span", id="MainContent2_ctl00_lblContent").findAll("table")[1] header="Tender Number, Description, Documents Link, Closing Date, Contact Details, Briefing"+"\n" file = open(os.path.expanduser("output.csv"), "wb") file.write(bytes(header, encoding="ascii",errors='ignore')) skiptrcnt=1 # skip first tr block for i,record in enumerate(testwebsite_container.findAll('tr')): if skiptrcnt&gt;i: continue testwebsitetender="" tnum = record('td')[0].text desc = record('td')[1].text doclink = record('td')[2].text alink = record('td')[2].find("a") if alink : doclinkurl=testwebsite+alink['href'] closingdate = record('td')[3].text detail = record('td')[4].text detail = detail.replace('\n', '') brief = record('td')[5].text brief = brief.replace('\n', '') print(tnum, desc, doclink, doclinkurl, closingdate, detail, brief) testwebsitetendersaved="{},{},{},{},{},{}\n".format(tnum, desc, doclink, doclinkurl, closingdate, detail, brief) file.write(bytes(testwebsitetendersaved, encoding="ascii",errors='ignore')) file.close() my output is 123456 text 123 Documents click here https://example.com/downloads/linktofile.zip 2 weeks me you next week 123456 text 123 Documents click here https://example.com/downloads/linktofile.zip 2 weeks me you next week 123456 text 123 Documents click here https://example.com/downloads/downloads/linktofile.zip 2 weeks me you next week 123456 text 123 Documents click here https://example.com/downloads/linktofile.zip 2 weeks me you next week 123456 text 123 Documents click here https://example.com/downloads/downloads/linktofile.zip 2 weeks me next week 123456 text 123 Documents click here https://example.com/downloads/linktofile.zip 2 weeks me next week
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85857513
answers question: http://stackoverflow.com/q/49427372
has comment: http://stackoverflow.com/comment/85883431

http://stackoverflow.com/q/49372279
has answer: http://stackoverflow.com/a/49372445
score: -1
has answer: http://stackoverflow.com/a/49372422
possible better answer: http://stackoverflow.com/a/49372422
has title: Factorial and Fibonacci functions work, but I can't get the third function to work
has comment: http://stackoverflow.com/comment/85745942
has comment: http://stackoverflow.com/comment/85747398
tagged with: factorial
type: AnsweredQuestion
downvote count: 2
answer count: 3
has body: def Factorial(n): n=int(input("Input a number?")) if n==0: return 1 else: return n * Factorial(n-1) def Fibonacci(num): i=0 present=1 previous=0 while i&lt;=num: nextterm=present+previous present=previous previous=nextterm i=i+1 print("The fibonacci number for", i, "is", nextterm) def CallFibOrFac(s): s=input('Fib or Fac?') if s == 'Fib': num=input('Up to what number?') print(Fibonacci(num)) elif s == 'Fac': n=input('What number?') print(Factorial(n)) CallFibOrFac() I've spent a lot of time trying to solve this assignment. I don't understand how I'm supposed to have my defined function CallFibOrFac call the other two functions for solving the Fibonacci or Factorial numbers. Any help/explanation is appreciated. Thanks! This is the exact prompt that I was left with in class: Write a Python program that has 3 Functions: The first function will be called CallFibOrFac It will receive a single string as a parameter. If the string is "Fib" it will call the second function called Fibonacci If the string is "Fac" it will call the third function called Factorial. The Second function prints the first 10 numbers in the Fibonacci sequence. The Third function prints the value of 10 factorial. We want to make the second and third functions work for cases other than just the first 10 numbers so add a parameter to the Fibonacci function and the Factorial function which will tell it how far to go along the Fibonacci sequence or the Factorial.
upvote count: 1
accepted answer: http://stackoverflow.com/a/49372445
has answer: http://stackoverflow.com/a/49372394
favorite count: 0
type: Question
tagged with: fibonacci
tagged with: function
tagged with: python

http://stackoverflow.com/a/49327632
type: Answer
answers question: http://stackoverflow.com/q/49327312
score: 0
has body: Where you currently have nunique, this is counting the number of unique values for each judge - but there are two possible values (1 and 2) and apparently they all have at least one vote of each kind. value_counts should give you roughly what you want: sc = pd.DataFrame([['a', 1], ['b', 2], ['b', 1], ['a', 1], ['a', 2], ['c', 1], ['b', 2], ['b', 1], ['b', 1], ['a', 2]]) sc.columns = ['justiceName', 'direction'] sc.groupby('justiceName')['direction'].value_counts().plot(kind='bar')

http://stackoverflow.com/q/49351121
tagged with: python-multiprocessing
type: Question
tagged with: gunicorn
upvote count: 2
tagged with: nginx
has answer: http://stackoverflow.com/a/49454711
has comment: http://stackoverflow.com/comment/85777472
has comment: http://stackoverflow.com/comment/85702557
linked to: http://stackoverflow.com/q/6011235
has body: I use the library multiprocessing in a flask-based web application to start long-running processes. The function that does it is the following: def execute(self, process_id): self.__process_id = process_id process_dir = self.__dependencies["process_dir"] self.fit_dependencies() process = Process(target=self.function_wrapper, name=process_id, args=(self.__parameters, self.__config, process_dir,)) process.start() When I want to deploy some code on this web application, I restart a service that restarts gunicorn, served by nginx. My problem is that this restart kills all children processes started by this application as if a SIGINT signal were sent to all children. How could I avoid that ? EDIT: After reading this post, it appears that this behavior is normal. The answer suggests to use the subprocess library instead. So I reformulate my question: how should I proceed if I want to start long-running tasks (which are python functions) in a python script and make sure they would survive the parent process OR make sure the parent process (which is a gunicorn instance) would survive a deployement ? FINAL EDIT: I chose @noxdafox answer since it is the more complete one. First, using process queuing systems might be the best practice here. Then as a workaround, I can still use multiprocessing but using the python-daemon context (see here ans here) inside the function wrapper. Last, @Rippr suggests using subprocess with a different process group, which is cleaner than forking with multiprocessing but involves having standalone functions to launch (in my case I start specific functions from imported libraries).
tagged with: python
linked to: http://stackoverflow.com/q/21665341
tagged with: flask
has title: Avoid killing children when parent process is killed
accepted answer: http://stackoverflow.com/a/49406652
has comment: http://stackoverflow.com/comment/115099615
has comment: http://stackoverflow.com/comment/85702129
linked to: http://stackoverflow.com/q/27624850
has answer: http://stackoverflow.com/a/49406652
has comment: http://stackoverflow.com/comment/114513021
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85702332
answer count: 3
has comment: http://stackoverflow.com/comment/85702242
possible better answer: http://stackoverflow.com/a/49487939
downvote count: 0
has answer: http://stackoverflow.com/a/49487939
favorite count: 0

http://stackoverflow.com/comment/85777029
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49387799
type: Comment
has text: Try to cast the filename to unicode: `file = file.decode('utf-8')`

http://stackoverflow.com/a/49419001
score: 2
has body: You've got it right. It's just showing the ASCII representation of the data as that's usually the more useful form &gt;&gt;&gt; s = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00(\x00\x00\x00(\x08\x02\x00\x00\x00\x03\x9c/:\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x01XIDATXG\xe5\xcd\xb1m\x031\x14\x04\xd1\xebF\xad\xb8+\xd5\xe0\x8a\xe5`f\x19|,.\xa0\x0fL\xf4\xc0h\x08.\xafo\xf5&gt;\xc8/a;\xc2/a;\xc2/a;\xc2/a;\xc2/a\x0b\xebC\x1c\r+la}\x88\xa3a\x85-\x88\xbf?\xff=p4\xac\xb0\x05q\xacl\x1c8\x1aV\xd8\x828V6\x0e\x1c\r+lA\x1c+\x1b\x07\x8e\x86\x15\xb6 \x8e\x95\x8d\x03G\xc3\n[\x10\xeb\xca\xbd\xfa\xc4\xd1\xb0\xc2\x16\xc4\xbar\xaf&gt;q4\xac\xb0\x05\xb1\xae|\xde\xafz\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xf7\xea\x13G\xc3\n[\x10\xeb\xca\xbd\xfa\xc4\xd1\xb0\xc2\x16\xc4\xb1\xb2q\xe0hXa\x0b\xe2X\xd98p4\xac\xb0\x05q\xacl\x1c8\x1aV\xd8\x828V6\x0e\x1c\r+lA\x1c+\x1b\x07\x8e\x86\x15\xb6\xb0&gt;\xc4\xd1\xb0\xc2\x16\xd6\x878\x1aV\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0\xcb/s]\x7f\xf8o$|7\xc4\xdf\xeb\x00\x00\x00\x00IEND\xaeB`\x82' &gt;&gt;&gt; s[0] 137 &gt;&gt;&gt; s[1] 80 &gt;&gt;&gt; s[2] 78 &gt;&gt;&gt; hex(s[0]) '0x89' &gt;&gt;&gt; hex(s[1]) '0x50' &gt;&gt;&gt; hex(s[2]) '0x4e' &gt;&gt;&gt; I don't think you'd need the UTF-8 decode step as this is just binary data right? If you actually want an ASCII representation of the data in hex form to match what you have in the question you could use &gt;&gt;&gt; ''.join('%02x' % c for c in s) '89504e470d0a1a0a0000000d4948445200000028000000280802000000039c2f3a000000017352474200aece1ce90000000467414d410000b18f0bfc6105000000097048597300000ec300000ec301c76fa86400000158494441545847e5cdb16d03311404d1eb46adb…
downvote count: 0
answers question: http://stackoverflow.com/q/49418929
upvote count: 2
type: Answer

http://stackoverflow.com/comment/85613507
has text: I don't use "ugly" syntax. But you are right that some people can mistakenly think that `and`/`or`/`in` also works.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49305440

http://stackoverflow.com/comment/85584152
comment on: http://stackoverflow.com/a/49290406
type: Comment
score: 0
has text: You are correct. This is what `break` does.. if you reach `True` you break the loop. Worst case is you get to the end of the string and nothing happens.
type: AnswerComment

http://stackoverflow.com/a/49316376
has body: cv-parser seems a bit old (last updated 5 years ago) so maybe it used an old version of pdfminer. Now there is no PDFParser class in pdfminer.pdfdocument (look up the code on Github), but this class is found in pdfminer.pdfparser. So I think you have two solutions: Revert to an older version of pdfminer Correct all import lines in cv-parser source code
type: Answer
answers question: http://stackoverflow.com/q/49316255
score: 0

http://stackoverflow.com/q/49361673
has body: Given my list of dictionaries dict_nomi = [ {'first_name': 'Luca', 'last_name': 'Rossi'}, {'first_name': 'Stefano', 'last_name': 'De Rosso'}, {'first_name': 'Luca', 'last_name': 'Bianchi'}, {'first_name': 'Luca', 'last_name': 'Rossi'}, ] I'd like to count the occurrences of values not by one key, but by multiple keys (two, in this case). def count_names(dict_nomi): names = Counter(v['first_name'] for v in dict_nomi if v.get('first_name')) for names, count in names.most_common(): print(names, count) count_names(dict_nomi) This gives me: ('Luca', 3) ('Stefano', 1) But how can I get something like ('Luca Rossi', 2) ('Stefano De Rosso', 1) ('Luca Bianchi', 1) this? Thanks.
has answer: http://stackoverflow.com/a/49362162
possible better answer: http://stackoverflow.com/a/49361729
has title: Count joined strings in dictionary values
has answer: http://stackoverflow.com/a/49361751
has answer: http://stackoverflow.com/a/49361729
type: Question
answer count: 5
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49361819
has answer: http://stackoverflow.com/a/49361734
accepted answer: http://stackoverflow.com/a/49361734
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85723452

http://stackoverflow.com/comment/85679086
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49339492
type: AnswerComment
has text: Also, you used the dictionary tag. Are you by chance trying to convert data from a list to a dictionary?

xpath
tags question: http://stackoverflow.com/q/49297380
tags question: http://stackoverflow.com/q/49352180
tags question: http://stackoverflow.com/q/49422219
tags question: http://stackoverflow.com/q/49302626
tags question: http://stackoverflow.com/q/49344639
tags question: http://stackoverflow.com/q/49402888
tags question: http://stackoverflow.com/q/49364202
tag name: xpath
tags question: http://stackoverflow.com/q/49308006
tags question: http://stackoverflow.com/q/49381342
type: Tag
tags question: http://stackoverflow.com/q/49409766
tags question: http://stackoverflow.com/q/49301335
tags question: http://stackoverflow.com/q/49364186
tags question: http://stackoverflow.com/q/49392693
tags question: http://stackoverflow.com/q/49432864
tags question: http://stackoverflow.com/q/49343677

http://stackoverflow.com/comment/85740015
score: 1
type: Comment
has text: @Ludo: See the [`assertRaises()` documentation](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises); the context manager stores the exception raised and you can then make further assertions on it.
type: AnswerComment
comment on: http://stackoverflow.com/a/49369203

http://stackoverflow.com/q/49426584
type: Question
has comment: http://stackoverflow.com/comment/85855314
has answer: http://stackoverflow.com/a/49426735
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/36272992
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85854157
has comment: http://stackoverflow.com/comment/85854477
linked to: http://stackoverflow.com/q/5040797
linked to: http://stackoverflow.com/q/976882
tagged with: numpy
tagged with: shuffle
has comment: http://stackoverflow.com/comment/85855251
linked to: http://stackoverflow.com/q/45437988
linked to: http://stackoverflow.com/q/36272992
tagged with: arrays
answer count: 1
downvote count: 0
has title: Shuffle independently within column of numpy array
has comment: http://stackoverflow.com/comment/85854450
has comment: http://stackoverflow.com/comment/85854392
upvote count: 1
has body: I have a numpy array of the format [[0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] ... [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.] [0. 0. 0. ... 0. 0. 0.]] Each column represents a data channel, and I need to shuffle the contents of each column within that column independently of the other channels. I understand that numpy.random.shuffle only shuffles along the first axis of the array ie. shuffles the order of rows within the array. What is the best way to carry out an independent shuffle within each column?
accepted answer: http://stackoverflow.com/a/49426735
has comment: http://stackoverflow.com/comment/85855530
has comment: http://stackoverflow.com/comment/85854565
favorite count: 0

http://stackoverflow.com/q/49422092
has comment: http://stackoverflow.com/comment/85844964
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49422182
has answer: http://stackoverflow.com/a/49422423
has title: How do I let users input any number of input values in Python?
linked to: http://stackoverflow.com/q/4663306
has answer: http://stackoverflow.com/a/49422165
tagged with: python
duplicate of: http://stackoverflow.com/q/4663306
score: 0
answer count: 3
has body: For example, if you wanted to accept say 2 input values it would be something like, x = 0 y = 0 line = input() x, y = line.split(" ") x = int(x) y = int(y) print(x+y) Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space. How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.

python-typing
tags question: http://stackoverflow.com/q/49427944
tags question: http://stackoverflow.com/q/49335263
type: Tag
tags question: http://stackoverflow.com/q/49360480
tags question: http://stackoverflow.com/q/49392845
tag name: python-typing
tags question: http://stackoverflow.com/q/49296843

makefile
tags question: http://stackoverflow.com/q/49370572
type: Tag
tag name: makefile
tags question: http://stackoverflow.com/q/49335880

http://stackoverflow.com/comment/85581716
type: Comment
type: QuestionComment
has text: fixed the indentation issues in my sample code
comment on: http://stackoverflow.com/q/49288730
score: 0

google-chrome
tags question: http://stackoverflow.com/q/49298245
type: Tag
tags question: http://stackoverflow.com/q/49367450
tags question: http://stackoverflow.com/q/49323099
tags question: http://stackoverflow.com/q/49371296
tag name: google-chrome
tags question: http://stackoverflow.com/q/49322339

http://stackoverflow.com/q/49300451
tagged with: bash
answer count: 1
tagged with: shell
type: Question
has body: Our environment has a shell script to setup the working area. setup.sh looks like this: export BASE_DIR=$PWD export PATH=$BASE_DIR/bin export THIS_VARIABLE=THAT_VALUE The user does the following: % . setup.sh Some of our users are looking for a csh version and that would mean having two setup files. I'm wondering if there is a way to do this work with a common python file. In The Hitchhiker's Guide to Python Kenneth Reitz suggests using a setup.py file in projects, but I'm not sure if Python can set environment variables in the shell as I do above. Can I replace this shell script with a python script that does the same thing? I don't see how. (There are other questions that ask this more broadly with many many comments, but this one has a direct question and direct single answer.)
has answer: http://stackoverflow.com/a/49300758
linked to: http://stackoverflow.com/q/716011
tagged with: python
has title: Setting Environment Up with Python
accepted answer: http://stackoverflow.com/a/49300758
has comment: http://stackoverflow.com/comment/85602794
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85860497
score: 0
has text: what is the point of your active_children and terminate loop? Could it be stuck there? If you join a child process, it will be removed from process table when the task is complete. Join takes already care of that. There should not be any subprocesses running at that time, so that part looks like it is obsolete anyway.
type: Comment
comment on: http://stackoverflow.com/q/49428431
type: QuestionComment

http://stackoverflow.com/comment/85794124
type: Comment
comment on: http://stackoverflow.com/q/49396094
has text: Did you try `PyObject * python_val = Py_BuildValue("s", s.c_str());` ?
type: QuestionComment
score: 5

http://stackoverflow.com/comment/85758356
comment on: http://stackoverflow.com/q/49378857
type: Comment
has text: The fact that superuser access can be made so easily - and I don't assume big websites like twitter or facebook would have them.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49335766
upvote count: 7
has comment: http://stackoverflow.com/comment/85674015
tagged with: python-asyncio
has title: Asyncio in Django
has comment: http://stackoverflow.com/comment/85673838
has body: I'm using a module that performs asyncio functions to obtain comments through scraping, the code works perfectly in Python scripts but Django does not seem to execute the Asyncio code. I get an error saying There is no current event loop in thread 'Thread-3'. def comments(request): if request.method == 'POST': async def main(): q = Query('Donald Trump', limit=20) async for tw in q.get_comments(): print(tw) loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) loop.run_until_complete(loop.shutdown_asyncgens()) finally: loop.close() form = CommentForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/index.html') else: form = CommentForm() return render(request, 'index.html', {'form': form}) With some dirty threading work with Asyncio inside of threads, I'm able to execute the loop, but only once.
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49341115
type: UnansweredQuestion
answer count: 1
score: 6
has comment: http://stackoverflow.com/comment/85672983
has comment: http://stackoverflow.com/comment/85673280
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85568732
score: 0
type: QuestionComment
type: Comment
has text: Do the points need to be "aligned" in some way, or is it okay if they are placed kinda randomly but with adequate densities?
comment on: http://stackoverflow.com/q/49282945

http://stackoverflow.com/comment/85837993
type: Comment
has text: YOU SHOULD put them into a dictionary as keys!
type: QuestionComment
comment on: http://stackoverflow.com/q/49415432
score: 0

http://stackoverflow.com/a/49401212
type: Answer
has body: Sure, MD5 is always 128 bytes, but sometimes the first byte is a 0, and occasionally the second byte is too. Think of it this way: the decimal string '15' and the decimal '0015' are both the same number 15. When you ask Python to convert the int 15 to a string, you're going to get '15', not '0015'. It has no way of knowing that you wanted 4 digits instead of 2: &gt;&gt;&gt; n = int('0015') &gt;&gt;&gt; str(n) '15' And it's the same with bin. It has no way of knowing that you wanted 128 bits instead of 126. You gave it a number with 126 bits, so it gives you 126 binary digits. But you can tell it you want that, e.g., with a format spec: bits = format(md5_bin, '0128b') … or, equivalently: bits = '{:0128b}'.format(md5_bin) If you want the 0b prefix, you can add that: bits = format(md5_bin, '#0128b') bits = '{md5_bin:#0128b}'.format(md5_bin) bits = '0b{md5_bin:0128b}'.format(md5_bin)
score: 9
answers question: http://stackoverflow.com/q/49401085
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49401085
upvote count: 9
has comment: http://stackoverflow.com/comment/85803728
has comment: http://stackoverflow.com/comment/85803694

http://stackoverflow.com/comment/85657045
type: Comment
type: QuestionComment
has text: My bad, i'm relatively new in conda and didn't get the concept at the beginning. Now I'm able to install the package from source. The purpose is using conda without connecting to internet.
score: 0
comment on: http://stackoverflow.com/q/49319808

http://stackoverflow.com/comment/85736004
has text: so basically, you are saying, that I could use the router as the third device, that will transmit data between two endpoints (machine A and B)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49367430
type: AnswerComment

http://stackoverflow.com/comment/85879015
type: Comment
type: QuestionComment
has text: I think you'll be able to increase the batch size if you "siamese" and concatenate before `avg_pool`, but I'm still a little confused: what shape do you expect the output to have?
score: 0
comment on: http://stackoverflow.com/q/49391386

http://stackoverflow.com/comment/85818899
type: Comment
type: QuestionComment
has text: Where are you displaying the data? But note that although you check the the form is valid, you don't tell the user if it isn't; or redirect away when it is. Presumably what's happening here that the form is indeed not valid.
comment on: http://stackoverflow.com/q/49408730
score: 0

http://stackoverflow.com/comment/85678338
has text: You will have much more luck if you post code and data so that we can replicate your results before making suggestions.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49339079

http://stackoverflow.com/q/49341905
tagged with: python
has comment: http://stackoverflow.com/comment/85683973
has comment: http://stackoverflow.com/comment/85684036
has body: How do services like Instabot perform UI driven actions from the terminal? Are they using some headless browser automation or some other technique? https://github.com/instabot-py/instabot.py
type: AnsweredQuestion
score: 0
has title: How does Instabot perform actions in the browser?
accepted answer: http://stackoverflow.com/a/49342279
answer count: 1
has answer: http://stackoverflow.com/a/49342279
tagged with: browser
type: Question

http://stackoverflow.com/a/49320382
type: Answer
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/118061079
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49320255
has body: You can use command, *values = input().split(' ') values is a list. For example the 'insert' part becomes: if command == 'insert': my_list.insert(int(values[0]), int(values[1]))
answers question: http://stackoverflow.com/q/49320255

http://stackoverflow.com/a/49410091
score: 2
answers question: http://stackoverflow.com/q/49409150
type: Answer
accepted answer of: http://stackoverflow.com/q/49409150
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Assuming a items are always in pairs, a simple approach would be as follows. Look at the first item - if it's an a, use it and the next item as a pair. Otherwise, just use the single item. Then 'jump' forward by 1 or 2, as appropriate: A=[(721,'a'),(765,'a'),(421,'a'),(422,'a'),(106,'b'),(784,'a'),(201,'a'),(206,'b'),(207,'b')] result = [] count = 0 while count &lt;= len(A)-1: if A[count][1] == 'a': result.append([A[count], A[count+1]]) count += 2 else: result.append([A[count]]) count += 1 print(result)

http://stackoverflow.com/q/49383044
tagged with: netcdf
downvote count: 0
has answer: http://stackoverflow.com/a/49383299
upvote count: 1
linked to: http://stackoverflow.com/q/222877
has title: Inheritance for custom class
favorite count: 0
type: Question
has body: I have a very large dataset in NetCDF4 format. Normally I would just read the variables I need and pass them as attributes to my custom class so I can create new methods for post processing. Since this dataset is so large, this is not an option as it throws a memory error. So I want to extend the attributes of the NetCDF4 Dataset instead. The following code illustrates what I'm trying to do: import netCDF4 class output(NetCDF4.Dataset): def __init__(self, path): super(NetCDF4.Dataset, self).__init__(path) print(self.variables) # Prints successfully def my_new_method(self): print(self.variables) # AttributeError: 'output' object has no attribute 'variables'
possible better answer: http://stackoverflow.com/a/49390748
tagged with: python
has answer: http://stackoverflow.com/a/49390748
type: AnsweredQuestion
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/49383299

http://stackoverflow.com/a/49344006
score: 1
has comment: http://stackoverflow.com/comment/85694904
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85699194
has body: dict.fromkeys is a class method, basically meaning it doesn't need to be attached to an instance of a dict class to work. This makes sense - dict.fromkeys is basically an alternative constructor for a dict. list.append on the other hand is a regular instance method, meaning we need an actual list instance to call .append on. This also makes sense - appending is an operation that does not precede the creation of a list, i.e. we need a list to append to. We can also reference instance methods as class attributes, and get back a regular function object that we pass an instance to as the first argument, i.e. list.append(some_list, 'foo').
type: Answer
answers question: http://stackoverflow.com/q/49343971

http://stackoverflow.com/a/76719778
score: 0
has body: Ran into the same problem with one specific DF after I concatenated a Pandas DF with two Pandas Series. Tried to use several variants of df.rename() listed below. None of them worked. # using column name and axis df = df.rename({'oldName1':'newName1', 'oldName2':'newName2'}, axis = 'columns') # using column index and axis df = df.rename({28:'newName1', 29:'newName2'}, axis = 'columns') # using column name df = df.rename(columns = {'oldName1':'newName1', 'oldName2':'newName2'}) # using column name and inplace function df.rename(columns = {'oldName1':'newName1', 'oldName2':'newName2'}, inplace = True) # using column index and inplace function df.rename(columns = {28:'newName1', 29:'newName2'}, inplace = True) Also tried above suggestion df.rename(columns={(28, 'newName1'): 'newName1'}, inplace = True, which did not work. What worked is this: df.columns.values[27]= 'newName1' This is of course not ideal as it needs to be done individually for each column. As I only had 2 columns to rename this is ok for me. If possible I recommend to use df.rename(), but if it just doesn't work this may be an alternative.
type: Answer
answers question: http://stackoverflow.com/q/49429646

http://stackoverflow.com/comment/85650081
score: 0
has text: When you signed up, you were encouraged to take the SO tour and study the Help section.In your case I suggest reading #1 of [What topics can I ask about here?](https://stackoverflow.com/help/on-topic) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49324062

http://stackoverflow.com/comment/85800077
score: 2
comment on: http://stackoverflow.com/q/49399439
type: QuestionComment
has text: It sounds like you're going to need a romanization library that can generate the various Latin-script equivalents of all strings in other scripts, or maybe even a more general transliteration library (so a katakana search can match English words). Unfortunately, SO is not a good place to ask for library recommendations. Maybe go to python.org's Community section, and see if there's a relevant-looking mailing list, and if not try the general python-list or the IRC channel.
type: Comment

http://stackoverflow.com/comment/85574265
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49281467
has text: Sorry, it must be a matter of words. I mean a widget can **contain** more than one layout, other than the widget's own one. Using children/parent relationship terminology about layouts can also be misleading, because they're not Qwidget subclasses.
type: Comment

http://stackoverflow.com/q/49299470
has comment: http://stackoverflow.com/comment/85600582
answer count: 1
tagged with: postman
tagged with: flask
favorite count: 0
type: Question
downvote count: 3
type: UnansweredQuestion
has title: None type json object after hosting in Apache server
score: -3
tagged with: http://stackoverflow.com/tag/json
tagged with: python
upvote count: 0
has body: I have a python script that is hosted on a python flask server. When I test it with postman by providing Json in the body of postman, I get very good response. But when I try using the same method after hosting the same script in apache server, I am getting a Nontype for my json.request. Please help, thanks in advance!
has answer: http://stackoverflow.com/a/49313244
tagged with: apache

http://stackoverflow.com/comment/85690959
has text: Check it out. It's art not a science.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49345583
type: Comment

http://stackoverflow.com/a/49384114
has comment: http://stackoverflow.com/comment/85769176
has body: In the last two lines you catch any exception: except: pass This includes the exception SystemExit, which is raised by sys.exit. To fix this, only catch exceptions deriving from Exception, which SystemExit does not: except Exception: pass In general, it's (almost) never a good idea to do a bare except, always catch Exception, or if possible, something more specific.
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49383977
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85769040
answers question: http://stackoverflow.com/q/49383977
upvote count: 5
type: Answer

python
tags question: http://stackoverflow.com/q/49325837
tags question: http://stackoverflow.com/q/49375093
tags question: http://stackoverflow.com/q/49427065
tags question: http://stackoverflow.com/q/49437589
tags question: http://stackoverflow.com/q/49396954
tags question: http://stackoverflow.com/q/49367052
tags question: http://stackoverflow.com/q/49298888
tags question: http://stackoverflow.com/q/49325027
tags question: http://stackoverflow.com/q/49379864
tags question: http://stackoverflow.com/q/49398152
tags question: http://stackoverflow.com/q/49281955
tags question: http://stackoverflow.com/q/49284466
tags question: http://stackoverflow.com/q/49371343
tags question: http://stackoverflow.com/q/49361673
tags question: http://stackoverflow.com/q/49365864
tags question: http://stackoverflow.com/q/49409124
tags question: http://stackoverflow.com/q/49307047
tags question: http://stackoverflow.com/q/49324970
tags question: http://stackoverflow.com/q/49363931
tags question: http://stackoverflow.com/q/49286456
tags question: http://stackoverflow.com/q/49383930
tags question: http://stackoverflow.com/q/49306865
tags question: http://stackoverflow.com/q/49290991
tags question: http://stackoverflow.com/q/49375609
tags question: http://stackoverflow.com/q/49321445
tags question: http://stackoverflow.com/q/49370756
tags question: http://stackoverflow.com/q/49374778
tags question: http://stackoverflow.com/q/49403119
tags question: http://stackoverflow.com/q/49317852
tags question: http://stackoverflow.com/q/49328447
tags question: http://stackoverflow.com/q/49327456
tags question: http://stackoverflow.com/q/49388365
tags question: http://stackoverflow.com/q/49298245
tags question: http://stackoverflow.com/q/49374064
tags question: http://stackoverflow.com/q/49377971
tags question: http://stackoverflow.com/q/49343473
tags question: http://stackoverflow.com/q/49365532
tags question: http://stackoverflow.com/q/49286100
tags question: http://stackoverflow.com/q/49282945
tags question: http://stackoverflow.com/q/49418376
tags question: http://stackoverflow.com/q/49406154
tags question: http://stackoverflow.com/q/49436026
tags question: http://stackoverflow.com/q/49347446
tags question: http://stackoverflow.com/q/49286473
tags question: http://stackoverflow.com/q/49388200
tags question: http://stackoverflow.com/q/49330459
tags question: http://stackoverflow.com/q/49282032
tags question: http://stackoverflow.com/q/49361068
tags question: http://stackoverflow.com/q/49371847
tags question: http://stackoverflow.com/q/49367525
tags question: http://stackoverflow.com/q/49395819
tags question: http://stackoverflow.com/q/49384449
tags question: http://stackoverflow.com/q/49375932
tags question: http://stackoverflow.com/q/49367586
tags question: http://stackoverflow.com/q/49310198
tags question: http://stackoverflow.com/q/49306351
tags question: http://stackoverflow.com/q/49419205
tags question: http://stackoverflow.com/q/49393780
tags question: http://stackoverflow.com/q/49402203
tags question: http://stackoverflow.com/q/49331945
tags question: http://stackoverflow.com/q/49403647
tags question: http://stackoverflow.com/q/49355489
tags question: http://stackoverflow.com/q/49353418
tags question: http://stackoverflow.com/q/49394628
tags question: http://stackoverflow.com/q/49347203
tags question: http://stackoverflow.com/q/49299033
tags question: http://stackoverflow.com/q/49336564
tags question: http://stackoverflow.com/q/49432135
tags question: http://stackoverflow.com/q/49305709
tags question: http://stackoverflow.com/q/49340762
tags question: http://stackoverflow.com/q/49282186
tags question: http://stackoverflow.com/q/49282487
tags question: http://stackoverflow.com/q/49300902
tags question: http://stackoverflow.com/q/49332300
tags question: http://stackoverflow.com/q/49371486
tags question: http://stackoverflow.com/q/49286784
tags question: http://stackoverflow.com/q/49393366
tags question: http://stackoverflow.com/q/49331892
tags question: http://stackoverflow.com/q/49439339
tags question: http://stackoverflow.com/q/49381679

http://stackoverflow.com/comment/85742736
has text: https://stackoverflow.com/questions/49370871/python-and-pandas-to-get-the-highs-and-lows
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49334898

http://stackoverflow.com/comment/85806634
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49402499
has text: any suggestion that you can make for gender? i chose 1 for male and 2 for female.

http://stackoverflow.com/comment/85769510
score: 0
type: Comment
type: AnswerComment
has text: Do you mean together with the other HTML (DjangoWeb/mysite/articles/templates/) or the CSS in the static folder (DjangoWeb/mysite/articles/static/)? If you want to see the full path of the project to have a clear view it is stored here: github.com/marcogdepinto/DjangoWeb .
comment on: http://stackoverflow.com/a/49349318

http://stackoverflow.com/comment/85797968
type: Comment
has text: try virtualenv..
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49397960

http://stackoverflow.com/q/49335263
type: Question
answer count: 2
tagged with: pycharm
has answer: http://stackoverflow.com/a/49335777
tagged with: contextmanager
tagged with: python
has answer: http://stackoverflow.com/a/56611439
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49335777
has title: How to properly annotate a ContextManager in PyCharm?
possible better answer: http://stackoverflow.com/a/56611439
downvote count: 0
score: 17
tagged with: python-typing
has body: How can I annotate the yield type of a contextmanager in PyCharm so that it properly guesses the type of the value used in the with clauses - just as it guesses that the f created in with open(...) as f is a file? For example, I have a context manager like this: @contextlib.contextmanager def temp_borders_file(geometry: GEOSGeometry, name='borders.json'): with TemporaryDirectory() as temp_dir: borders_file = Path(dir) / name with borders_file.open('w+') as f: f.write(geometry.json) yield borders_file with temp_borders_file(my_geom) as borders_f: do_some_code_with(borders_f...) How do I let PyCharm know that every borders_f created like this is a pathlib.Path (and thus enable the autocompletion for the Path methods on border_f)? Of course, I can make a comment like # type: Path after every with statement, but it seems that this can be done by properly annotating temp_border_file. I tried Path, typing.Iterator[Path] and typing.Generator[Path, None, None] as the return type of temp_border_file, as well as adding # type: Path on borders_file within the context manager's code, but it seems like it doesn't help.
favorite count: 0
upvote count: 17

http://stackoverflow.com/a/56769160
has comment: http://stackoverflow.com/comment/107746087
answers question: http://stackoverflow.com/q/49427944
has comment: http://stackoverflow.com/comment/112047438
has comment: http://stackoverflow.com/comment/108349421
type: Answer
upvote count: 22
score: 22
has body: You should go with Sequence from typing if you plan to use only list or tuple and access its elements by index, like x[0]. Sequence is both Sized and Iterable, see here.
downvote count: 0

http://stackoverflow.com/q/49316255
has body: I need to use a python cv_parser in my project . I have found one on Github, Github/cv-parser, so i downloaded it and i have open it with Pycharm. When i opened the project with pycharm 2017.3.4 it demand to install the required pakages , so i have downloaded and installed them with python setup.py install for each one. But , a package named pdfminer still have a problem after installing it; this is what the console return after compiling : File "C:/Users/GeeksData/Desktop/cv-parser-master/parsecv.py", line 14, in &lt;module&gt; from pdfminer.pdfdocument import PDFParser, PDFDocument ImportError: cannot import name PDFParser
has title: Github Cv_parser-pdfminer bugs
has answer: http://stackoverflow.com/a/49316376
score: 0
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: pdfminer
tagged with: python

http://stackoverflow.com/a/49437518
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49437457
has body: From the documentation it would appear to be close_preds['score'] = close_preds['pred'].apply(score_pred, args=(pred, scores)) I can't see what your close_pred_thresh is though. The score_pred needs two arguments.
type: Answer

http://stackoverflow.com/a/49323656
score: 29
upvote count: 29
answers question: http://stackoverflow.com/q/49323439
type: Answer
has body: Try it this way: df.loc[[0],'geometry'].plot() # ^ ^ Explanation: shapely.geometry.polygon.Polygon doesn't have .plot() method: In [19]: type(df.loc[0,'geometry']) Out[19]: shapely.geometry.polygon.Polygon geopandas.geoseries.GeoSeries does have .plot() method: In [20]: type(df.loc[[0],'geometry']) Out[20]: geopandas.geoseries.GeoSeries
accepted answer of: http://stackoverflow.com/q/49323439
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85774699
type: Comment
score: 0
type: AnswerComment
has text: oh.i misunderstood. store `json.dumps(csv_dict)` in a variable and use it further as above. remember it is JSON text. You may need to do some coding based on your need
comment on: http://stackoverflow.com/a/49371952

http://stackoverflow.com/comment/85755825
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49377049
has text: I am curious if we can create a list of all users without using an external file. Say if 'A' logs in list would have [ 'A']. If 'B' logs in the new list would be [ 'A','B'] etc.
type: Comment

http://stackoverflow.com/comment/85870272
score: 0
comment on: http://stackoverflow.com/a/49392389
type: Comment
has text: Could you please explain more about `w1,w2,w3 =args[0]` ? I can only understand `*arg` should take unlimited number of arguments.
type: AnswerComment

http://stackoverflow.com/comment/85596547
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49297206
type: Comment
has text: thanks! Now it looks fine. I just don't have intrinsic understanding of log so sometimes I don't know when to use the log scale

http://stackoverflow.com/comment/136222223
has text: I'm also looking for a way to update without performance degradation. Have you found any, sir?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49309631

http://stackoverflow.com/q/49422283
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85845775
has comment: http://stackoverflow.com/comment/85845887
type: Question
has comment: http://stackoverflow.com/comment/85845407
has answer: http://stackoverflow.com/a/49422704
has title: error ::sklearn.exceptions.NotFittedError: CountVectorizer - Vocabulary wasn't fitted
accepted answer: http://stackoverflow.com/a/49422704
has comment: http://stackoverflow.com/comment/85845962
answer count: 1
tagged with: scikit-learn
tagged with: python
has body: How do I solve the error here in vectorizor.tranform(fd_norm)? encoder = LabelEncoder() vectorizer = CountVectorizer() lis=[description] lis1=[name_predict] lis2=[text_predict] lis_df=pd.DataFrame(lis,columns=['description']) lis1_df=pd.DataFrame(lis1,columns=['name']) lis2_df=pd.DataFrame(lis2,columns=['text']) pred_df=pd.concat([lis_df,lis1_df,lis2_df],axis=1) fd=pred_df.iloc[ : , : ].values fd_norm=[normalize_text(s) for s in fd] predV=vectorizer.transform(fd_norm) fname='gender_predictor.sav' model=pickle.load(open(fname,'rb')) fresnel=model.predict(predV) fresnel_label=encoder.inverse_transform(fresnel) self.gender.setText(fresnel_label) the error: Traceback (most recent call last): File "the_linking.py", line 162, in predict predV=self._vectorizer.transform(fd_norm) File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 890, in transform self._check_vocabulary() File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 278, in _check_vocabulary check_is_fitted(self, 'vocabulary_', msg=msg), File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 690, in check_is_fitted raise _NotFittedError(msg % {'name': type(estimator).__name__}) sklearn.exceptions.NotFittedError: CountVectorizer - Vocabulary wasn't fitted.

http://stackoverflow.com/comment/85662348
comment on: http://stackoverflow.com/a/49322470
type: Comment
has text: How about `s=df1.merge(df2);s[s['PRICE']>s['SELLLING_PRICE']]`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85740013
has text: Why do you want to call that method in your template tag at all? What's the point?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49369241

http://stackoverflow.com/comment/85660232
type: AnswerComment
has text: Perfect! Worked for me. Changed it to with open('Example CARESCAPE Datalog.dat', 'rb') as binary_file:
score: 1
comment on: http://stackoverflow.com/a/49329105
type: Comment

http://stackoverflow.com/q/49375106
downvote count: 0
has answer: http://stackoverflow.com/a/49375137
accepted answer: http://stackoverflow.com/a/49375137
answer count: 1
tagged with: virtualenv
has title: Pipenv modules not found
favorite count: 0
type: Question
tagged with: pipenv
type: AnsweredQuestion
has body: I installed pipenv and then used pipenv install beautifulsoup4. My understanding is that this should have created a pipfile and a virtual env. So I started up pipenv shell. My pipfile is there, with Beautiful Soup there. Next thing I tried to do was pipenv install selenium. I wrote this really short script: from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Firefox() profile = 'https://www.linkedin.com/in/user-profile-name' driver.get(profile) html = driver.page_source soup = BeautifulSoup(html) print(soup) I tried running it and got this error: Traceback (most recent call last): File "LiScrape.py", line 2, in <module> from selenium import webdriver ModuleNotFoundError: No module named 'selenium' I tried running python3 in the shell and just doing import selenium to see if it would let me check the version. Again, I got the ModuleNotFoundError. What am I doing wrong with selenium that I didn't do wrong with beautiful soup??
linked to: http://stackoverflow.com/q/40208051
tagged with: python
score: 8
upvote count: 8
tagged with: python-3.x

http://stackoverflow.com/q/49393153
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49404516
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: 'price_and_currency' method in Python's Amazon Simple Product API returns "Decimal"
tagged with: amazon-product-api
score: 1
answer count: 1
has body: I'm calling the Amazon Product API using Amazon Simple Product API Module (Python): product = amazon.lookup(ItemId="B00H2VOSP8") When returning return str(product.price_and_currency) I get the following: (Decimal('149.95'), 'USD') The official documentation indicates I should be getting ('149.95', 'USD') How can I correct this?
upvote count: 1

http://stackoverflow.com/a/49403911
downvote count: 0
has comment: http://stackoverflow.com/comment/85808995
has comment: http://stackoverflow.com/comment/85809363
answers question: http://stackoverflow.com/q/49403845
type: Answer
accepted answer of: http://stackoverflow.com/q/49403845
has body: An MCVE would help here, but if I understand correctly, just use the numpy.array constructor. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arraylist = [np.array([1,2,3]), np.array([1,2,3])] &gt;&gt;&gt; arraylist [array([1, 2, 3]), array([1, 2, 3])] &gt;&gt;&gt; np.array(arraylist) array([[1, 2, 3], [1, 2, 3]])
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49333733
has answer: http://stackoverflow.com/a/49333791
score: 0
answer count: 2
has title: Python Pandas Combine two rows
tagged with: pandas
has answer: http://stackoverflow.com/a/49333846
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85669198
has body: I have a big dataset like following: There are so many rows like this format. Finding each NaN rows should base on the feature of NaN. In other words, these rows cannot be located directly df['Computer'] It needs find NaN first, and then return its row index to locate these rows. Therefore, I would like to get:

http://stackoverflow.com/q/49397019
has comment: http://stackoverflow.com/comment/85796720
has comment: http://stackoverflow.com/comment/85795881
tagged with: pyaudio
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86119703
has comment: http://stackoverflow.com/comment/85796112
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85815239
has title: Encountered an error trying Active Noise Reduction with Pyaudio
has body: I got this code from here. When I try to run it on Python (I am using Python 3.6) it encounters this error: runfile('C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT/SIGNLABPROJ.py', wdir='C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT') * recording C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT/SIGNLABPROJ.py:75: RuntimeWarning: invalid value encountered in true_divide obj = np.real(np.dot(avg_freq_buffer[1:51], np.abs(freq_synth[1:100:2])) / np.dot(freq_synth[1:100:2], np.conj(freq_synth[1:100:2]))) C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT/SIGNLABPROJ.py:76: RuntimeWarning: invalid value encountered in greater if obj &gt; obj_last: Traceback (most recent call last): File "&lt;ipython-input-1-3d1fe0eb2795&gt;", line 1, in &lt;module&gt; runfile('C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT/SIGNLABPROJ.py', wdir='C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT') File "C:\Users\vsecadesang\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\vsecadesang\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/vsecadesang/Desktop/5th year/2nd sem/SIGNLAB/PROJECT/SIGNLABPROJ.py", line 99, in &lt;module&gt; stream.write(string_audio_data, CHUNK) File "C:\Users\vsecadesang\Anaconda3\lib\site-packages\pyaudio.py", line 586, in write exception_on_underflow) KeyboardInterrupt I don't know exactly what's wrong, please help. Here are the codes below: import pyaudio import numpy as np import scipy.signal CHUNK = 1024*2 WIDTH = 2 DTYPE = np.int16 MAX_INT = 32768.0 CHANNELS = 1 RATE = 11025*1 RECORD_SECONDS = 20 j = np.complex(0,1) p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(WIDTH), channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK) print("* recording") # init…
tagged with: python

http://stackoverflow.com/a/49427495
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49427446
score: 1
has body: ranks = [1,2,3,4,5] suits = [10,11,12,13,14,15] deck = [] for rank in ranks: for suit in suits: deck.append(('%s%s')%(rank, suit)) deck_comp = [('%s%s')%(rank, suit) for rank in ranks for suit in suits] print(deck == deck_comp)
downvote count: 0

http://stackoverflow.com/q/49383797
has title: Pythonic way to extract region name from zone (AWS/GCloud)
tagged with: python
has answer: http://stackoverflow.com/a/49384063
accepted answer: http://stackoverflow.com/a/49384022
type: AnsweredQuestion
has body: I'm new to Python and I was wondering, what is the best way to extract the region's name from a zone name. For example: GCP: - us-east1-c - europe-west2-b AWS: - eu-west-2 - ap-northeast-1 In bash, I would use: echo "zone"|rev|cut -f2- -d-|rev" In Python, I used: '-'.join(zone.split('-')[:-1]), I know it doesn't really matter, but I would like to do it in the pythonic way. Thanks in advance! Oh, expected output is if zone is us-east1-b us-east1
tagged with: list
downvote count: 0
answer count: 3
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/49384063
has answer: http://stackoverflow.com/a/78607823
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49384022
has comment: http://stackoverflow.com/comment/85768771
tagged with: extract
has comment: http://stackoverflow.com/comment/85768638

http://stackoverflow.com/a/49437018
answers question: http://stackoverflow.com/q/49436833
has comment: http://stackoverflow.com/comment/134784476
has comment: http://stackoverflow.com/comment/134774162
has comment: http://stackoverflow.com/comment/134784887
score: 6
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/135245858
has body: They serve different purposes. lru_cache saves the least recent uses - you should specify maxsize which distinguishes how many computations of your function you can save. Once you surpass this number, the 'oldest' result is discarded and the new one is saved. cached_property just computes the result and saves it. It doesn't take arguments unlike lru_cache (you can think of it as a lru_cache on an object type with maxsize = 1 with no arguments).
type: Answer

http://stackoverflow.com/a/49422088
downvote count: 0
upvote count: 1
has body: You can not type cast string which contains dot which is causing error. Just remove type casting i.e. int() prior to input(). inet_aton() takes care of ip validation internally. code: import socket userip = input("enter ip addr") try: socket.inet_aton(userip) except socket.error: print("invalid ip")
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49421943

http://stackoverflow.com/a/49416181
answers question: http://stackoverflow.com/q/49415834
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85835407
has body: There are several ways to solve your problem. Since you want to use np.eye, maybe below solution could help. import numpy as np def matrix(n): x = np.eye(n) for i in range(n): x[i] = i + 1 return x.T def main(): n=3 print(matrix(n)) if __name__ == '__main__': main() Output [[ 1. 2. 3.] [ 1. 2. 3.] [ 1. 2. 3.]]
has comment: http://stackoverflow.com/comment/85835158

http://stackoverflow.com/a/49323178
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49322894
has body: One way is to convert to categories and use groupby to calculate Cartesian product. In fact, given your data is largely categorical, this is a good idea and would yield memory benefits for large number of Time-City-Day combinations. for col in ['Time', 'City', 'Day']: df[col] = df[col].astype('category') bin_cats = sorted(set(pd.Series(pd.to_datetime(np.arange(0, 86401, 600), unit='s'))\ .dt.round('10min').dt.strftime('%H:%M:%S'))) df['Time'] = df['Time'].cat.set_categories(bin_cats, ordered=True) res = df.groupby(['Time', 'City', 'Day'], as_index=False)['COUNT'].sum() res['COUNT'] = res['COUNT'].fillna(0).astype(int) # Time City Day COUNT # 0 00:00:00 ATLANTA Friday 521 # 1 00:00:00 ATLANTA Monday 767 # 2 00:00:00 ATLANTA Saturday 474 # 3 00:00:00 ATLANTA Sunday 1126 # 4 00:00:00 ATLANTA Thursday 157 # 5 00:00:00 ATLANTA Tuesday 720 # 6 00:00:00 ATLANTA Wednesday 0 # 7 00:00:00 CHICAGO Friday 1114 # 8 00:00:00 CHICAGO Monday 813 # 9 00:00:00 CHICAGO Saturday 137 # 10 00:00:00 CHICAGO Sunday 134 # 11 00:00:00 CHICAGO Thursday 0 # 12 00:00:00 CHICAGO Tuesday 168 # ..........

http://stackoverflow.com/comment/85651677
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49325097
has text: Yes i get that but how does it know to call the underlying function from what the name is nowhere else in the code?

http://stackoverflow.com/comment/85627745
score: 0
has text: @Jabir thanks, it was helpful, I didnt had to remove any header but just needed to add some
type: Comment
comment on: http://stackoverflow.com/q/49292192
type: QuestionComment

http://stackoverflow.com/q/49403965
tagged with: tf-slim
favorite count: 0
score: 2
tagged with: python
tagged with: tensorflow-estimator
type: Question
has body: I use nasnet.py from tf.slim with the High Level API of tf.estimator. The problem is that the allow growth parameter is not respected, i.e. the entire GPU memory is used Here is a condensed version of the code (only relevant parts): from lib.nasnet.nasnet import build_nasnet_mobile def model_fn(features, labels, mode, params): ... # build model (based on tf.slim) net_out, cells_out = build_nasnet_mobile( features, 2, is_training=mode == tf.estimator.ModeKeys.TRAIN) predictions = ... if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) loss = ... optimizer = tf.train.AdamOptimizer() update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(loss=loss, train_op=train_op, mode=mode) def main(): ... session_config = tf.ConfigProto() session_config.gpu_options.allow_growth = True session_config.allow_soft_placement = True config = tf.estimator.RunConfig(session_config=session_config) estimator = tf.estimator.Estimator(model_fn=model_fn, model_dir=model_dir, config=config) Is there full compatibility with training tf.slim defined networks with tf.estimator or do I have to use the high level API of tf.slim?
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has title: Compatibility of tf.estimator high level API with tf.slim network definition
tagged with: tensorflow

http://stackoverflow.com/q/49302516
score: 14
has comment: http://stackoverflow.com/comment/85650945
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/94528812
tagged with: dll
has comment: http://stackoverflow.com/comment/94419537
has comment: http://stackoverflow.com/comment/85645022
tagged with: python
has comment: http://stackoverflow.com/comment/94528626
has body: Note: This is not an issue with Visual Studio, but rather with incompatible dll versions. The steps below replicate the problem since running in Visual Studio in debug mode breaks on exceptions being thrown. If you just run, the thrown exception is handled elsewhere and the program works fine. But since I spend a lot of time in debug mode, I would prefer to fix this problem. When debugging, I want to be able to step into modules I have added to my Virtual Environment in Visual Studio. I get a 'library not found' error that I am not able to fix. Here are the steps: In Visual Studio create a new Python Application. Create a virtual environment for that application (Python 3.6 64 bit). pip install twilio into your virtual environment. You get the following output. ... ----- Installing 'twilio' ----- Collecting twilio Using cached twilio-6.10.5-py2.py3-none-any.whl Collecting pytz (from twilio) Using cached pytz-2018.3-py2.py3-none-any.whl Collecting six (from twilio) Using cached six-1.11.0-py2.py3-none-any.whl Collecting PyJWT&gt;=1.4.2 (from twilio) Using cached PyJWT-1.6.0-py2.py3-none-any.whl Collecting requests&gt;=2.0.0; python_version &gt;= "3.0" (from twilio) Using cached requests-2.18.4-py2.py3-none-any.whl Collecting pysocks; python_version &gt;= "3.0" (from twilio) Using cached PySocks-1.6.8.tar.gz Collecting certifi&gt;=2017.4.17 (from requests&gt;=2.0.0; python_version &gt;= "3.0"-&gt;twilio) Using cached certifi-2018.1.18-py2.py3-none-any.whl Collecting chardet&lt;3.1.0,&gt;=3.0.2 (from requests&gt;=2.0.0; python_version &gt;= "3.0"-&gt;twilio) Using cached chardet-3.0.4-py2.py3-none-any.whl Collecting urllib3&lt;1.23,&gt;=1.21.1 (from requests&gt;=2.0.0; python_version &gt;= "3.0"-&gt;twilio) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting idna&lt;2.7,&gt;=2.5 (from requests&gt;=2.0.0; python_version &gt;= "3.0"-&gt;twilio) Using cached idna-2.6-py2.py3-none-any.whl Installing collected packages: pytz, six, PyJWT, certifi, chardet, urllib3, idn…
has comment: http://stackoverflow.com/comment/85662251
tagged with: openssl
tagged with: python-3.x
upvote count: 15
tagged with: python-import
linked to: http://stackoverflow.com/q/23804438
answer count: 3
possible better answer: http://stackoverflow.com/a/49607725
accepted answer: http://stackoverflow.com/a/49594324
linked to: http://stackoverflow.com/q/19849077
linked to: http://stackoverflow.com/q/19019720
has answer: http://stackoverflow.com/a/49607725
has title: where to get and install crypto.dll on 64 bit Windows
has answer: http://stackoverflow.com/a/49594324
has answer: http://stackoverflow.com/a/55930971
has comment: http://stackoverflow.com/comment/94528608
has comment: http://stackoverflow.com/comment/85661614
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85566216
comment on: http://stackoverflow.com/q/49281664
has text: Are `X`, `y`, or `weights` growing as you train your model?
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49397599
answers question: http://stackoverflow.com/q/49354665
has body: I think stemming a lemmatized word is redundant if you get the same result than just stemming it (which is the result I expect). Nevertheless, the decision between stemmer and lemmatizer depends on your need. My intuition said that steamming increses recall and lowers precision and the opposite for a lemmatization. Consider this scores, what matter for your specific problem? Other option talking about this scores is to calculate F-1 score which is the harmonic average of the precision and recall.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85720855
has text: If you open a file with `w`, and then don't write anything to it, you will get an empty file. Any existing file contents are lost.
type: Comment
comment on: http://stackoverflow.com/a/49360080
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85786797
has text: That is true. You can search through different endings you can think of, but it is a flaw.
comment on: http://stackoverflow.com/a/49392002
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85640455
comment on: http://stackoverflow.com/a/49318098
score: 0
type: AnswerComment
type: Comment
has text: Yeah that's right. I only looked at the first part where the error seemed to be coming from.

http://stackoverflow.com/comment/85687861
type: AnswerComment
score: 2
has text: I think you want `len(mystr)+1` to not miss `'bell'`.
comment on: http://stackoverflow.com/a/49343731
type: Comment

http://stackoverflow.com/comment/85826723
type: QuestionComment
has text: line = `"YES, OF COURSE!WITHOUT A DOUBT, YESYOU CAN COUNT ON IT.FOR SURE!ASK ME LATERI AM NOT SUREI CAN'T TELL YOU RIGHT NOW?I WILL TELL YOU AFTER MY NAPNO WAY!I DON'T THINK SOWITHOUT A DOUBT, NO.THE ANSWER IS CLEARLY NO"` So of course, when you print line[0] you get `"Y"`
type: Comment
comment on: http://stackoverflow.com/q/49412349
score: 1

http://stackoverflow.com/comment/85584148
type: Comment
type: AnswerComment
has text: @abarnert chose to use `.extend()` because it seemed to be slightly faster than `.append()`. In this case it's small scale so its irrelevant I guess.
comment on: http://stackoverflow.com/a/49290453
score: 1

http://stackoverflow.com/comment/85670681
has text: @pynexj: Do you know how to do it in py3?
score: 0
comment on: http://stackoverflow.com/q/49334378
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49308370
has body: It is only capable of only handling one request at a time, because that is what you told mod_wsgi to do in using: threads=1 Don't set that option and it will instead default to 15 threads in the daemon process group and so that is how many requests it can handle concurrently. If your requests are I/O bound that should be fine to begin with and you can tune things later. If your requests are more CPU bound than I/O bound, start to introduce additional processes as well and distribute requests across them. processes=3 threads=5 Even if heavily I/O bound, do not increase threads too far per process, it is better to still spread them across processes as Python doesn't work as well with high number of threads per process. For more information read the documentation: http://modwsgi.readthedocs.io/en/develop/user-guides/processes-and-threading.html
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85621489
has comment: http://stackoverflow.com/comment/85621452
has comment: http://stackoverflow.com/comment/85619291
has comment: http://stackoverflow.com/comment/85620055
has comment: http://stackoverflow.com/comment/85619091
has comment: http://stackoverflow.com/comment/85621396
has comment: http://stackoverflow.com/comment/85619260
has comment: http://stackoverflow.com/comment/85621461
answers question: http://stackoverflow.com/q/49307704
type: Answer

http://stackoverflow.com/comment/85654673
score: 0
comment on: http://stackoverflow.com/q/49325509
has text: [https://docs.python.org/3.6/library/re.html] in explaination of `?=` it is mentioned that "(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov' " but in `(?=(\d)\d\1)` there is nothing in front of `?=` to match
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49355681
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85712256
has answer: http://stackoverflow.com/a/49356020
accepted answer: http://stackoverflow.com/a/49356020
tagged with: python
has body: I realize there are questions already posted in the past on SO that are similar to my question here. They don't, however, give me what I want. I have a large dataframe, data, with 314 columns. I would like to calculate the correlation values between all pairs of only the first 30 columns of my dataframe. After that, I would like to report the top 5 correlated pairs, regardless of sign, so in terms of magnitude of the correlation coef. I realize I should use .corr() because some dataframe cells are empty, and we don't want to include them. Here's what I have so far. I am still working on it. Don't know the type for cc either, which is why I didn't get as far as to report the top 5 values: W = 30 # taking the first 30 columns cc = np.zeros((1,W)) # pre-allocation for coefficients for c in range(1:W) in data: tmp = data.corr(data(:,c0),data(:,c)); cc(c) = tmp(1,2); Here are the first 15 rows and 5 columns of the data frame: Group Age Gender Weight Height 0 1 50 1 224 73.533514 1 1 59 0 180 62.625479 2 1 22 0 167 62.253894 3 1 48 0 113 61.476092 4 1 53 1 166 70.076665 5 1 48 1 210 71.384046 6 1 29 0 140 61.438960 7 1 44 1 181 74.992675 8 1 28 0 98 60.145635 9 1 42 1 187 71.588029 10 1 35 0 199 66.773644 11 0 54 1 228 76.971180 12 0 43 0 145 67.586941 13 1 50 0 190 67.229118 14 1 62 0 281 63.645601
has title: Calculating pairwise correlations of large dataframe among a certain number of columns
has comment: http://stackoverflow.com/comment/85712334
tagged with: numpy
tagged with: correlation
downvote count: 0
has comment: http://stackoverflow.com/comment/85711944
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85711837
favorite count: 0

http://stackoverflow.com/comment/85594310
type: Comment
score: 1
type: QuestionComment
has text: I have cut back your question text considerably. Please take note of how this was edited; I put your question *on top*, so people reading the post know what to look for. I removed everything from the assignment text that has no bearing on your actual question. Try to do the same in future questions.
comment on: http://stackoverflow.com/q/49295038

http://stackoverflow.com/q/49398255
has comment: http://stackoverflow.com/comment/85799472
tagged with: deep-learning
possible better answer: http://stackoverflow.com/a/49546835
upvote count: 10
has answer: http://stackoverflow.com/a/49546835
accepted answer: http://stackoverflow.com/a/50140036
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50140036
tagged with: pytorch
has body: How do I load pretrained model using fastai implementation over PyTorch? Like in SkLearn I can use pickle to dump a model in file then load and use later. I've use .load() method after declaring learn instance like bellow to load previously saved weights: arch=resnet34 data = ImageClassifierData.from_paths(PATH, tfms=tfms_from_model(arch, sz)) learn = ConvLearner.pretrained(arch, data, precompute=False) learn.load('resnet34_test') Then to predict the class of an image: trn_tfms, val_tfms = tfms_from_model(arch,100) img = open_image('circle/14.png') im = val_tfms(img) preds = learn.predict_array(im[None]) print(np.argmax(preds)) But It gets me the error: ValueError: Expected more than 1 value per channel when training, got input size [1, 1024] This code works if I use learn.fit(0.01, 3) instead of learn.load(). What I really want is to avoid the training step In my application.
downvote count: 0
has answer: http://stackoverflow.com/a/52780016
score: 10
tagged with: resnet
has title: How do I re-use trained fastai models?
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/85878856
type: Comment
comment on: http://stackoverflow.com/a/49436607
score: 0
type: AnswerComment
has text: thats perfect, would you mind explaining it to me , thank you so much for your help

http://stackoverflow.com/q/49314261
favorite count: 0
type: Question
tagged with: numpy
tagged with: h5py
has title: Converting A folder of images into a .h5 file?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49316108
score: 3
has body: Currently I am doing the deep learning course by Andrew NG in coursera. There they are opening the dataset of images from a .h5 file. I would like to try the same approach for my own dataset: I want to convert a folder of images to a .h5 file. I tried the following, but when I open the train_x.h5 it is showing all entries as zeros. h5_train = h5py.File("train_x.h5", 'w') h5_train.create_dataset("data_train", data=np.array(train_x)) print(h5_train) h5_train.close() Here train_x is an array of shape(270000,500), where first entry is the number of pixels(300*300*3) and second entry is number of images in the folder.
upvote count: 3
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49396962
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: A simple list comprehension will do the job along with filter and map. filter will be used to filter out None values and map will be used to cast the filtered string to float &gt;&gt;&gt; [tuple(map(float,filter(None, a))) for a in data] &gt;&gt;&gt; [ (-0.167969896634, 0.475981802514), (-0.186100643368, 0.47510168705), (-0.205064369305, 0.476225633961) ]
answers question: http://stackoverflow.com/q/49396521

http://stackoverflow.com/comment/85828194
has text: What is your operating system?
comment on: http://stackoverflow.com/q/49412451
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49349817
has body: For comparison with @KeyurPotdar's solution, this can also be achieved via collections.defaultdict: from collections import defaultdict temp_dict1 = {'A': [1,2,3,4], 'B':[5,5,6], 'C':[6,6,7,8]} temp_dict2 = defaultdict(list) val = [5, 6] for i in val: for k, v in temp_dict1.items(): if i in v: temp_dict2[k].append(i) # defaultdict(list, {'B': [5, 6], 'C': [6]})
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85709477
has comment: http://stackoverflow.com/comment/85709443
score: 1
has comment: http://stackoverflow.com/comment/85709429
type: Answer
answers question: http://stackoverflow.com/q/49348944
has comment: http://stackoverflow.com/comment/85709415

http://stackoverflow.com/comment/85700887
has text: I tried changing void* to char* but get an error: Traceback (most recent call last): File "./test.py", line 6, in <module> test_class.set_data(data_1) File "example.py", line 104, in set_data return _example.MyTestClass_set_data(self, data) TypeError: in method 'MyTestClass_set_data', argument 2 of type 'char *'
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49348920
score: 0

http://stackoverflow.com/comment/85724138
has text: actually i need to split into 4 ranges, for tat quarter is fine rit? after i find this count value need to apply for finding churn rate
comment on: http://stackoverflow.com/a/49359884
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49306996
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/49309626
favorite count: 0
type: Question
tagged with: heroku
tagged with: gunicorn
type: UnansweredQuestion
tagged with: python
has title: Worker failed to boot
has answer: http://stackoverflow.com/a/49364569
has body: I'm trying to deploy my Django project on Heroku, but something is going wrong, and I'm not able to found out what is happening, and what to do in order to solve this. I read in other posts that the problem may be something related with Gunicorn, but I can't solve it. (env) ignacio@ignacio:~/atletico$ heroku logs 2018-03-15T18:04:33.770218+00:00 app[web.1]: [2018-03-15 18:04:33 +0000] [4] [INFO] Reason: Worker failed to boot. 2018-03-15T18:04:47.082000+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2018-03-15T18:04:49.411412+00:00 heroku[web.1]: Process exited with status 3 2018-03-15T18:04:49.139027+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Starting gunicorn 19.7.1 2018-03-15T18:04:49.139593+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Listening at: http://0.0.0.0:25381 (4) 2018-03-15T18:04:49.139786+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Using worker: sync 2018-03-15T18:04:49.149373+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [ERROR] Exception in worker process 2018-03-15T18:04:49.149376+00:00 app[web.1]: Traceback (most recent call last): 2018-03-15T18:04:49.149391+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-03-15T18:04:49.149394+00:00 app[web.1]: worker.init_process() 2018-03-15T18:04:49.143828+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [INFO] Booting worker with pid: 8 2018-03-15T18:04:49.149396+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-03-15T18:04:49.149398+00:00 app[web.1]: self.load_wsgi() 2018-03-15T18:04:49.149400+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-03-15T18:04:49.149401+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-03-15T18:04:49.149408+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-…
tagged with: deployment
score: 2
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85616325
has comment: http://stackoverflow.com/comment/85616655

http://stackoverflow.com/comment/85743838
type: Comment
type: QuestionComment
score: 0
has text: Show us how you are running `cython` on the `pyx` file, and how you are compiling the resulting `c` code. You can't import `pyx` file directly into a Python session.
comment on: http://stackoverflow.com/q/49370572

http://stackoverflow.com/comment/101418622
has text: With momentum, gradient descent may converge faster, but it doesn't guarantee that it will reach the global minimum. Here is an illustration: https://ikocabiyik.com/data-science/gradient-descent-with-momentum/
comment on: http://stackoverflow.com/q/49346720
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49432949
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: linux
has answer: http://stackoverflow.com/a/49433546
has title: How to grep the names of files and store it in output with python
has body: I have a directory that has multiple files and I want to grep only test.uwsgi.log files and remove the .uwsgi.log part. After greping the names I store it in a output file. Here is what I got: import subprocess testlist = “cd /root/test/ &amp;&amp; ls | grep ‘uwsgi.log' |sed 's/\.uwsgi.log\&gt;//g' &gt; /root/test/testlist.txt" output = subprocess.check_output(['bash','-c', testlist]) and the output is : test1 test2 test3 Can someone educate me on how to achieve this without the subprocess module and use python only?
accepted answer: http://stackoverflow.com/a/49433546
tagged with: python
tagged with: ubuntu
tagged with: unix
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/85708611
type: AnswerComment
comment on: http://stackoverflow.com/a/49354082
score: 0
has text: True! Don't know why I was doing that!
type: Comment

http://stackoverflow.com/q/49386774
answer count: 1
has body: Using matplotlib.pyplot, I want to create a barplot, and save it to an image without axes, borders and additional whitespace around. The answers to Save spectrogram (only content, without axes or anything else) to a file using Matloptlib and all the linked questions and respective answers seem not to work for barplots. So far I got: import matplotlib.pyplot as plt fig,ax = plt.subplots(1) fig.subplots_adjust(left=0,right=1,bottom=0,top=1) fig.patch.set_facecolor('xkcd:mint green') ax.set_facecolor('xkcd:salmon') ax.axis('off') ax.bar(1,1,1,-1,alpha=1, align='center', edgecolor='black') ax.bar(2,1,1,-2,alpha=1, align='center', edgecolor='black') ax.axis('off') fig.savefig('test.png', dpi=300, frameon='false', pad_inches=0.0,bbox_inches='tight') which has three issues: There is some remaining whitespace at the left,top and right. The figure seems to be cut at the bottom, as the bottom line of the lower bar is thinner than the others. The aspect ration should be 1:1 and seems to be off.
type: Question
has answer: http://stackoverflow.com/a/49387509
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/49387509
has title: Save a barplot in matplotlib without border, axes, whitespace
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/47147146

http://stackoverflow.com/comment/85854477
type: QuestionComment
type: Comment
score: 0
has text: @droooze, this may work. But I suggest you post on the duplicate answer.
comment on: http://stackoverflow.com/q/49426584

http://stackoverflow.com/comment/85870360
has text: Indeed, I was expecting something more elegant, but this also works.
comment on: http://stackoverflow.com/a/49431180
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85860490
has text: I'm need to get full info about all file permissions (FILE_READ_DATA, FILE_WRITE_DATA, FILE_APPEND_DATA, ...) for all users.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49428874
type: Comment

http://stackoverflow.com/comment/85667054
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49290356
has text: @phyloflash Thank you so much for your suggestion! ^^ I will read more about the function and then try it~ ^^

http://stackoverflow.com/q/49294326
answer count: 1
has comment: http://stackoverflow.com/comment/85591089
tagged with: tensorflow
type: Question
has body: Let's say I have a tensor with shape [a,b] and another one with shape [a,c], where c&lt;b. I want to merge both to a tensor with the dimensions [a, b+c]. How would one accomplish this in TensorFlow? Simply using tf.concat won't work in this case because it expects that all dimensions, except 0, to be equal: All dimensions except 0 must match. Input 1 has shape [a b] and doesn't match input 0 with shape [a c]
has comment: http://stackoverflow.com/comment/85591251
has title: Expanding a tensor by another one with different dimensions in TensorFlow
tagged with: python
has comment: http://stackoverflow.com/comment/85591374
has comment: http://stackoverflow.com/comment/85591342
accepted answer: http://stackoverflow.com/a/49294698
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85593777
has answer: http://stackoverflow.com/a/49294698
has comment: http://stackoverflow.com/comment/85593234

http://stackoverflow.com/a/49646706
upvote count: 1
has body: Possibly even more Pythonic: Code data = ["keywords", "testcases"] data_combination = ["data", "index"] [[x] + data_combination[:i] for x in data for i, _ in enumerate(data_combination, 1)] Output [['keywords', 'data'], ['keywords', 'data', 'index'], ['testcases', 'data'], ['testcases', 'data', 'index']]
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49296697

http://stackoverflow.com/a/49430335
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85863271
has comment: http://stackoverflow.com/comment/85874273
accepted answer of: http://stackoverflow.com/q/49430014
type: Answer
answers question: http://stackoverflow.com/q/49430014
has comment: http://stackoverflow.com/comment/85905699
has comment: http://stackoverflow.com/comment/85864851
has body: SublimeText itself doesn't install Python packages. Instead, the virtualenv package substitutes a Python binary that you specify instead of the system installation whenever you hit Ctrl+B. Your virtual environments are stored in the ~/.virtualenvs directory (though you can keep them anywhere). From your snippet above, it appears you have three virtualenvs installed, called python, python3 and python3.6. To install TensorFlow or Requests, you need to activate your virtualenv from the terminal: source ~/.virtualenvs/python3.6/bin/activate Then run your installation commands: pip install tensorflow You can verify the installation completed successfully by running pip freeze. In sublime, check the virtualenv package settings to confirm that it's pointed at your ~/.virtualenvs directory. When you run the command to select a virtualenv (Ctrl+Shift+P), you will see a list of all the virtualenvs saved to that folder. If you select the python3.6 environment, you can now use Tensorflow.
has comment: http://stackoverflow.com/comment/85863306
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85773060
comment on: http://stackoverflow.com/q/49385105
type: Comment
type: QuestionComment
has text: What should I do then? I am running it in VScode. At the bottom it says. Python 3.6.4 and MagicPython. So are they different?
score: 0

http://stackoverflow.com/comment/85586049
has text: @ConfusinglyCuriousTheThird: the sample code is submitted. I hope the code help to clear the question.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49291317

http://stackoverflow.com/q/49395280
answer count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
upvote count: 3
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/49395319
accepted answer: http://stackoverflow.com/a/49395319
type: Question
score: 2
tagged with: bash
has body: I want to execute a python script,test.py, from a php function. #!/usr/bin/env python import random def test() : print("test success") if __name__ == '__main__': test() I can successfully execute it using php command line: php -r '$message = exec("python3 ~/../scripts/test.py"); print_r($message);' I've added the following to my php code: $message = exec("python3 ~/../scripts/test.py", $output, $return_val); When I execute it, nothing is output (no errors in devtools). When I print the variables, $output and $message are empty and $return_val is 2 (misuse of shell builtins according to Bash documentation). I know exec() is allowed after adding the following into the same function: if (exec('echo TEST') == 'TEST') { echo 'exec works!'; } What could be causing this error? How can I execute the python script with php?
has title: Executing python script from php function?

python-2.7
tags question: http://stackoverflow.com/q/49433496
tags question: http://stackoverflow.com/q/49332044
tags question: http://stackoverflow.com/q/49310204
tags question: http://stackoverflow.com/q/49405240
tags question: http://stackoverflow.com/q/49340845
tags question: http://stackoverflow.com/q/49370795
tags question: http://stackoverflow.com/q/49326559
tags question: http://stackoverflow.com/q/49324077
tags question: http://stackoverflow.com/q/49311565
tags question: http://stackoverflow.com/q/49356592
tags question: http://stackoverflow.com/q/49330843
tags question: http://stackoverflow.com/q/49295890
tags question: http://stackoverflow.com/q/49382207
tags question: http://stackoverflow.com/q/49305946
tags question: http://stackoverflow.com/q/49363505
tags question: http://stackoverflow.com/q/49314988
tags question: http://stackoverflow.com/q/49379689
tags question: http://stackoverflow.com/q/49433777
tags question: http://stackoverflow.com/q/49354814
tags question: http://stackoverflow.com/q/49354860
tags question: http://stackoverflow.com/q/49418839
tags question: http://stackoverflow.com/q/49436931
tags question: http://stackoverflow.com/q/49419339
tags question: http://stackoverflow.com/q/49386034
tags question: http://stackoverflow.com/q/49280714
tags question: http://stackoverflow.com/q/49413005
tags question: http://stackoverflow.com/q/49343908
tags question: http://stackoverflow.com/q/49424733
tags question: http://stackoverflow.com/q/49364196
tags question: http://stackoverflow.com/q/49418669
tags question: http://stackoverflow.com/q/49308887
tags question: http://stackoverflow.com/q/49394007
tags question: http://stackoverflow.com/q/49345455
tags question: http://stackoverflow.com/q/49312374
tags question: http://stackoverflow.com/q/49362591
tags question: http://stackoverflow.com/q/49311085
tags question: http://stackoverflow.com/q/49405251
type: Tag
tags question: http://stackoverflow.com/q/49334585
tags question: http://stackoverflow.com/q/49406058
tags question: http://stackoverflow.com/q/49382167
tags question: http://stackoverflow.com/q/49410529
tags question: http://stackoverflow.com/q/49290338
tags question: http://stackoverflow.com/q/49371214
tags question: http://stackoverflow.com/q/49347166
tags question: http://stackoverflow.com/q/49361201
tags question: http://stackoverflow.com/q/49310466
tags question: http://stackoverflow.com/q/49428562
tags question: http://stackoverflow.com/q/49416698
tags question: http://stackoverflow.com/q/49401065
tags question: http://stackoverflow.com/q/49396311
tags question: http://stackoverflow.com/q/49384188
tags question: http://stackoverflow.com/q/49308330
tags question: http://stackoverflow.com/q/49297194
tags question: http://stackoverflow.com/q/49324807
tags question: http://stackoverflow.com/q/49398594
tags question: http://stackoverflow.com/q/49333238
tags question: http://stackoverflow.com/q/49301732
tags question: http://stackoverflow.com/q/49319528
tags question: http://stackoverflow.com/q/49396521
tags question: http://stackoverflow.com/q/49319760
tags question: http://stackoverflow.com/q/49425018
tags question: http://stackoverflow.com/q/49424199
tags question: http://stackoverflow.com/q/49399962
tags question: http://stackoverflow.com/q/49335177
tags question: http://stackoverflow.com/q/49280143
tags question: http://stackoverflow.com/q/49350385
tags question: http://stackoverflow.com/q/49424857
tags question: http://stackoverflow.com/q/49380224
tags question: http://stackoverflow.com/q/49315762
tags question: http://stackoverflow.com/q/49319601
tags question: http://stackoverflow.com/q/49346405
tags question: http://stackoverflow.com/q/49342573
tags question: http://stackoverflow.com/q/49395393
tags question: http://stackoverflow.com/q/49361297
tags question: http://stackoverflow.com/q/49368126
tags question: http://stackoverflow.com/q/49334378
tags question: http://stackoverflow.com/q/49327856
tags question: http://stackoverflow.com/q/49355187
tags question: http://stackoverflow.com/q/49323210

http://stackoverflow.com/q/49386696
duplicate of: http://stackoverflow.com/q/31833897
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85774806
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85774794
has body: I am trying to run proc = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) with the output being monitored with comm = proc.communicate(). This works fine, in that I can print comm[0] or comm[1] and get all of the output, but it doesn't work in real time, only all at the end of the process. Is there a way to have the stability of communicate() with the speed of just running something like proc.stdout.readline()? I get clogged (as the python manual suggests I might) when I try to use proc.stdout.readline().
has comment: http://stackoverflow.com/comment/85774980
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/874815
tagged with: python
linked to: http://stackoverflow.com/q/31833897
linked to: http://stackoverflow.com/q/1085071
has comment: http://stackoverflow.com/comment/85774412
has comment: http://stackoverflow.com/comment/85774687
has title: Display Popen.communicate() in real time
tagged with: subprocess
tagged with: popen
answer count: 0

http://stackoverflow.com/comment/85741952
type: Comment
score: 0
type: AnswerComment
has text: No worries. I'll figure it out, I think I have an idea of where to head. Thank you for your help!
comment on: http://stackoverflow.com/a/49349496

http://stackoverflow.com/q/49307738
answer count: 1
has comment: http://stackoverflow.com/comment/85617724
tagged with: file
tagged with: plot
has comment: http://stackoverflow.com/comment/85617955
has answer: http://stackoverflow.com/a/49308024
has comment: http://stackoverflow.com/comment/85617616
tagged with: python
has body: I have a problem with my script. I have (blabla.)txt file, for example: blablaba bla dsadsadsa dsadsadsa 50 2323 60 2839 70 9832 80 0000 ..... .... ... and script I wrote: import numpy as np import matplotlib.pyplot as plt with open("blabla.txt") as f: for line in xrange(3): next(f) for line in f: data = f.read() data = data.split('\n') x = [row.split()[0] for row in data] y = [row.split()[1] for row in data] index = [i for i,val in enumerate(x)] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("graph") ax1.set_xlabel('time') ax1.set_ylabel('distance') ax1.set_xticklabels(x) ax1.plot(index ,y, c='r', label='distance1') leg = ax1.legend() plt.locator_params(nbins=len(index)-1) plt.show() The first question is: Is it true (syntax in the script) when I want to skip (because of the graph) the first three lines in the txt file? The second: After runscript it says: data = f.read() ValueError: Mixing iteration and read methods would lose data. What is the problem, its because of size? (txt file has about 600 000 lines) Thanks for all the help....Funstorm60
type: Question
score: 0
has title: Python - plot from txt file, skipping lines
has comment: http://stackoverflow.com/comment/85617555
type: UnansweredQuestion

http://stackoverflow.com/comment/85904070
type: Comment
type: QuestionComment
score: 0
has text: There are always better solutions imho but definitely check upper and lower bounds, and be explicit to the user about the format of the input. Some example code added below that may or may not be useful. Some good point raised there in previous comments.
comment on: http://stackoverflow.com/q/49415175

http://stackoverflow.com/q/49415811
has comment: http://stackoverflow.com/comment/85833439
answer count: 3
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/49416118
possible better answer: http://stackoverflow.com/a/49415867
has comment: http://stackoverflow.com/comment/85833454
accepted answer: http://stackoverflow.com/a/49415980
downvote count: 1
favorite count: 0
type: Question
has title: most pythonic way to compare substrings l in list L to string S & edit S according to l in L?
has answer: http://stackoverflow.com/a/49415980
type: AnsweredQuestion
has body: The list ['a','a #2','a(Old)'] should become {'a'} because '#' and '(Old)' are to be excised and a list of duplicates isn't needed. I struggled to develop a list comprehension with a generator and settled on this since I knew it'd work and valued time more than looking good: l = [] groups = ['a','a #2','a(Old)'] for i in groups: if ('#') in i: l.append(i[:i.index('#')].strip()) elif ('(Old)') in i: l.append(i[:i.index('(Old)')].strip()) else: l.append(i) groups = set(l) What's the slick way to get this result?
tagged with: python
has answer: http://stackoverflow.com/a/49415867
has comment: http://stackoverflow.com/comment/85833432

django
tags question: http://stackoverflow.com/q/49302478
tags question: http://stackoverflow.com/q/49376263
tags question: http://stackoverflow.com/q/49399501
tags question: http://stackoverflow.com/q/49379532
tags question: http://stackoverflow.com/q/49352971
tags question: http://stackoverflow.com/q/49340026
tags question: http://stackoverflow.com/q/49394906
tags question: http://stackoverflow.com/q/49377020
tags question: http://stackoverflow.com/q/49436833
tags question: http://stackoverflow.com/q/49330581
tags question: http://stackoverflow.com/q/49412526
tags question: http://stackoverflow.com/q/49350041
tags question: http://stackoverflow.com/q/49347265
tags question: http://stackoverflow.com/q/49361430
tags question: http://stackoverflow.com/q/49297935
tags question: http://stackoverflow.com/q/49422490
tags question: http://stackoverflow.com/q/49395533
tags question: http://stackoverflow.com/q/49292879
tags question: http://stackoverflow.com/q/49326282
tags question: http://stackoverflow.com/q/49342882
tags question: http://stackoverflow.com/q/49370804
tags question: http://stackoverflow.com/q/49331935
tags question: http://stackoverflow.com/q/49331945
tags question: http://stackoverflow.com/q/49300902
tags question: http://stackoverflow.com/q/49356501
tags question: http://stackoverflow.com/q/49402212
tags question: http://stackoverflow.com/q/49382543
tags question: http://stackoverflow.com/q/49403209
tags question: http://stackoverflow.com/q/49317265
tags question: http://stackoverflow.com/q/49297630
tags question: http://stackoverflow.com/q/49312557
tags question: http://stackoverflow.com/q/49303397
tags question: http://stackoverflow.com/q/49381031
tags question: http://stackoverflow.com/q/49281370
tags question: http://stackoverflow.com/q/49345950
tags question: http://stackoverflow.com/q/49326259
tags question: http://stackoverflow.com/q/49327416
tags question: http://stackoverflow.com/q/49306996
tags question: http://stackoverflow.com/q/49377595
tags question: http://stackoverflow.com/q/49362442
tags question: http://stackoverflow.com/q/49339569
tags question: http://stackoverflow.com/q/49381132
tags question: http://stackoverflow.com/q/49323188
tags question: http://stackoverflow.com/q/49401465
tags question: http://stackoverflow.com/q/49338522
tags question: http://stackoverflow.com/q/49279697
tags question: http://stackoverflow.com/q/49301699
tags question: http://stackoverflow.com/q/49346893
tags question: http://stackoverflow.com/q/49439451
tags question: http://stackoverflow.com/q/49435647
tags question: http://stackoverflow.com/q/49330155
tags question: http://stackoverflow.com/q/49386423
tags question: http://stackoverflow.com/q/49347266
tags question: http://stackoverflow.com/q/49425053
tags question: http://stackoverflow.com/q/49374951
tags question: http://stackoverflow.com/q/49312718
tags question: http://stackoverflow.com/q/49306177
tags question: http://stackoverflow.com/q/49384756
tags question: http://stackoverflow.com/q/49368312
tags question: http://stackoverflow.com/q/49336389
tags question: http://stackoverflow.com/q/49393181
tags question: http://stackoverflow.com/q/49341093
tags question: http://stackoverflow.com/q/49389440
tags question: http://stackoverflow.com/q/49289663
tags question: http://stackoverflow.com/q/49360770
tags question: http://stackoverflow.com/q/49366473
tags question: http://stackoverflow.com/q/49310014
tags question: http://stackoverflow.com/q/49286928
tags question: http://stackoverflow.com/q/49382020
tags question: http://stackoverflow.com/q/49396918
tags question: http://stackoverflow.com/q/49296647
tags question: http://stackoverflow.com/q/49285546
tags question: http://stackoverflow.com/q/49393777
tags question: http://stackoverflow.com/q/49394280
tags question: http://stackoverflow.com/q/49306634
tags question: http://stackoverflow.com/q/49308441
tags question: http://stackoverflow.com/q/49344703
tags question: http://stackoverflow.com/q/49353692
tags question: http://stackoverflow.com/q/49381367
tags question: http://stackoverflow.com/q/49319153

http://stackoverflow.com/comment/85869427
has text: @jpp It is not (here), but always necessary inside a groupby. I do it for consistency.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49433579
type: AnswerComment

http://stackoverflow.com/q/49313024
has answer: http://stackoverflow.com/a/49313052
tagged with: python
has answer: http://stackoverflow.com/a/49313109
has title: How to match *only* a six digit version?
has answer: http://stackoverflow.com/a/49313118
type: AnsweredQuestion
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/49313092
has comment: http://stackoverflow.com/comment/85628288
has answer: http://stackoverflow.com/a/49313053
accepted answer: http://stackoverflow.com/a/49313053
downvote count: 1
tagged with: python-2.x
tagged with: regex
has answer: http://stackoverflow.com/a/49313173
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49313128
answer count: 8
has answer: http://stackoverflow.com/a/49314974
possible better answer: http://stackoverflow.com/a/49313052
has comment: http://stackoverflow.com/comment/85627686
has comment: http://stackoverflow.com/comment/85627661
has body: I am trying to match a six digit version (seperated by a dot . ),lets say 9.130.46.32.6.2 and it works fine but it matches a seven digit version (seperated by a dot .) aswell,lets say 9.130.46.32.6.2.1',how to ensure it only matches a six digit version but not anything else? import re version = '9.130.46.32.6.2' (six digit) --&gt;SHOULD MATCH version = '9.130.46.32.6.2.1'(seven digit) --&gt; SHOULD NOT MATCH #if the version is six digit append a ".0" as 4th digit regex = re.compile(r'\d+\.\d+\.\d+\.\d+\.\d+\.\d+') m = regex.match(version) if m: print "Its a six digit version..." digit1 = version.split('.')[-6] print digit1 digit2 = version.split('.')[-5] print digit2 digit3 = version.split('.')[-4] print digit3 digit4 = version.split('.')[-3] print digit4 digit5 = version.split('.')[-2] print digit5 digit6 = version.split('.')[-1] print digit6 new_version = digit1 + "."+ digit2 + "." + digit3 + "."+ "0." + digit4 + "." + digit5 + "." + digit6 print new_version

http://stackoverflow.com/comment/85912521
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49454336
type: Comment
has text: Other queries run in the expected time, specifically get() and mget()

http://stackoverflow.com/q/49407788
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/49408015
downvote count: 3
has answer: http://stackoverflow.com/a/49407879
has title: Create new class with an instance of the inherited class
favorite count: 0
type: Question
tagged with: oop
type: UnansweredQuestion
tagged with: python
tagged with: inheritance
score: -3
has body: I would like to know how I could take an object from a function and place it and all it's attributes into another object. class Something: def create(self): print('Creating') class Foo(Something): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def do_something(self): print('Do somthing') def bar(): # Can not change this function return Something() s = bar() s.create() # 'Creating' -- I want to do this -- f = Foo(s) f.create() f.do_something() Limitations: I cant alter bar(). I need to be able to access all of Something's methods and attributes from Foo. I would like to stay away form composition so that I can call Foo.create() directly (not like Foo.something.create()).
has comment: http://stackoverflow.com/comment/85816980

http://stackoverflow.com/q/49383135
score: 0
has body: I can not get the plot stretched to the whole area of the figure. When I call the tight_layout, the required height of the plot is obtained, but I can not achieve the required length: Code: self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) # self.figure.set_figheight(15) # self.figure.set_figwidth(5) #self.figure.tight_layout() self.figure.set_size_inches(1, 7) self.graphBox.addWidget(self.canvas) # ------------------------------------------------------------------ # ------------------------------------------------------------------ t = np.arange(0.0, 2.0, 0.01) s = np.sin(2 * np.pi * t) ax = plt.subplot2grid((1, 1), (0, 0)) ax.set_facecolor(color='#b3ff66') ax.plot(t, s) self.canvas.draw() #plt.tight_layout(h_pad=1.0, w_pad=1.0) # ------------------------------------------------------------------ # ------------------------------------------------------------------
tagged with: canvas
answer count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/85767189
duplicate of: http://stackoverflow.com/q/332289
type: Question
has title: How to stretch the size of a plot to the whole area of a shape
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85769549
tagged with: plot
linked to: http://stackoverflow.com/q/332289

http://stackoverflow.com/comment/86612234
comment on: http://stackoverflow.com/a/49759560
has text: `$ cat /etc/profile.d/jython.sh export PATH="/opt/jython/bin/:$PATH"` . Looks nice enough, at least to my eye.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49379332
linked to: http://stackoverflow.com/q/43482191
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37970424
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/35677767
has comment: http://stackoverflow.com/comment/85762845
score: 0
duplicate of: http://stackoverflow.com/q/35677767
has body: import matplotlib.pyplot as plt fig = plt.figure("Histogram") ax = fig.add_subplot(1,1,1) ax.hist([10,10,10,10,10,21,12,23,35,45,60,33,22,56,34,28,40,41],bins=7,ec='black',color = 'b') plt.title("Distribution") plt.xlabel("Range") plt.ylabel("Amount") plt.show() this is the simple program to make a histogram My question is if I remove plt from plt.title("Distribution") plt.xlabel("Range") plt.ylabel("Amount") plt.show() And rewrite my code like this ax.set_title("Distribution") ax.set_xlabel("Range") ax.set_ylabel("Amount") plt.show() Why are both of the versions same? What are the difference between functions xlabel and set_xlabel/ylabel and set_ylabel
answer count: 0
has comment: http://stackoverflow.com/comment/85762502
type: Question
tagged with: python-3.x
has title: Data visualization in python (matplotlib)
has comment: http://stackoverflow.com/comment/85759905

http://stackoverflow.com/comment/85637473
score: 0
type: Comment
type: AnswerComment
has text: Thank you for the solution @Vivek Kumar . It worked.
comment on: http://stackoverflow.com/a/49315441

http://stackoverflow.com/a/49407693
has body: Opening a file in the "a+" method means, if a file with the specified name exists, append text to him, if that certain file doesn't exist create one with that name. class Login(QDialog): def __init__(self, parent=None): self.contributors=['','A','B','C'] super(Login, self).__init__(parent) ... self.buttonLogin = QPushButton('Login', self) self.buttonLogin.clicked.connect(self.user_entered) ... def user_entered(self): text = str(self.cb.currentText()) with open("my log file", "a+") as file: # wirting user name into a file file.write(text + "\n") self.close() if __name__ == '__main__': app = QApplication(sys.argv) login=Login() login.show() app.exec_() # delete the exec_() call in your window __init__
has comment: http://stackoverflow.com/comment/85844939
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49377049
has comment: http://stackoverflow.com/comment/85846541
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85855978
has text: Thanks @yelsayed, I tried using the google.datalab.* namespace and I am still getting the same error. If I pass a string without special characters everything works just fine. When passing any special character Google's library raises the exception, no matter if I pass a utf-8 encoded str or a unicode variable, and regardless of the content_type specified.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49411182

http://stackoverflow.com/comment/85885304
type: AnswerComment
comment on: http://stackoverflow.com/a/49440066
has text: This works with the test string, but I think it would grab "architecture," "arches," and other such words. My take on it is `([a-zA-Z-]*?archipel[a-zA-Z']*)`.
type: Comment
score: 0

http://stackoverflow.com/a/49435451
answers question: http://stackoverflow.com/q/49435233
upvote count: 1
score: 1
has body: Using default Readline bindings, Control-P + Enter is probably the closest exact equivalent to !!; the first key fetches the previous command; the second executes it. You can probably add a custom binding to .inputrc to execute both functions with one keystroke. Note, though, this is entirely line-oriented; if you try to use this following a multi-line for statement, for example, you'll only get the very last line of the body, not the entire for statement. The _ variable stores the result of the last evaluated expression; it doesn't reevaluate, though. This can be seen most clearly with something like datetime.datetime.now: &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2018, 3, 22, 14, 14, 50, 360944) &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2018, 3, 22, 14, 14, 51, 665947) &gt;&gt;&gt; _ datetime.datetime(2018, 3, 22, 14, 14, 51, 665947) &gt;&gt;&gt; _ datetime.datetime(2018, 3, 22, 14, 14, 51, 665947) &gt;&gt;&gt; _ datetime.datetime(2018, 3, 22, 14, 14, 51, 665947) &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2018, 3, 22, 14, 14, 58, 404816)
type: Answer
downvote count: 0

http://stackoverflow.com/q/49384940
has title: How to post form data(uploaded image) in python bottle using Ajax?
answer count: 1
downvote count: 0
upvote count: 1
has body: This is my form &lt;form method='post' enctype='multipart/form-data' id='uploadForm' name='formn'&gt; &lt;input type='file' value='' name='newfile'&gt; &lt;input type='submit' name='sub' value='Submit'&gt; &lt;/form&gt; this is my Ajax code $("#uploadForm").submit(function(event) { event.preventDefault(); var form_data = $("#uploadForm").serialize(); //var form_data = new FormData($('#uploadForm')[0]); $.ajax({ type : "POST", url : "/my_url", data : form_data, contentType : false, processData : false, cache : false, async : false, success: function(data, status ) { alert('success'); }, error : function() { alert('fail'); } }) }); when use, var form_data = $("#uploadForm").serialize()=> form_data is empty string. when use, var form_data = new FormData($('#uploadForm')[0])=> form data is as following screen shot. I want to pass the uploaded image into the service method. How can I access form data in my js file? Thank you.
favorite count: 0
type: Question
tagged with: ajax
type: UnansweredQuestion
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/49498435
score: 1

http://stackoverflow.com/q/49412706
has comment: http://stackoverflow.com/comment/85827393
has answer: http://stackoverflow.com/a/70370212
tagged with: runpy
type: Question
score: 9
type: UnansweredQuestion
downvote count: 0
has body: I have a Python package (Python 3.6, if it makes a difference) that I've designed to run as 'python -m package arguments' and I'd like to write unit tests for the __main__.py module. I specifically want to verify that it sets the exit code correctly. Is it possible to use runpy.run_module to execute my __main__.py and test the exit code? If so, how do I retrieve the exit code? To be more clear, my __main__.py module is very simple. It just calls a function that has been extensively unit tested. But when I originally wrote __main__.py, I forgot to pass the result of that function to exit(), so I would like unit tests where the main function is mocked to make sure the exit code is set correctly. My unit test would look something like: @patch('my_module.__main__.my_main', return_value=2) def test_rc2(self, _): """Test that rc 2 is the exit code.""" sys.argv = ['arg0', 'arg1', 'arg2', …] runpy.run_module('my_module') self.assertEqual(mod_rc, 2) My question is, how would I get what I’ve written here as ‘mod_rc’? Thanks.
favorite count: 0
has comment: http://stackoverflow.com/comment/85830516
has answer: http://stackoverflow.com/a/49413309
upvote count: 9
answer count: 3
has title: Unit testing __main__.py
has answer: http://stackoverflow.com/a/62476072
tagged with: python-unittest
tagged with: python

http://stackoverflow.com/comment/85648574
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49321165
has text: Possible duplicate of [How to set display precision in PySpark Dataframe show](https://stackoverflow.com/questions/48832493/how-to-set-display-precision-in-pyspark-dataframe-show)
type: Comment

http://stackoverflow.com/a/70370212
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49412706
type: Answer
has body: __main__.py is still subject to normal __main__ global behavior — which is to say, you can implement your __main__.py like so def main(): # Your stuff if __name__ == "__main__": main() and then you can test your __main__ in whatever testing framework you like by using from your_package.__main__ import main As an aside, if you are using argparse, you will probably want: def main(arg_strings=None): # … args = parser.parse_args(arg_strings) # … if __name__ == "__main__": main() and then you can override arg strings from a unit test simply with from your_package.__main__ import main def test_main(): assert main(["x", "y", "z"]) == … or similar idiom in you testing framework.
score: 3

http://stackoverflow.com/a/49385755
answers question: http://stackoverflow.com/q/49385690
score: 1
downvote count: 0
upvote count: 1
has body: Use pd.cut + pd.get_dummies: v = pd.cut(df.measurement, bins=[17, 18, 19, 20], labels=['17-18', '18-19', '19-20']) pd.get_dummies(v) 17-18 18-19 19-20 0 1 0 0 1 0 1 0 2 0 1 0 3 0 1 0 4 0 1 0
type: Answer

http://stackoverflow.com/q/49291335
has body: I'm running a jupyter notebook inside an ubuntu 16.04 docker container, as a non-root user, with SSL configured via a .pem file. My issue is, I can't perform the jupyter notebook stop $port command to stop the running server. I start the notebook by executing sudo HOME=/home/seiji -u seiji jupyter notebook to change the HOME environment variable (which is chown'd as seiji). I can perform the usual jupyter notebook list command by running it as the user (seiji) and feeding in the JUPYTER_RUNTIME_DIR environment variable where jupyter looks for json files containing server info. For example: sudo JUPYTER_RUNTIME_DIR=/jupyter/runtime -u seiji jupyter notebook list correctly returns: https://localhost:8888/ :: /jupyter/notebooks (I specify the runtime dir in the config file in the usual way). My issue is, I can't figure out how to execute jupyter notebook stop 8888 in a similar way. If I run it as is, it runs as root and tells me There are no running servers. If I run it as user:seiji, I run into SSL issues. As in: &gt; sudo JUPYTER_RUNTIME_DIR=/jupyter/runtime -u seiji jupyter notebook stop 8888 returns an error. It begins: Shutting down server on port 8888 ... but then prints the following: SSL Error on 10 ('::1', 8888, 0, 0): [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) My guess is that it tries a 'http' address to access the server instead of 'https', but I can't figure out how to change this. I've also tried passing the environment variable JUPYTER_CONFIG_DIR which contains the config file listing the location of the .pem file with the line c.NotebookApp.certfile = u'/jupyter/certs/mycert.pem'. I've also tried explicitly feeding in the location of the cert when running from cmdline with --certfile=[location] but it seems this is ignored. Does anyone have any ideas?
linked to: http://stackoverflow.com/q/10162707
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69462921
downvote count: 0
answer count: 1
has title: jupyter notebook stop SSL error
score: 6
favorite count: 0
tagged with: docker
tagged with: ssl
tagged with: python
tagged with: jupyter
has comment: http://stackoverflow.com/comment/85615373
upvote count: 6
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/comment/86070207
comment on: http://stackoverflow.com/q/49361952
type: Comment
type: QuestionComment
has text: Check my answer@Salem Hassan
score: 0

pandas
tags question: http://stackoverflow.com/q/49291740
tags question: http://stackoverflow.com/q/49316425
tags question: http://stackoverflow.com/q/49360566
tags question: http://stackoverflow.com/q/49287830
tags question: http://stackoverflow.com/q/49329569
tags question: http://stackoverflow.com/q/49412488
tags question: http://stackoverflow.com/q/49306430
tags question: http://stackoverflow.com/q/49333733
tags question: http://stackoverflow.com/q/49308580
tags question: http://stackoverflow.com/q/49345067
tags question: http://stackoverflow.com/q/49314650
tags question: http://stackoverflow.com/q/49417653
tags question: http://stackoverflow.com/q/49422448
tags question: http://stackoverflow.com/q/49324898
tags question: http://stackoverflow.com/q/49433910
tags question: http://stackoverflow.com/q/49392387
tags question: http://stackoverflow.com/q/49321065
tags question: http://stackoverflow.com/q/49315084
tags question: http://stackoverflow.com/q/49420520
tags question: http://stackoverflow.com/q/49436402
tags question: http://stackoverflow.com/q/49310989
tags question: http://stackoverflow.com/q/49308626
tags question: http://stackoverflow.com/q/49381524
tags question: http://stackoverflow.com/q/49355498
tags question: http://stackoverflow.com/q/49332187
tags question: http://stackoverflow.com/q/49392606
tags question: http://stackoverflow.com/q/49419407
tags question: http://stackoverflow.com/q/49364754
tags question: http://stackoverflow.com/q/49370713
tags question: http://stackoverflow.com/q/49308813
tags question: http://stackoverflow.com/q/49288557
tags question: http://stackoverflow.com/q/49390950
tags question: http://stackoverflow.com/q/49367799
tags question: http://stackoverflow.com/q/49322894
tags question: http://stackoverflow.com/q/49302095
tags question: http://stackoverflow.com/q/49344723
tags question: http://stackoverflow.com/q/49373835
tags question: http://stackoverflow.com/q/49357352
tags question: http://stackoverflow.com/q/49331834
tags question: http://stackoverflow.com/q/49316668
tags question: http://stackoverflow.com/q/49371343
tags question: http://stackoverflow.com/q/49324970
tags question: http://stackoverflow.com/q/49306467
tags question: http://stackoverflow.com/q/49309256
tags question: http://stackoverflow.com/q/49416969
tags question: http://stackoverflow.com/q/49361068
tags question: http://stackoverflow.com/q/49326496
tags question: http://stackoverflow.com/q/49354447
tags question: http://stackoverflow.com/q/49367586
tags question: http://stackoverflow.com/q/49308247
tags question: http://stackoverflow.com/q/49424089
tags question: http://stackoverflow.com/q/49371455
tags question: http://stackoverflow.com/q/49354556
tags question: http://stackoverflow.com/q/49295890
tags question: http://stackoverflow.com/q/49360958
tags question: http://stackoverflow.com/q/49334810
tags question: http://stackoverflow.com/q/49298766
tags question: http://stackoverflow.com/q/49345578
tags question: http://stackoverflow.com/q/49404405
tags question: http://stackoverflow.com/q/49360576
tags question: http://stackoverflow.com/q/49412694
tags question: http://stackoverflow.com/q/49388065
tags question: http://stackoverflow.com/q/49304323
tags question: http://stackoverflow.com/q/49356798
tags question: http://stackoverflow.com/q/49354390
tags question: http://stackoverflow.com/q/49293469
tags question: http://stackoverflow.com/q/49378948
tags question: http://stackoverflow.com/q/49411991
tags question: http://stackoverflow.com/q/49364654
tags question: http://stackoverflow.com/q/49351190
tags question: http://stackoverflow.com/q/49339350
tags question: http://stackoverflow.com/q/49438910
tags question: http://stackoverflow.com/q/49321361
tags question: http://stackoverflow.com/q/49433777
tags question: http://stackoverflow.com/q/49424455
tags question: http://stackoverflow.com/q/49439187
tags question: http://stackoverflow.com/q/49323439
tags question: http://stackoverflow.com/q/49437457
tags question: http://stackoverflow.com/q/49404061
tags question: http://stackoverflow.com/q/49295620

http://stackoverflow.com/comment/85668632
type: AnswerComment
score: 0
has text: Thank you for your reply! I used your solution and it returns `2>3>10>5>4`, which is not correct, will you please mind looking at it again ? Also, thanks for letting me know about `PEP8 standards`, I will read it. One more question at at the end, `temp.next points out to current.next`, which in my understanding `10 points to 5` now, again `cur.next points to temp` which means `3 also points to 5`. aren't we supposed to do it such that `3 should point to 10, and 10 should point to 5` ?
type: Comment
comment on: http://stackoverflow.com/a/49333365

http://stackoverflow.com/q/49335183
type: Question
has comment: http://stackoverflow.com/comment/85676285
has comment: http://stackoverflow.com/comment/85675973
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49338222
tagged with: python
has body: I've been creating a physics projectile simulation for my computer science project, and one of the key elements of it is collision detection. Essentially, I need the program to flag up when the "projectile" has hit a certain point. As an example, if I were to plot a simple line graph like ax1.plot([0,1,2,3,4,5],[5,4,3,2,1]) What sort of function would be able to determine if the line produced by the graph passes through the point (3.5,1.5)? Currently, the code is simply determining the distance travelled by the projectile in the x and y direction each second, so I don't believe a form of estimation can be used, though I may be wrong. Thank you in advance
has comment: http://stackoverflow.com/comment/85673795
tagged with: collision-detection
tagged with: graph
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85673731
score: 0
has title: Collision Detection for a Matplotlib graph within Python
has comment: http://stackoverflow.com/comment/85674461
answer count: 1
has comment: http://stackoverflow.com/comment/85672241
accepted answer: http://stackoverflow.com/a/49338222

http://stackoverflow.com/comment/85883052
has text: it turns out i try another function driver.fullscreen_window\(). it seems work
type: QuestionComment
comment on: http://stackoverflow.com/q/49435873
type: Comment
score: 0

http://stackoverflow.com/comment/85820326
type: QuestionComment
score: 2
has text: The error message is quite good IMHO.
type: Comment
comment on: http://stackoverflow.com/q/49408242

http://stackoverflow.com/q/49384233
answer count: 1
downvote count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/85769310
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85769412
has comment: http://stackoverflow.com/comment/85769519
has answer: http://stackoverflow.com/a/49384427
accepted answer: http://stackoverflow.com/a/49384427
tagged with: python
has comment: http://stackoverflow.com/comment/85769248
has comment: http://stackoverflow.com/comment/85770042
type: Question
has title: PEP 3106 suggests slower way? Why?
score: 5
tagged with: pep
has body: Recently, I had to convert the values of a dictionary to a list in Python 3.6 and an use case where this is supposed to happen a lot. Trying to be a good guy I wanted to use a solution which is close to the PEP. Now, PEP 3106 suggests list(d.keys()) which obviously works fine - but using timeit on my Windows 7 machine i see &gt;python -m timeit "[*{'a': 1, 'b': 2}.values()]" 1000000 loops, best of 3: 0.249 usec per loop &gt;python -m timeit "list({'a': 1, 'b': 2}.values())" 1000000 loops, best of 3: 0.362 usec per loop I assume that there is an advantage in the latter version, because why else should the PEP suggest the slower one. So here comes my question: What's the advantage of the latter version compared to the first one?

file-conversion
tags question: http://stackoverflow.com/q/49352303
tag name: file-conversion
type: Tag

http://stackoverflow.com/comment/85767202
has text: Yes,the type changes if the task is completed or else it remains the same
type: QuestionComment
comment on: http://stackoverflow.com/q/49381355
type: Comment
score: 0

copy
tags question: http://stackoverflow.com/q/49352970
type: Tag
tags question: http://stackoverflow.com/q/49329183
tag name: copy
tags question: http://stackoverflow.com/q/49375681

http://stackoverflow.com/q/49395363
score: -1
has body: I have modified the following function to return if the given string is a Palindrome. I also have it excluding capitalization, spaces, and punctuation. How can i modify this to return "false" if the user enters a non string. import string def remove_punctuations(word): return "".join(i.lower() for i in word if i in string.ascii_letters) def reverse(text): return text[::-1] def is_palindrome(text): text = remove_punctuations(text) return text==reverse(text) # where I am entering the string something = "12.5" if (is_palindrome(something)): print("True") else: print("False") # some test cases &gt;&gt;&gt; isPalindrome("alula") True &gt;&gt;&gt; isPalindrome("love") False &gt;&gt;&gt; isPalindrome(12) False &gt;&gt;&gt; isPalindrome(12.21) False Also how can i adjust this code so i can input is_palindrome(something), instead of manually entering "something"
has title: Palindrome string. How to exclude non strings.
duplicate of: http://stackoverflow.com/q/4843173
has answer: http://stackoverflow.com/a/49395404
answer count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4843173
has comment: http://stackoverflow.com/comment/85792609
tagged with: python

http://stackoverflow.com/comment/85563574
comment on: http://stackoverflow.com/q/49280161
has text: Besides manually there's no quick way, is the format 7 numbers and then a name 100% of the time?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85667689
has text: Because the loop changes the copy of `arr` was made.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49315196
type: AnswerComment

http://stackoverflow.com/comment/85609058
type: QuestionComment
has text: Hi @AlexanderTronchin-James, nope, I'm not playing around with the meta DB, but good thought. Here's what I think I will actually do: run two separate DAGs at different times in the day without explicitly declaring the task dependency. Not ideal, but it will be good enough for now.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49290546

http://stackoverflow.com/q/49420191
has title: Providing user defined sample weights for knn classifier in scikit-learn
has answer: http://stackoverflow.com/a/63655345
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/53602315
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/75271121
favorite count: 0
type: Question
tagged with: knn
type: UnansweredQuestion
upvote count: 6
score: 6
has body: I am using the scikit-learn KNeighborsClassifier for classification on a dataset with 4 output classes. The following is the code that I am using: knn = neighbors.KNeighborsClassifier(n_neighbors=7, weights='distance', algorithm='auto', leaf_size=30, p=1, metric='minkowski') The model works correctly. However, I would like to provide user-defined weights for each sample point. The code currently uses the inverse of the distance for scaling using the metric='distance' parameter. I would like to continue to keep the inverse distance scaling but for each sample point, I have a probability weight as well. I would like to apply this as a weight in the distance calculation. For example, if x is the test point and y,z are the two nearest neighbors for which distance is being calculated, then I would like the distance to be calculated as (sum|x-y|)*wy and (sum|x-z|)*wz respectively. I tried to define a function that was passed into the weights argument but then I also would like to keep the inverse distance scaling in addition to the user defined weight and I do not know the inverse distance scaling function. I could not find an answer from the documentation. Any suggestions?
tagged with: python
tagged with: nearest-neighbor

http://stackoverflow.com/comment/85745271
has text: Shouldn't it be added rather that subtraced? The given time is already in UTC, im trying to convert it to the local time, not the other way around.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49372003
score: 0

http://stackoverflow.com/q/49290330
tagged with: radio-button
type: UnansweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85585158
tagged with: python
score: -1
has body: I am using python 3 with Tkinter, when I select an item from the radio button, it correctly shows the radio button and all the contents of the list, however when I use the .get() function it only returns the first radio button item each time. I cannot seem to find why this isn't working correctly and this code was working perfectly earlier tonight. For contact the list stockList is ['apple','google','Tesla','amazon'] and this all displays in the correct order however the function stockStore only prints apple each time. stockList = ReadFile.PullStockCsv(self) var = tk.StringVar() var.set(stockList[0]) for item in stockList: button = tk.Radiobutton(self, text=item, variable=var, value=item) button.pack() btnPlotGraph = tk.Button(self, text="Plot Graph", command=lambda: stockStore(self, var)) btnPlotGraph.pack() button3 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(MainMenu)) button3.pack() def stockStore(self, var): y = var.get() print(y) ReadFile.textWrite(self, y) controller.show_frame(GraphPlot)
type: Question
has answer: http://stackoverflow.com/a/49291764
has title: Tkinter radio button not working correctly (always stores choice as first item)
tagged with: python-3.x
tagged with: tkinter

http://stackoverflow.com/a/49438475
accepted answer of: http://stackoverflow.com/q/49437887
has body: For a CSR matrix, m1.indptr does not hold the row indices. Instead, for row r, the pair of values start, end = m1.indptr[r:r+2] gives the start and end indices into m1.data of the values that are stored in row r. That is, m1.data[start:end] holds the nonzero values in row r. The columns of these values are in m1.indices[start:end]. In your example, you have m1.indptr = [ 0 2 4 6 8 10 12 14 16 18 20]. So the nonzero values in the first row are stored in m1.data[0:2], and the columns where these values are located are stored in m1.indices[0:2]. The nonzeros values stored in the second row are m1.data[2:4], and their columns are m1.indices[2:4], etc. If you want the row and column indices, probably the simplest method is to use the nonzero() method. For example, here is a CSR matrix: In [50]: s Out[50]: &lt;5x8 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 4 stored elements in Compressed Sparse Row format&gt; In [51]: s.A Out[51]: array([[ 0, 10, 40, 0, 0, 20, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 30, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64) Here we use the nonzero() method to get the row and column indices of the nonzero values: In [71]: row, col = s.nonzero() In [72]: row Out[72]: array([0, 0, 0, 2], dtype=int32) In [73]: col Out[73]: array([1, 2, 5, 3], dtype=int32) Alternatively, you could convert the array to the "COO" (coordinate) format. Then you can access the row and col attributes: In [52]: c = s.tocoo() In [53]: c.row Out[53]: array([0, 0, 0, 2], dtype=int32) In [54]: c.col Out[54]: array([1, 2, 5, 3], dtype=int32)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49437887
type: Answer
has comment: http://stackoverflow.com/comment/85880931
score: 2
upvote count: 2

http://stackoverflow.com/comment/85838369
comment on: http://stackoverflow.com/q/49417414
has text: @MrName My original issue was with deploying to heroku. The app is correctly serving the static files in heroku and I don't think there is another solution for it. This is the settings.py that I'm using for the tests both locally and on the build server
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49315525
has comment: http://stackoverflow.com/comment/85632588
type: Answer
has body: It looks like you are just printing each value, but that you really want a list. This appends each value into a list, then prints it: traceFilters = sqlContext.read.format("csv").options(header='true', delimiter = ',').load("/data/*.txt") traceFilters.take(5) fields = [ StructField("City", StringType(), False), StructField("Country", StringType(), False) ] traceFilters.track(5) a = [] for row in traceFilters.rdd.collect(): a.append(row.City) print(a)
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49315127
accepted answer of: http://stackoverflow.com/q/49315127

http://stackoverflow.com/comment/85875641
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49436834
score: 0
has text: What have you tried and where did you stuck at?

http://stackoverflow.com/q/49426315
has answer: http://stackoverflow.com/a/49426386
downvote count: 0
favorite count: 0
type: Question
has body: I have the following classes: class Site(models.Model): articles = models.ManyToManyField(Article, blank=True, null=True) products = models.ManyToManyField(Product, blank=True, null=True) class Product(models.Model): @property def sites_count(self): return self.site_set.count() In my admin I would like to the many to many relationships to be sorted by sites_count. class SiteAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "articles": kwargs['queryset'] = Article.objects.order_by('sites_count') return super().formfield_for_manytomany(self, db_field, request, **kwargs) I get complaints that sites_count cannot be used because it's not a column in my db. What is an alternative approach to this?
type: AnsweredQuestion
has title: Django order by count (@property) in many-to-many?
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49426386
tagged with: python-3.x
upvote count: 1
answer count: 1
tagged with: django

http://stackoverflow.com/q/49335512
type: AnsweredQuestion
score: 3
has body: I have a barchart, where the tick labels on the 'y' axes are outside. Example However, I would like to have the ylabels inside the bars with an align to the left. Is there a way to do this? Here is the code: fig, ax = plt.subplots() # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) ax.barh(y_pos, performance, xerr=error, align='center', color='green', ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(people) ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Performance') ax.set_title('How fast do you want to go today?') plt.show() If I play with tick_params: ax.tick_params(axis='y', direction='in',pad=-5) I get which is not what I want since the text is underneath and still aligned to the right.
linked to: http://stackoverflow.com/q/47873389
tagged with: matplotlib
tagged with: python
type: Question
upvote count: 3
linked to: http://stackoverflow.com/q/46457615
has title: Ticklabels inside a plot in matplotlib
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49338620
favorite count: 0
has answer: http://stackoverflow.com/a/49338620

http://stackoverflow.com/q/49386650
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has title: Terminate called after throwing an instance of 'std::bad_alloc' when training a CNN
tagged with: gpu
type: UnansweredQuestion
tagged with: python
score: 3
tagged with: image-segmentation
tagged with: deep-learning
answer count: 0
upvote count: 3
has body: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) I am training 3d dense CNN. I have 12GB GPU and 128GB RAM. The training happens on GPU but the cross-validation happens on RAM because of which I get the above error in between the training (CV utilizes all RAM). I want both training and CV to use GPU resources. The model has around 3M parameters and I am using a batch size of 1 (both for training and CV). I am using the following commands to specify GPU - os.environ[CUDA_VISIBLE_DEIVCES] = '0' config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True sess = tf.Session(config=config)

http://stackoverflow.com/q/49429709
upvote count: 0
score: -4
linked to: http://stackoverflow.com/q/48427185
has comment: http://stackoverflow.com/comment/85861131
tagged with: pyspark
has body: I am new in pyspark. Can you please help me how to get max age from json using pyspark? I tried df.filter(df['employees.age'] &gt; 22).show() It throws error, org.apache.spark.sql.AnalysisException: cannot resolve '(employees.age > 22)' due to data type mismatch: differing types in '(employees.age > 22)' (array and int).;; 'Filter (employees#0.age > 22) {'employees': [{'age': '12', 'firstName': 'John', 'lastName': 'Doe'}, {'age': '14', 'firstName': 'Anna', 'lastName': 'Smith'}, {'age': '54', 'firstName': 'Peter1', 'lastName': 'Jones1'}, {'age': '44', 'firstName': 'Peter2', 'lastName': 'Jones2'}, {'age': '42', 'firstName': 'Peter3', 'lastName': 'Jones3'}, {'age': '62', 'firstName': 'Peter4', 'lastName': 'Jones4'}, {'age': '65', 'firstName': 'Peter5', 'lastName': 'Jones5'}, {'age': '23', 'firstName': 'Peter6', 'lastName': 'Jones6'}, {'age': '77', 'firstName': 'Pete7', 'lastName': 'Jones7'}, {'age': '82', 'firstName': 'Peter8', 'lastName': 'Jones8'}, {'age': '92', 'firstName': 'Peter9', 'lastName': 'Jones9'}, {'age': '78', 'firstName': 'Peter10', 'lastName': 'Jones10'}]} I want to find those employee who has age greater than 22.
tagged with: python
has comment: http://stackoverflow.com/comment/85861255
has comment: http://stackoverflow.com/comment/85862112
has comment: http://stackoverflow.com/comment/85860940
has comment: http://stackoverflow.com/comment/85861092
has comment: http://stackoverflow.com/comment/85863540
has comment: http://stackoverflow.com/comment/85864220
has comment: http://stackoverflow.com/comment/85860917
has comment: http://stackoverflow.com/comment/85861892
has comment: http://stackoverflow.com/comment/85861458
has answer: http://stackoverflow.com/a/49429772
possible better answer: http://stackoverflow.com/a/49429772
has answer: http://stackoverflow.com/a/49430800
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85860827
has comment: http://stackoverflow.com/comment/85862965
has comment: http://stackoverflow.com/comment/85862538
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85861007
has comment: http://stackoverflow.com/comment/85860890
tagged with: http://stackoverflow.com/tag/json
has title: How to find age greater than value from json using pyspark?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85863282
has comment: http://stackoverflow.com/comment/85861101
accepted answer: http://stackoverflow.com/a/49430800
answer count: 2
downvote count: 4

http://stackoverflow.com/comment/85697385
comment on: http://stackoverflow.com/a/49348783
type: Comment
has text: Works like a charm! Thanks!
score: 0
type: AnswerComment

http://stackoverflow.com/q/49343619
linked to: http://stackoverflow.com/q/20932888
tagged with: jinja2
has answer: http://stackoverflow.com/a/49345259
type: Question
tagged with: python
tagged with: dictionary
has title: jinja2 throwing TemplateSyntaxError: unexpected char
has body: I am passing Jinja a dataset that includes time-bucket strings like "0Y-5Y". The tags are standard to my organization, so I prefer not to change them. However, the string is causing Jinja to throw a TemplateSyntaxError: unexpected char error. Can someone please explain why this particular error arises, and how I can get around it? I see from here that variables with space characters might throw similar error, but that does not apply in my case. It seems almost like Jinja is trying to parse the string as a number? I thought it was just a simple string used as the dictionary key? Is there a way to force Jinja not to do this, like with raw tags or similar? Here is my code: # https://realpython.com/blog/python/primer-on-jinja-templating/#flask-examples from jinja2 import Template data = [ {'name':'aaa','0Y-5Y':100,'5Y-25Y':50,'total':150} ,{'name':'bbb','0Y-5Y':10,'5Y-25Y':125,'total':135} ] html_ok = """ {% for item in data %} {{ item.name }} {{ item.total }} {% endfor %} """ html_error = """ {% for item in data %} {{ item.name }} {{ item.0Y-5Y }} {% endfor %} """ t=Template(html_ok) print t.render( data=data ) t=Template(html_error) print t.render( data=data ) And the output: aaa 150 bbb 135 Traceback (most recent call last): File "C:\Users\beRto\Desktop\jinja_number_key.py", line 23, in &lt;module&gt; t=Template(html_error) File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 945, in __new__ return env.from_string(source, template_class=cls) File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 880, in from_string return cls.from_code(self, self.compile(source), globals, None) File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 591, in compile self.handle_exception(exc_info, source_hint=source_hint) File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "&lt;unknown&gt;…
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/44190948
answer count: 1
accepted answer: http://stackoverflow.com/a/49345259
tagged with: templates

http://stackoverflow.com/a/49304257
answers question: http://stackoverflow.com/q/49304145
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85610700
has body: You can parse the date string to find the year. file_name = 'R:\Data\LUCZ_2017\MXDs\conservation_priority.mxd' time_str = time.ctime(os.stat(file_name).st_atime) year = int(time_str[-4:]) if year &gt;= 2014 and year &lt;= 2017: print('I was opened between 2014 and 2017')
type: Answer
accepted answer of: http://stackoverflow.com/q/49304145
has comment: http://stackoverflow.com/comment/85610598
downvote count: 0

http://stackoverflow.com/a/49380834
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85967503
has comment: http://stackoverflow.com/comment/86030438
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49374112
has body: I think you're problem is that your not authorising your credentials before making the call to the Calendar API but there is a couple of differences that you have that I use in my own implementation Use the following import statements from oauth2client.service_account import ServiceAccountCredentials from apiclient import discovery Use the from_json_keyfile_name method Authorise the credentials and pass it as a http argument when building the service Try this modification to your code: from apiclient import discovery from oauth2client.service_account import ServiceAccountCredentials import httplib2 SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE = 'GOOGLE_SECRET.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # Use the create_delegated() method and authorize the delegated credentials delegated_credentials = credentials.create_delegated('address@example.com') delegated_http = delegated_credentials.authorize(httplib2.Http()) google_calendar = discovery.build('calendar', 'v3', http=delegated_http) events = google_calendar.events().list( calendarId='address@example.com', maxResults=10 ).execute() I would also suggest setting calendarId='primary' in your API call so that you always return the primary calendar of the user who you currently have delegated credentials for. For more information on authenticating using ServiceAccountCredentials see the following link: http://oauth2client.readthedocs.io/en/latest/source/oauth2client.service_account.html
has comment: http://stackoverflow.com/comment/85958947
answers question: http://stackoverflow.com/q/49374112
downvote count: 0

http://stackoverflow.com/q/49335590
possible better answer: http://stackoverflow.com/a/49335680
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49335680
has comment: http://stackoverflow.com/comment/85673162
tagged with: technical-indicator
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49335686
has comment: http://stackoverflow.com/comment/85673276
has comment: http://stackoverflow.com/comment/85673237
has comment: http://stackoverflow.com/comment/85673053
has answer: http://stackoverflow.com/a/49335686
type: AnsweredQuestion
answer count: 2
has title: TypeError: object of type 'numpy.float64' has no len()
tagged with: pandas
score: 1
has body: I'm trying to calculate Money Flow Index for bitcoin price. To do this I'm using gdax, pandas and pyti. Here's my code: import gdax import pandas as pd from pyti.money_flow_index import money_flow_index as mfi public_client = gdax.PublicClient() historic = public_client.get_product_historic_rates('BTC-USD', granularity=60) pd.set_option('display.max_rows', 30) df = pd.DataFrame(historic) df.columns = ['Time', 'Low', 'High', 'Open', 'Close', 'Volume'] df = df.head(n=30) print(df, '\n') close_data = df['Close'][0] high_data = df['High'][0] low_data = df['Low'][0] volume_data = df['Volume'][0] period = 14 print(mfi(close_data, high_data, low_data, volume_data, period)) Here's the error I'm getting: Traceback (most recent call last): File "tiiii.py", line 18, in &lt;module&gt; print(mfi(close_data, high_data, low_data, volume_data, period)) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyti\money_ flow_index.py", line 19, in money_flow_index close_data, high_data, low_data, volume File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyti\catch_ errors.py", line 26, in check_for_input_len_diff arrays_len = [len(arr) for arr in args] File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pyti\catch_ errors.py", line 26, in &lt;listcomp&gt; arrays_len = [len(arr) for arr in args] TypeError: object of type 'numpy.float64' has no len() Edit: OK so now I'm using: close_data = df['Close'] high_data = df['High'] low_data = df['Low'] volume_data = df['Volume'] And here's what I'm getting: 0 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN .. ... 23 97.914228 24 97.816960 25 96.440309 26 94.668462 27 94.340548 28 91.255057 29 87.706573 [30 rows x 1 columns] I don't understand the order of the values. Also why am I not getting the full list? P.S. Thanks for the help Rahul and timgeb!
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85686160
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49342926
type: QuestionComment
has text: use random.choices for strings. https://docs.python.org/2/library/random.html. Also tried your code and I don't see why it should return an empty string

http://stackoverflow.com/q/49376263
upvote count: 2
score: 2
answer count: 1
has body: i am trying to integrate django app with paypal payment gateway, but i am not getting my signals fired, as well as i am not able to receive paypal ipn notifications, models.py class Pr_request(models.Model): number = models.CharField(max_length=20) subject = models.TextField(max_length=500) date_posted = models.DateTimeField(auto_now_add=True) class Purchase(models.Model): resourse = models.ForeignKey(Pr_request, related_name='purchase') purchaser = models.ForeignKey(User) purchased_at = models.DateTimeField(auto_now_add=True) views.py ti create payment_dic def payment_proccess(request, id): pr = get_object_or_404(Pr_request, id=id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % pr.fees.quantize(Decimal('.01')), 'item_name': 'purchase Req {}'.format(pr.number), 'invoice': '2', 'currency_code': 'USD', 'notifiy_url' : 'http://da...879.ngrok.io',#also i tried localhost 'return_url' : 'http://{}{}'.format(host, reverse('payment:done')), 'cancel_return': 'http://{}{}'.format(host, reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) print (" iam pyament process function") return render(request, 'payment/process.html', {'pr':pr, 'form':form}) signals.py def payment_notification(request, sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: print ("successful payment was done Lol") pr = get_object_or_404(Pr_request, id=ipn_obj.invoice) pur = Purchase.objects.get_or_create(resourse=pr, purchaser=request.user, tx='some text') pur.save() #mark the pr as paid else: print (" not able to pay") # payment was successful valid_ipn_received.connect(payment_notification) print ("signal is fired") init.py default_app_config = 'payment.apps.PaymentConfig' note that i am getting my signals fired whenever i reload my local server, so any idea about my mistake,thanks ..
downvote count: 0
tagged with: django
has title: Django, cannot receive paypal ipn notification
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49400140
has answer: http://stackoverflow.com/a/49400140
tagged with: python
favorite count: 0

http://stackoverflow.com/q/49313957
downvote count: 0
upvote count: 1
score: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I want to run one of the TensorFlow metrics on my labels and Estimator predictions as a summary to display in Tensorboard. Is there an easy way to do this, or does it require defining a Custom Estimator and model_fn?
has title: How to add a metric summary to a canned tensorflow Estimator?
tagged with: api
type: UnansweredQuestion
tagged with: high-level
tagged with: python
tagged with: tensorflow-estimator
answer count: 0

http://stackoverflow.com/q/49333339
upvote count: 4
score: 2
has comment: http://stackoverflow.com/comment/85668530
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58521037
possible better answer: http://stackoverflow.com/a/58521037
has answer: http://stackoverflow.com/a/49333593
has title: Swapping the inner and outer keys of a nested dictionary
accepted answer: http://stackoverflow.com/a/49333593
favorite count: 0
type: Question
has body: I have the following dictionary {'a':{'se':3, 'op':2}, 'b':{'se':4, 'op':3}} I need to convert it as follows: {'se':{'a':3, 'b': 4}, 'op':{'a':2,'b':3}} This is the following code I could come up with: from collections import defaultdict a = {'a':{'se':3, 'op':2}, 'b':{'se':4, 'op':3}} b = defaultdict(dict) for key1, value1 in a.items(): for key2, value2 in value1.items(): b[key2].update({key1: value2}) The following gets the job done but I am fond of one-liners. Is there a one-liner to the above or even a better way (better performance such as to eliminate two loops)?
answer count: 2
downvote count: 2
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/85742634
type: Comment
has text: Thank you for answer. I managed to get there by my self after a while and this was the exact solution i got to. And this is the kind of answer I was looking for when i made the question along with an explanation, instead of other people posting comments such as "this is a poor code attemp to avoid no code posted". Thank you for your time!
type: AnswerComment
comment on: http://stackoverflow.com/a/49370607
score: 2

http://stackoverflow.com/comment/85669933
has text: Because the functions are written that way.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49334210

http://stackoverflow.com/comment/85757971
type: QuestionComment
comment on: http://stackoverflow.com/q/49378685
has text: If the object has no name or other reference, it's garbage, and will be cleaned up by the garbage collector—immediately in CPython, or very soon in PyPy or Jython. So you can't access it.
score: 3
type: Comment

http://stackoverflow.com/comment/85826820
score: 0
type: Comment
has text: wow! I see... the data is stored in as a `list` of lists in a `row` in the data column. The headers are probably stored somewhere in the meta column
comment on: http://stackoverflow.com/a/49397849
type: AnswerComment

http://stackoverflow.com/a/49413167
type: Answer
has comment: http://stackoverflow.com/comment/85829749
has comment: http://stackoverflow.com/comment/85830507
has comment: http://stackoverflow.com/comment/85830144
has comment: http://stackoverflow.com/comment/85829412
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49413109
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85830060
has comment: http://stackoverflow.com/comment/85829211
accepted answer of: http://stackoverflow.com/q/49413109
has body: Create a variable in your route to receive the type of currency. The route variable is passed as an argument to the view function. The / route doen't have the variable, so provide a default in that case. import functools def verify_currency(f): @functools.wraps(f) def wrapper(currency_type): if currency_type not in ['dollars', 'euros']: #can add more currencies to list later return flask.render_template("error.html") #or redirect return f(currency_type) return wrapper @app.route('/', methods=['POST', 'GET'], defaults={'currency': 'euro'}) @app.route('/currency/&lt;currency&gt;', methods=['POST', 'GET']) @verify_currency def dollar_page(currency): form = MyTextForm() values = labels = None if form.validate_on_submit(): values = app.process(request.form["values"]) labels = get_data() return render_template('currency.html', currency=currency, labels=labels, values=values)
has comment: http://stackoverflow.com/comment/85829578

http://stackoverflow.com/comment/85627496
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49312895
has text: I am not sure what you are trying to achieve. But make sure you don't include a slash in the start of `templates`. Do it from `/templates/` to `templates/....`.

http://stackoverflow.com/comment/85658583
has text: Try changing uses of `+` to `,`
score: 1
comment on: http://stackoverflow.com/q/49328339
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49348447
accepted answer of: http://stackoverflow.com/q/49348396
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49348396
downvote count: 1
has body: I think simpliest is use list comprehension if no NaNs values: #import ast #one possible way for convert string to tuples #df['aid'] = df['aid'].apply(ast.literal_eval) print (df['aid'].head().apply(type)) 0 &lt;class 'tuple'&gt; 1 &lt;class 'tuple'&gt; 2 &lt;class 'tuple'&gt; 3 &lt;class 'tuple'&gt; 4 &lt;class 'tuple'&gt; Name: aid, dtype: object df['aid'] = [tuple(sorted(x)) for x in df['aid']] print (df) pid aid 0 0000000F (0BDEAC61, 288E046F) 1 00000017 (4A259AFA, 7795AF0D, 7DA84B6E) 2 00000019 (3A25A1FE, 8123B8CF) 3 00000025 (28045D98, 8043B6E5, 81195E5D) 4 0000003A (7D566708, 7F5583AE) Or: df['aid'] = df['aid'].apply(sorted) print (df) pid aid 0 0000000F [0BDEAC61, 288E046F] 1 00000017 [4A259AFA, 7795AF0D, 7DA84B6E] 2 00000019 [3A25A1FE, 8123B8CF] 3 00000025 [28045D98, 8043B6E5, 81195E5D] 4 0000003A [7D566708, 7F5583AE]
score: 3
type: Answer
upvote count: 4

http://stackoverflow.com/q/49410886
tagged with: file
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49411157
has comment: http://stackoverflow.com/comment/85823983
has title: Should json.load() or json.dump() be used with an open() context manager?
type: Question
tagged with: contextmanager
linked to: http://stackoverflow.com/q/7395542
linked to: http://stackoverflow.com/q/2333872
has comment: http://stackoverflow.com/comment/85825697
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/85828488
favorite count: 0
upvote count: 2
score: 2
has body: As an example, let's say we are checking a preferences.json file with the contents of preferences.json { "background_color": "red" } Then we read/modify/write the preferences back using the Python json module. The following two examples both function the same except one uses the open() context manager and one doesn't. change_pref_with_CM.py import json # Load the user preferences with open('preferences.json') as prefs_file: prefs = json.load(prefs_file) print(prefs['background_color']) # Prints 'red' # Change the user's background_color preference to blue prefs['background_color'] = 'blue' # Save the user preferences with open('preferences.json', 'w') as prefs_file: json.dump(prefs, prefs_file) change_pref_without_CM.py import json # Load the user preferences prefs = json.load(open('preferences.json')) print(prefs['background_color']) # Prints 'red' # Change the user's background_color preference to blue prefs['background_color'] = 'blue' # Save the user preferences prefs = json.dump(prefs, open('preferences.json', 'w')) For normal file reading/writing I always use a context manager and handle all logic inside the context manager. But in this example the file is being used just long enough to either populate a dict or write a dict to a file. So the example not using a context manager seems much cleaner to me. I worry that since the files are being opened "anonymously" there is nothing to call close() on and I don't know if the json module handles that with a context manager internally or if I would just be leaking file descriptors. I'm sure using a context manager just in case is the safe way to go, but at the same time I would like to know how the json module handles file descriptors (or is it file objects?) I went looking for the source for the json module but after finding it and searching for "dump" and "load" and finding nothing I'm not sure what to check next. I'm not nearly proficient enough with C to understand what's going on in there.
downvote count: 0

http://stackoverflow.com/comment/86170154
has text: I used your second implementation: `line = select_text_regex.sub(r"\g<to_replace>\1",lambda m: m.group('first').upper(), line)` It says: `TypeError: 'str' object cannot be interpreted as an integer`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49395961

http://stackoverflow.com/comment/85769571
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49378987
has text: I probably found what was missing: actions.click()...

http://stackoverflow.com/comment/85686145
type: Comment
type: QuestionComment
has text: As in it generates strings lower than 10 characters.
comment on: http://stackoverflow.com/q/49342926
score: 0

http://stackoverflow.com/comment/95074291
score: 1
comment on: http://stackoverflow.com/a/49362032
has text: Yep, this gives 50-500x times faster result in my case, training with images.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49302035
favorite count: 0
has answer: http://stackoverflow.com/a/49317009
tagged with: optimization
linked to: http://stackoverflow.com/q/46988797
type: Question
tagged with: matplotlib
tagged with: curve-fitting
score: 1
has title: Plot paraboloid surface fitting
has comment: http://stackoverflow.com/comment/85617054
type: AnsweredQuestion
has body: How can I plot the paraboloid after fitting it using Python? in order to get that plot import numpy as np import scipy.optimize as opt import matplotlib.pyplot as plt doex = [0.4,0.165,0.165,0.585,0.585] doey = [.45, .22, .63, .22, .63] doez = np.array([1, .99, .98,.97,.96]) def paraBolEqn(data,a,b,c,d): x,y = data return -(((x-b)/a)**2+((y-d)/c)**2)+1.0 popt,pcov=opt.curve_fit(paraBolEqn,np.vstack((doex,doey)),doez,p0=[1.5,0.4,1.5,0.4]) print(popt)
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49317009
tagged with: python
answer count: 1

http://stackoverflow.com/q/49324850
tagged with: user-interface
answer count: 1
favorite count: 0
tagged with: oop
has answer: http://stackoverflow.com/a/49328283
score: 1
tagged with: python
has body: MainTicTacToe.py import tkinter as tk import MenubarCommand as mbc class Game(tk.Frame): def __init__(self,parent): tk.Frame.__init__(self,parent) self.parnt=parent # self.parnt.geometry('500x300') self.parnt.title("Tic Tac Toe") # self.pack() menubar=tk.Menu(parent) # 'settings' menu settingsOption=tk.Menu(menubar, tearoff=0) settingsOption.add_command(label='Player Settings', command=self.doit) settingsOption.add_command(label='Board Settins', command=self.doit) menubar.add_cascade(label='Setings', menu=settingsOption) # without using this method, menubar isn't shown in Frame self.parnt.config(menu=menubar) def doit(self): root=self.win() set=mbc.playerSettings(root) # print(set.p1name) root.mainloop() def win(self): return tk.Tk() def main(): root=tk.Tk() Game(root) root.mainloop() main() MenubarCommand.py import tkinter as tk class playerSettings(tk.Frame): def __init__(self,parent=tk.Frame): tk.Frame.__init__(self,parent) self.parnt=parent self.parnt.title("Player Setting") self.p1name='Player 1' self.p2name='Player 2' self.p1symbol='x' self.p2symbol='o' # **********************************# self.p1NameLabel = tk.Label(parent, text='Player 1: Name ') self.p1NameLabel.grid(row=0, column=0) self.p1NameEntry = tk.Entry(parent) self.p1NameEntry.insert(0,self.p1name) self.p1NameEntry.bind('&lt;FocusIn&gt;', lambda event:self.p1NameEntry.delete(0,'end')) self.p1NameEntry.grid(row=0, column=1) apply=tk.Button(parent, text="Apply Settings", fg='white', bg='gray', command=self.saveStat) apply.grid(row=2, rowspan=1, columnspan=4) def saveStat(self): print('Settings Window Destroyed') self.p1name=self.p1NameEntry.get() print(self.p1name) self.parnt.destroy() I want to change the value of attribute of an instance in one file from the instance of another class in another file already created. When I change default Player name in MenubarComman.py file, I want to access the changed name from MainTicTacToe.py class. How can I do this? I'm new new in Python. Thanks in Advance.
type: Question
has title: Updating value of attribute of a created instance of a class from an instance of another class created later, in tkinter python 3
tagged with: tkinter
downvote count: 0
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/85782108
type: AnswerComment
comment on: http://stackoverflow.com/a/49389709
score: 0
type: Comment
has text: Yeah, I didn't think anyone would see this question before I finished answering it... My intention for posting the question was to fill a google gap rather than to actually get help, since "create a dataframe from a list using sparksession pyspark" wasn't returning anything immediately useful for me and it's such a basic question I don't think everyone should have to dig through the documentation for it when they're new to spark.

http://stackoverflow.com/comment/138234608
comment on: http://stackoverflow.com/a/78394817
score: 0
type: Comment
has text: Related to this suggestion, there is also [Voici](https://github.com/voila-dashboards/voici) in development. It is essentially Voila run with JupyterLite so that allows the Python handling code to be run inside the users browser so you don't need a server that serves active Python, just a static files hosting site or server. I note the OP mentioned using ipywidgets and bokeh and both of those work with the pyodide kernel that underlies JupyterLite.
type: AnswerComment

http://stackoverflow.com/comment/85696760
type: Comment
comment on: http://stackoverflow.com/a/49333807
score: 0
type: AnswerComment
has text: Thanks again Martijn. If this were real code, would you leave it as f.read(28 * 28)? It seems clearer to me.

http://stackoverflow.com/comment/85711732
type: QuestionComment
comment on: http://stackoverflow.com/q/49301983
type: Comment
has text: it should be `x1 = x[np.where(np.logical_and(x>0 & x<10))]`, try this
score: 0

http://stackoverflow.com/q/49403610
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/25234782
answer count: 1
tagged with: rolling-average
favorite count: 0
linked to: http://stackoverflow.com/q/42027131
type: Question
has comment: http://stackoverflow.com/comment/85808747
duplicate of: http://stackoverflow.com/q/42027131
has body: I have a df like this: a001 a002 a003 a004 a005 time_axis 2017-02-07 1 NaN NaN NaN NaN 2017-02-14 NaN NaN NaN NaN NaN 2017-03-20 NaN NaN 2 NaN NaN 2017-04-03 NaN 3 NaN NaN NaN 2017-05-15 NaN NaN NaN NaN NaN 2017-06-05 NaN NaN NaN NaN NaN 2017-07-10 NaN 6 NaN NaN NaN 2017-07-17 4 NaN NaN NaN NaN 2017-07-24 NaN NaN NaN 1 NaN 2017-08-07 NaN NaN NaN NaN NaN 2017-08-14 NaN NaN NaN NaN NaN 2017-08-28 NaN NaN NaN NaN 5 And I would like to make a rolling mean for each row on the previous 3 valid values(not empty rows) and save in another df: last_3 time_axis 2017-02-07 1 # still there is only a row 2017-02-14 1 # only a valid value(in the first row) -&gt; average is the value itself 2017-03-20 1.5 # average on the previous rows (only 2 rows contain value-&gt; (2+1)/2 2017-04-03 2 # average on the previous rows with non-NaN values(2017-02-14 excluded) (2+3+1)/3 2017-05-15 2 # Same reason as the previous row 2017-06-05 2 # Same reason 2017-07-10 3.6 # Now the considered values are:2,3,6 2017-07-17 4.3 # considered values: 4,6,3 2017-07-24 3.6 # considered values: 1,4,6 2017-08-07 3.6 # no new values in this row, so again 1,4,6 2017-08-14 3.6 # same reason 2017-08-28 3.3 # now the considered values are: 5,1,4 I was trying deleting the empty rows in the first dataframe and then apply rolling and mean, but I think it is the wrong approach(df1 in my example already exist): df2 = df.dropna(how='all') df1['last_3'] = df2.mean(axis=1).rolling(window=3, min_periods=3).mean()
tagged with: dataframe
tagged with: python
has title: Moving average in a pandas dataframe on valid values (non empty rows)
has answer: http://stackoverflow.com/a/49403848
accepted answer: http://stackoverflow.com/a/49403848
duplicate of: http://stackoverflow.com/q/25234782
type: AnsweredQuestion
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/49433220
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
has body: I use psycopg2 to to join two tables together. But for some reason the process is taking way too long. Both tables have index. The tables have around 280 rows and 5-6 columns. But they do have a geometry column with complex boundaries of countries. This is how the query looks like: sqlstr = """CREATE TABLE {new_table_name} AS ( SELECT {geom_table_columns}, {added_columns} FROM {geom_table} INNER JOIN {temp_table} ON (g.{id} = {temp_table}.{id}) ); """.format(** { 'new_table_name': new_table, 'geom_table': geom_table_name, 'geom_table_columns': geom_table_columns, 'temp_table': table_name_temp, 'id': geom_table_id, 'added_columns': added_columns }) Is there any way to make this inner join query faster?
has comment: http://stackoverflow.com/comment/85869041
has comment: http://stackoverflow.com/comment/85903977
has comment: http://stackoverflow.com/comment/85904063
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/85868682
downvote count: 0
upvote count: 1
has title: How to speed up join query in postgresql
has comment: http://stackoverflow.com/comment/85870054
has comment: http://stackoverflow.com/comment/85868390

http://stackoverflow.com/comment/85803185
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49395695
type: Comment
has text: Sorry if I did not get you, but doesn’t the error message imply Sublime is not aligned with the user’s ‘PATH’ environment variable?

variables
tags question: http://stackoverflow.com/q/49344449
tags question: http://stackoverflow.com/q/49323696
tags question: http://stackoverflow.com/q/49321247
tag name: variables
tags question: http://stackoverflow.com/q/49414862
tags question: http://stackoverflow.com/q/49328869
tags question: http://stackoverflow.com/q/49305721
tags question: http://stackoverflow.com/q/49359052
tags question: http://stackoverflow.com/q/49328084
tags question: http://stackoverflow.com/q/49314266
tags question: http://stackoverflow.com/q/49284583
tags question: http://stackoverflow.com/q/49401692
type: Tag
tags question: http://stackoverflow.com/q/49288384
tags question: http://stackoverflow.com/q/49413268
tags question: http://stackoverflow.com/q/49436376
tags question: http://stackoverflow.com/q/49303160

http://stackoverflow.com/q/49348263
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: pandas
tagged with: python
has title: BeautifulSoup page number
has body: I'm trying to extract text from the online version of The Wealth of Nations and create a data frame where each observation is a page of the book. I do it in a roundabout way, trying to imitate something similar I did in R, but I was wondering if there was a way to do this directly in BeautifulSoup. What I do is first get the entire text from the page: import pandas as pd import requests from bs4 import BeautifulSoup import re r = requests.get('https://www.gutenberg.org/files/38194/38194-h/38194-h.htm') soup = BeautifulSoup(r.text,'html.parser') But from here on, I'm just working with regular expressions and the text. I find the beginning and end of the book text: beginning = [a.start() for a in re.finditer(r"BOOK I\.",soup.text)] beginning end = [a.start() for a in re.finditer(r"FOOTNOTES",soup.text)] book = soup.text[beginning[1]:end[0]] Then I remove the carriage returns and new lines and split on strings of the form "[Pg digits]" and put everything into a pandas data frame. book = book.replace('\r',' ').replace('\n',' ') l = re.compile('\[[P|p]g\s?\d{1,3}\]').split(book) df = pd.DataFrame(l,columns=['col1']) df['page'] = range(2,df.shape[0]+2) There are indicators in the HTML code for page numbers of the form &lt;span class='pagenum'&gt;&lt;a name="Page_vii" id="Page_vii"&gt;[Pg vii]&lt;/a&gt;&lt;/span&gt;. Is there a way I can do the text extraction in BeautifulSoup by searching for text between these "spans"? I know how to search for the page markers using findall, but I was wondering how I can extract text between those markers.
upvote count: 2
accepted answer: http://stackoverflow.com/a/49348929
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49348929
score: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/85623136
score: 0
comment on: http://stackoverflow.com/q/49309899
type: QuestionComment
has text: thanks for the sample input, now what output to do you want?
type: Comment

http://stackoverflow.com/q/49353023
has comment: http://stackoverflow.com/comment/85711863
tagged with: excel
favorite count: 0
type: AnsweredQuestion
tagged with: win32com
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49419933
type: Question
has comment: http://stackoverflow.com/comment/85707700
answer count: 2
has answer: http://stackoverflow.com/a/49419933
possible better answer: http://stackoverflow.com/a/49415776
tagged with: vba
downvote count: 0
upvote count: 1
has body: I'm trying to get the interior colours of a range of cells in Excel using win32com/python. Looping through each cell is not an option as that takes 3 to 5 seconds to complete while the colours change every second. Using Range.Value(11) seems like it can help, but win32com doesn't like it when any parameters are passed to Range.Value. import win32com.client as win32 excel = win32.Dispatch('excel.application') fileName = r"myFile.xlsm" myBook = excel.Workbooks(fileName) mySheet = myBook.Sheets('Sheet1') myRange = mySheet.Range('I3:AL32') myState = myRange.Value # is acceptable but useless myState = myRange.Value(11) # TypeError: 'tuple' object is not callable Executing myRange("I3:AL32").Value(11) in VBA within Excel works just fine, but I cannot create a custom UDF and use Application.Run from within win32com either because there is already VBA code running inside the base Excel file (which is what's changing the cell colours in the first place). Is there another way to pass that parameter into Range.Value?
has answer: http://stackoverflow.com/a/49415776
has title: Passing parameter to Excel's Range.Value(RangeValueDataType) in win32com

http://stackoverflow.com/comment/85830861
has text: would you mind test timing for my solution as well ? Thank you
type: AnswerComment
comment on: http://stackoverflow.com/a/49413710
score: 1
type: Comment

http://stackoverflow.com/comment/85721909
has text: Changing the name of my computer fixed it! Thank you so much!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49353514
type: AnswerComment

http://stackoverflow.com/q/49309270
tagged with: pip
accepted answer: http://stackoverflow.com/a/49409241
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49409241
has title: Upgrading pip version to master branch in github before tox install dependencies
has body: I want to upgrade my pip version to pip 10.0.0.dev0 with master pip version in github like pip install -I https://github.com/pypa/pip/archive/master.zip#egg=pipbefore tox installs the dependencies. Is there a way to this? My current tox file is like below [tox] envlist = py36 [testenv] passenv = * deps= -rrequirements.txt commands= pip --version pytest tests
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: tox
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85746768
has text: Are you running the `main.py` file as the script? Then you are breaking the expectations of `package` being a proper top-level package. Put scripts **outside** of the package or use `python -m package.main` to run a nested module.
type: QuestionComment
comment on: http://stackoverflow.com/q/49372505
score: 0
type: Comment

http://stackoverflow.com/a/49393603
type: Answer
answers question: http://stackoverflow.com/q/49387559
has body: Firstly, your check function is incorrect. From this post, we see that the conditions required are that the sum of each pair of sides is greater than the other side. As @david explained: Let's say that a, b, c is the sides of the triangle. Therefore, it must be satisfy this criteria: a + b > c a + c > b b + c > a You are only checking to see if the sum of the two smaller sides is greater than the largest. Furthermore, your function would fail for cases where the largest side is duplicated. For example, the values 1, 4, 4 form a valid triangle but your function check(1, 4, 4) returns False. That being said, there is very little you can do to avoid checking all combinations of 3 values. from itertools import combinations [(x, y, z) for (x, y, z) in combinations(test, 3) if ((x+y) &gt; z) and ((x+z) &gt; y) and ((y+z) &gt; x)] #[(2, 5, 4), (2, 3, 4), (5, 3, 4)] You could make a marginal speed improvement by sorting the list. This helps because the code can short-circuit because the first condition will fail (and you don't have to check the other two). For example, these are the sorted combinations of 3 sides from your example list: &gt;&gt;&gt; test = [2,789,5,3,3237,4] &gt;&gt;&gt; list(combinations(sorted(test), 3)) [(2, 3, 4), (2, 3, 5), (2, 3, 789), (2, 3, 3237), (2, 4, 5), (2, 4, 789), (2, 4, 3237), (2, 5, 789), (2, 5, 3237), (2, 789, 3237), (3, 4, 5), (3, 4, 789), (3, 4, 3237), (3, 5, 789), (3, 5, 3237), (3, 789, 3237), (4, 5, 789), (4, 5, 3237), (4, 789, 3237), (5, 789, 3237)] In the third example, x = 2, y = 3, and z = 789. The first condition (x+y) &gt; z will fail and you won't have to check the other two. I've included some timing results to show that sorting is slightly faster. Update If you wanted to avoid duplicates, you can use a set comprehension: {(x, y, z) for (x, y, z) in combinations(sorted(test), 3) if ((x+y) &gt; z) and ((x+z) &gt; y) and ((y+z) &gt; x)} Timing Results # make list of random numbers import numpy as np N = 100 test = [np.random.rand…
score: 0

http://stackoverflow.com/a/49454578
answers question: http://stackoverflow.com/q/49378486
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49378486
has body: I found the answer to my problem. Seems that I used the wrong numpy version. With numpy 1.11.0 and the following stage packages it was working: - gcc - gfortran - python-dev - libc6 - libblas3 - liblapack3 - libopenblas-dev - liblapack-dev - cython
type: AcceptedAnswer

http://stackoverflow.com/q/49326588
has comment: http://stackoverflow.com/comment/85657694
has body: I need to have two different locale directories in my django project. Because there are some translations in third-party apps like rest_auth which are not available for my language. We translated them manually in .po file, but the problem is whenever I run: python manage.py makemessages It scans the project and get rid of all the manually translated strings! So I want a directory for third party app translations (which django ignores it and doesn't update it), and another locale directory for my own stuff which get updated everytime I run makemessages. p.s: I already added the second locale folder to LOCALE_PATHS in settings.
has title: How to have 2 different locale directories in django project?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85658189
downvote count: 0
has comment: http://stackoverflow.com/comment/85657365
tagged with: django
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/77736289
answer count: 1
tagged with: internationalization
has comment: http://stackoverflow.com/comment/85657475
has comment: http://stackoverflow.com/comment/85656339
has comment: http://stackoverflow.com/comment/85658443
has comment: http://stackoverflow.com/comment/85657403
score: 1

http://stackoverflow.com/a/49518604
has body: scipy's nquad does numerical integration only on bounded rectangular domains. The fact that your integral converges at all is due to the exp(-r^2)-type weight of the PDF (see here for its explicit form). Hence, you need Hermite quadrature in 2D. Some articles exist on this topic, and quadpy (a project of mine) implements those. You'll first need to bring your integral into a form that contains the exact weight exp(-r**2) where r**2 is x[0]**2 + x[1]**2. Then you cut this weight and feed it into quadpy's e2r2 quadrature: import numpy import quadpy def integrand(x): return 1 / numpy.pi * numpy.ones(x.shape[1:]) val = quadpy.e2r2.integrate( integrand, quadpy.e2r2.RabinowitzRichter(3) ) print(val) 1.0000000000000004
score: 1
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/49433077
type: Answer
has comment: http://stackoverflow.com/comment/86265832
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49433077

http://stackoverflow.com/comment/85752336
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49355810
has text: tacaswell - If you increase the length of the annotation text (eg. 'extra_information_string') the first few characters become visible in the extreme top right hand corner of the figure.
score: 0

http://stackoverflow.com/comment/86702127
has text: I can't get the first part of this to work, unfortunately. I change `detail_options.html` but can't get what's in there to render. All that renders is the default ModelMultipleChoiceField widget. I'm having a hard time figuring out how to debug this, since I've followed this answer exactly, and can't even get an error to lead me somewhere. Maybe this has to do with django-crispy-forms?
type: Comment
comment on: http://stackoverflow.com/a/49494136
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85584032
type: Comment
type: QuestionComment
has text: did you tried this, `path('blogs/<int:blog_pk>/authors/<int:author_pk>', views.BlogAuthorList.as_view(), name='blogauthor-detail'),`
comment on: http://stackoverflow.com/q/49286928
score: 1

http://stackoverflow.com/q/49408660
accepted answer: http://stackoverflow.com/a/49408792
has title: Adding a Day to a Date, based on another column
has answer: http://stackoverflow.com/a/49408792
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
has body: I have the issue that I am combining two data sets and they have different definitions of midnight. I therefore want to add a day to one of the dataset's for every occurrence of midnight so that they both follow the same date setup. I have structured my date and time by: df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%m/%Y') df['Hour'] = pd.to_datetime(df['Hour']).dt.strftime('%H:%M') And then I am trying to amend any occurrence of 00:00:00 so that it is one day later: df.loc['Hour' == '00:00:00', 'Date'] = pd.DatetimeIndex(df.Date) + timedelta(days=1) However i keep raising a KeyError: raise KeyError("cannot use a single bool to index into setitem") KeyError: 'cannot use a single bool to index into setitem Any help would be greatly appreciated. Aim: Input: Date | Hour --------------------- 19/06/2016 | 23:30 19/06/2016 | 23:45 19/06/2016 | 00:00 20/06/2016 | 00:15 20/06/2016 | 00:30 Output: Date | Hour --------------------- 19/06/2016 | 23:30 19/06/2016 | 23:45 20/06/2016 | 00:00 20/06/2016 | 00:15 20/06/2016 | 00:30
favorite count: 0
possible better answer: http://stackoverflow.com/a/49408806
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85818611
tagged with: pandas
has answer: http://stackoverflow.com/a/49408806
score: 1

http://stackoverflow.com/q/49337960
score: 5
tagged with: nmf
has comment: http://stackoverflow.com/comment/85691138
has answer: http://stackoverflow.com/a/49406777
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am trying to build a recommendation system using Non-negative matrix factorization. Using scikit-learn NMF as the model, I fit my data, resulting in a certain loss(i.e., reconstruction error). Then I generate recommendation for new data using the inverse_transform method. Now I do the same using another model I built in TensorFlow. The reconstruction error after training is close to that obtained using sklearn's approach earlier. However, neither are the latent factors similar to one another nor the final recommendations. One difference between the 2 approaches that I am aware of is: In sklearn, I am using the Coordinate Descent solver whereas in TensorFlow, I am using the AdamOptimizer which is based on Gradient Descent. Everything else seems to be the same: Loss function used is the Frobenius Norm No regularization in both cases Tested on the same data using same number of latent dimensions Relevant code that I am using: 1. scikit-learn approach: model = NMF(alpha=0.0, init='random', l1_ratio=0.0, max_iter=200, n_components=2, random_state=0, shuffle=False, solver='cd', tol=0.0001, verbose=0) model.fit(data) result = model.inverse_transform(model.transform(data)) 2. TensorFlow approach: w = tf.get_variable(initializer=tf.abs(tf.random_normal((data.shape[0], 2))), constraint=lambda p: tf.maximum(0., p)) h = tf.get_variable(initializer=tf.abs(tf.random_normal((2, data.shape[1]))), constraint=lambda p: tf.maximum(0., p)) loss = tf.sqrt(tf.reduce_sum(tf.squared_difference(x, tf.matmul(w, h)))) My question is that if the recommendations generated by these 2 approaches do not match, then how can I determine which are the right ones? Based on my use case, sklearn's NMF is giving me good results, but not the TensorFlow implementation. How can I achieve the same using my custom implementation?
has comment: http://stackoverflow.com/comment/85677522
has title: SKLearn NMF Vs Custom NMF
type: UnansweredQuestion
upvote count: 5
tagged with: python
tagged with: recommendation-engine
has comment: http://stackoverflow.com/comment/85677123
has comment: http://stackoverflow.com/comment/85677620

http://stackoverflow.com/comment/85811759
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49399612
has text: yes KeyError: None when i didnt set "flask_config" as environment variable . when i set "flask_config" as environment variable .i got KeyError = "flask_config environment variable path"

http://stackoverflow.com/comment/85752935
comment on: http://stackoverflow.com/q/49375101
type: Comment
has text: @jasonharper I think you're right on what file and enca commands do. But as you could see that utf-8 codec still find invalid start byte and could not decode the whole file.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85887267
score: 0
type: Comment
type: AnswerComment
has text: Yes,table exists and the role has administrator access.
comment on: http://stackoverflow.com/a/49433602

http://stackoverflow.com/comment/85660055
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49328978
has text: use `sort_order={}` instead of `sort_order=[]` will be better? `sort_order.index(id)` should be slower than dict[id]
score: 2

http://stackoverflow.com/q/49384742
has answer: http://stackoverflow.com/a/49415580
tagged with: aircrack-ng
has title: i can't kill multiprocessing or threading in python when try to run airodump
score: 0
has comment: http://stackoverflow.com/comment/85772762
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/85789495
has comment: http://stackoverflow.com/comment/85770922
has comment: http://stackoverflow.com/comment/85787529
tagged with: multiprocessing
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85771800
has comment: http://stackoverflow.com/comment/85778057
has body: I try to run Airodump-ng Wlan0mon in python code using Threading or Multiprocess but i can't kill the process i try all solution in this site but it not work my code is def RubAirdump(): try: def ai(): global Airdump Airdump = subprocess.Popen(["airodump-ng {}".format(CheckModeMonter())], stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True,preexec_fn=os.setsid()) airo1 = threading.Thread(target=ai) airo1.start() time.sleep(5) print(Airdump.stdout.read().decode("utf-8")) except Exception as EXC3: print("[-] There is some Error that say", EXC3) sys.exit() i'm trying to use (os.kill) and (os.killpg) but its not work all i wan't is to make airodump run for 5 or 10 second then stop get the result printed and returned by this fuction checkModeMonter() is returned to me wlan0mon I want any way to do this ,, thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85771471
linked to: http://stackoverflow.com/q/4789837
tagged with: python

http://stackoverflow.com/q/49349520
score: 1
tagged with: validation
has title: Validate input text in a QPlainTextEdit
downvote count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/85703155
upvote count: 1
has body: I am writing a simple editor program. How can I check the input text? For example, when the input contains "print", re-format it (color, bold, etc). How to check it continuously? def recognizer(self): while True: if "word" in self.plainTextEdit.toplainText : print("True")
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/40155268
tagged with: python
tagged with: qplaintextedit
has comment: http://stackoverflow.com/comment/85701364
answer count: 0
tagged with: pyqt
type: UnansweredQuestion

http://stackoverflow.com/a/49417986
type: Answer
answers question: http://stackoverflow.com/q/49417456
score: 0
has body: Another way you might achieve this is with JavaScript ...you could have a function in JavaScript called include_form which will be used to include the form inside a div and it might look like this function include_form(){ document.getElementById("form_div").innerHTML = "{% include 'folder/form.html'%}"; this.location.reload() }

http://stackoverflow.com/a/49333392
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49291048
has body: The multiprocessing package is incompatible with Eventlet. Here is a comment from the Evenlet maintainer. You should probably consider moving that functionality to a separate process (another microservice maybe) where you are not bound to Eventlet.
score: 1
accepted answer of: http://stackoverflow.com/q/49291048
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49419678
tagged with: apache-spark-sql
accepted answer: http://stackoverflow.com/a/49420723
tagged with: pyspark
has answer: http://stackoverflow.com/a/49420723
tagged with: python
score: 2
has title: Spark VectorAssembler Error - PySpark 2.3 - Python
type: AnsweredQuestion
tagged with: apache-spark
upvote count: 2
downvote count: 0
answer count: 1
has body: I am working with pySpark 2.3.0 and have a very simple Spark dataframe I created to test the functionality of VectorAssembler. This is a subset of a larger dataframe where I only picked a few numeric (double data type) columns: &gt;&gt;&gt;cols = ['index','host_listings_count','neighbourhood_group_cleansed',\ 'bathrooms','bedrooms','beds','square_feet', 'guests_included',\ 'review_scores_rating'] &gt;&gt;&gt;test = df[cols] &gt;&gt;&gt;test.take(3) [Row(index=0, host_listings_count=1, neighbourhood_group_cleansed=None, bathrooms=1.5, bedrooms=2.0, beds=3.0, square_feet=None, guests_included=1, review_scores_rating=100.0), Row(index=1, host_listings_count=1, neighbourhood_group_cleansed=None, bathrooms=1.5, bedrooms=2.0, beds=3.0, square_feet=None, guests_included=1, review_scores_rating=100.0), Row(index=2, host_listings_count=1, neighbourhood_group_cleansed=None, bathrooms=1.5, bedrooms=2.0, beds=3.0, square_feet=None, guests_included=1, review_scores_rating=100.0)] From the above it seems to me that there is nothing wrong with this Spark dataframe. So I then create the assembler as shown below and get the shown error. What could possibly have gone wrong? &gt;&gt;&gt;from pyspark.ml.feature import VectorAssembler &gt;&gt;&gt;assembler = VectorAssembler(inputCols=cols, outputCol="features") &gt;&gt;&gt;output = assembler.transform(test) &gt;&gt;&gt;output.take(3) Py4JJavaError: An error occurred while calling o279.collectToPython. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 5.0 failed 1 times, most recent failure: Lost task 0.0 in stage 5.0 (TID 10, localhost, executor driver): org.apache.spark.SparkException: Failed to execute user defined function($anonfun$3: (struct) => vector) at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source) at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43) at org.apache.spark.sql.execution.WholeStageCodegenE…
favorite count: 0
type: Question

http://stackoverflow.com/q/49364256
has title: Merge 2 dataframes on Days and Month
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49365527
downvote count: 0
favorite count: 0
score: 3
tagged with: pandas
has body: I have the following dataframes: print(df1) day month quantity Operation_type 21 6 6 2 24 6 4 2 ... print(df2) day month quantity Operation_type 22 6 10 1 23 6 15 1 ... I would like to get the following dataset: print(final_df) day month quantity Operation_type 21 6 6 2 22 6 10 1 23 6 15 1 24 6 4 2 ... I tried using: final_df = pd.merge(df1, df2, on=['day','month']) but it creates a huge dataset and does not seem to be working properly; Furthermore, if day and month are the same, I would like to paste the line whose Operation_type == 2 before the one with ==1. How can I solve this problem?
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/49364283
type: Question
answer count: 2

http://stackoverflow.com/q/49434908
has comment: http://stackoverflow.com/comment/85915750
tagged with: anaconda
has title: Unable to Install Kivy in Anaconda Prompt on Windows 10 python 3.6
has comment: http://stackoverflow.com/comment/85872984
tagged with: python
tagged with: kivy
type: Question
answer count: 0
has body: I'm trying to install Kivy through Anaconda Prompt and keep running into a message saying the Kivy file does not exist. I may be having trouble with properly inputting the directory to the folder containing the download. Any thoughts?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86012522
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/49280574
tags question: http://stackoverflow.com/q/49425018
tags question: http://stackoverflow.com/q/49390950
tags question: http://stackoverflow.com/q/49364256
tags question: http://stackoverflow.com/q/49370456
tags question: http://stackoverflow.com/q/49308290
tag name: merge
tags question: http://stackoverflow.com/q/49421619
tags question: http://stackoverflow.com/q/49329997
tags question: http://stackoverflow.com/q/49287395
tags question: http://stackoverflow.com/q/49404384
tags question: http://stackoverflow.com/q/49382937
tags question: http://stackoverflow.com/q/49364754
tags question: http://stackoverflow.com/q/49284466
tags question: http://stackoverflow.com/q/49302884
tags question: http://stackoverflow.com/q/49336657
tags question: http://stackoverflow.com/q/49425936
tags question: http://stackoverflow.com/q/49328466

http://stackoverflow.com/a/55570958
has body: Setting debug=False does solve the problem, but not with Jupyter notebook and Spyder. The code goes into limbo when executed with notebook/spyder. Change your code to debug=False and execute it in PyQt console that comes with Anaconda Navigator. It works.
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/109254236
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49370550
has comment: http://stackoverflow.com/comment/109181459

http://stackoverflow.com/a/60172473
has body: Zipping cursor.column_names with the row values is a good workaround: cursor = connection.cursor(prepared=True) query = 'SELECT foo, bar FROM some_table WHERE a = %s AND b = %s' a = 1 b = 42 cursor.execute(query, [a, b]) rows = cursor.fetchall() for row in rows: result = dict(zip(cursor.column_names, row)) print(result['foo'], result['bar']) See https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html for documentation on MySQLCursor.column_names.
has comment: http://stackoverflow.com/comment/110465881
answers question: http://stackoverflow.com/q/49428935
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/110493169
downvote count: 0
type: Answer

google-cloud-datastore
tags question: http://stackoverflow.com/q/49369438
tag name: google-cloud-datastore
type: Tag

http://stackoverflow.com/a/49384639
type: Answer
score: 0
type: AcceptedAnswer
has body: This just worked for me in the Terminal (Note that I have the Sikuli app in its own folder inside the Applications folder): java -jar /Applications/Sikuli/SikuliX.app/Contents/Java/sikulix.jar -r '/Applications/Sikuli/Sikuli_Stuff/test1-about.sikuli/' [EDIT on May 11, 2020] The path to the java JRE can get frustratingly obtuse in OSX. I recently was beset by "Unsupported major.minor version" errors when using the old java path, so I had to track down the newer runtime environment binary, which is now in /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java So in order to make this work (again), I had to specify the path to this newer JRE. The new command line looks like: /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -jar /Applications/Sikuli/SikuliX.app/Contents/Java/sikulix.jar -r '/Applications/Sikuli/Sikuli_Stuff/test1-about.sikuli/' And one may alias a link to this new RE as described in Mac OSX Java Terminal version incorrect
accepted answer of: http://stackoverflow.com/q/49360938
answers question: http://stackoverflow.com/q/49360938

http://stackoverflow.com/q/49437742
has comment: http://stackoverflow.com/comment/85877567
has body: Pardon my low-tech question, but either I'm going insane, or this simply doesn't exist. I get that you can do 5 * 5 and that will work, basic Python. You can even do operator.mul(5, 5). But why is there no helper function for multiplication over a iterable? I'm surprised to find that mul() isn't a standard built-in, or at the very least being a reference to it in either of the two main docs you end up in searching for mathematical functions. But also that there's no helper function called times(iterable) (or similar) that takes a iterable as an argument, much like sum(). It would for instance be handy when calculating the area size of a image if the image size is given as a tuple/list. https://docs.python.org/3/library/functions.html https://docs.python.org/3/library/math.html How can I multiply all items in a list together with Python? Am I blind or is there a reason for this? Isn't multiplication used that much?
tagged with: built-in
duplicate of: http://stackoverflow.com/q/595374
score: 0
answer count: 0
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85877434
type: Question
has comment: http://stackoverflow.com/comment/85877545
linked to: http://stackoverflow.com/q/13840379
has comment: http://stackoverflow.com/comment/85877467
tagged with: math
has title: multiplication over a iteratable, is there no times(iterable)?
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/595374
has comment: http://stackoverflow.com/comment/85877535
has comment: http://stackoverflow.com/comment/85877749

http://stackoverflow.com/q/49296230
tagged with: operator-overloading
has body: I want to implement in python a simple model for optical propagation. The rule is that if I chain three elements m0 -> m1-> m2 what I would get as system is: tau = tau0 * tau1 * tau2 B = B2 + B1*tau2 + B0*tau2*tau1 (tau is transmission, B is background). I wanted to implement overloading the __gt__ operator such that I can declare: m0 = Mirror(0.9, 10) m1 = Mirror(0.8, 11) m2 = Mirror(0.7, 12) x = m0 &gt; m1 &gt; m2 So far I wrote this: class OpticalElement: def __init__(self, trans, background): self.trans = trans self.background = background class Mirror(OpticalElement): def __gt__(self, other): if isinstance(other, Mirror): tau = self.trans * other.trans bkg = other.background + other.trans * self.background return Mirror(tau, bkg) else: return NotImplemented However this code seems only to get the transmission and background of the rightmost elements: x = m0 &gt; m1 &gt; m2 x.trans Returns 0.56, while I am expecting 0.504. Background behaves the same, I am getting 19.7 instead of 25.3 (first element ignored). Do you guys have any idea on how to implement several chained elements using the operator overloading? (putting parenthesis works, but I wanted to have cleaner code). Thanks! Andreu
has answer: http://stackoverflow.com/a/49296644
possible better answer: http://stackoverflow.com/a/49296579
tagged with: python
has title: Chained operator overloading for path propagation
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85594769
downvote count: 0
has answer: http://stackoverflow.com/a/49296579
score: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49296644

http://stackoverflow.com/a/52214328
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49285112
score: 2
type: Answer
has body: Answer mentioned by kmario23 is correct but there is a tricky case with variables created by tf.get_variable: with tf.variable_scope('myscope'): print(tf.get_variable('var1', shape=[3])) with tf.variable_scope('myscope/'): print(tf.get_variable('var2', shape=[3])) This snippet will output: &lt;tf.Variable 'myscope/var1:0' shape=(3,) dtype=float32_ref&gt; &lt;tf.Variable 'myscope//var2:0' shape=(3,) dtype=float32_ref&gt; It seems that tensorflow has not provided a formal way to handle this circumstance yet. The only possible method I found is to manually assign the correct name (Warning: The correctness is not guaranteed): with tf.variable_scope('myscope'): print(tf.get_variable('var1', shape=[3])) with tf.variable_scope('myscope/') as scope: scope._name = 'myscope' print(tf.get_variable('var2', shape=[3])) And then we can get the correct names: &lt;tf.Variable 'myscope/var1:0' shape=(3,) dtype=float32_ref&gt; &lt;tf.Variable 'myscope/var2:0' shape=(3,) dtype=float32_ref&gt;

http://stackoverflow.com/q/49348923
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has title: Create a New Column in a Pandas DataFrame, and Set all Cells to a Default Array
has body: I'm trying to build a DataFrame where one of the columns represents a vector. This is the part of code I'm having trouble with: tweets = pd.DataFrame(train_tweets) tweets["LangClass"] = "und" tweets["LangVec"] = pd.Series[[0,0,0,0,0,0,0,0,0,0]] train_tweets is an incoming DataFrame with only two columns, and I want to add a third and fourth column, LangClass and LangVec. The values in LangVec will be updated element by element. I had it working by using a for loop to iterate through the DataFrame and setting each value of LangVec to the desired vector, but that seems to be a very slow approach. Thanks for any suggestions!
has comment: http://stackoverflow.com/comment/85699561
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/49348965

http://stackoverflow.com/comment/85633811
score: 0
comment on: http://stackoverflow.com/q/49316102
type: QuestionComment
type: Comment
has text: I believe we need a bit more, for instance, have you parsed the punctuation of your text ?

http://stackoverflow.com/a/49328902
score: 2
answers question: http://stackoverflow.com/q/49327905
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49327905
type: Answer
has body: The there are different possible formats for markevery. None of them uses the actual values to mark. Here, it makes sense to either use the indices of the values to mark, or a boolean array of the same length as the data. The latter would look like this: import numpy as np markers_on = np.isin(df1.index, df2.index) plt.plot(df1["b"], '-gD', markevery=list(markers_on)) plt.show()
upvote count: 2

http://stackoverflow.com/comment/85784564
type: AnswerComment
has text: Updated snippet. Can you try now?
score: 0
comment on: http://stackoverflow.com/a/49389815
type: Comment

http://stackoverflow.com/a/49437049
has body: Your example works correctly if sectionViewportPosition is used: def on_header_sectionClicked(self, index): ... #FIXME: position the menu correctly headerPos = self.view.mapToGlobal(self.header.pos()) posY = headerPos.y() + self.header.height() posX = headerPos.x() + self.header.sectionViewportPosition(self.col_index) menu.exec_(QPoint(posX, posY))
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49431089
type: Answer
answers question: http://stackoverflow.com/q/49431089
downvote count: 0

http://stackoverflow.com/comment/85567845
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49282501
type: Comment
has text: i can't access the shall!

http://stackoverflow.com/comment/85906710
has text: So that takes whatever is listed in ghana_city and looks up the coordinates. This resulting column is the one that I can't lookup the coordinates for
score: 0
comment on: http://stackoverflow.com/a/49436091
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49324388
tagged with: sqlalchemy
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49438579
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85678226
has answer: http://stackoverflow.com/a/49438579
has title: Catch in python cx_Oracle DatabaseError DPI-1004: unable to get error message
tagged with: python
has comment: http://stackoverflow.com/comment/85764314
score: 0
has comment: http://stackoverflow.com/comment/85908144
answer count: 2
has comment: http://stackoverflow.com/comment/85747793
has comment: http://stackoverflow.com/comment/85854189
has body: I use cx_Oracle driver with SQLAlchemy to create engine. Succesfully create enine like: conn_string = 'oracle+cx_oracle://user:pass@host:1521/?service_name=some_service' eng = create_engine(conn_string, encoding='utf8') When I try to connect with: eng.connect() I catch the error: DatabaseError: (cx_Oracle.DatabaseError) DPI-1004: unable to get error message Using: Python 3.5.2 cx-Oracle (6.2.1) SQLAlchemy (1.1.15) Does anybody know solution?
has comment: http://stackoverflow.com/comment/85716318
tagged with: cx-oracle
has comment: http://stackoverflow.com/comment/85822061
accepted answer: http://stackoverflow.com/a/49516977
has answer: http://stackoverflow.com/a/49516977

http://stackoverflow.com/q/49353928
has comment: http://stackoverflow.com/comment/85750163
answer count: 1
downvote count: 0
upvote count: 1
tagged with: elementary-functions
has answer: http://stackoverflow.com/a/49354207
has title: Algorithm for computing base-10 logarithm in Python
favorite count: 0
type: Question
tagged with: algorithm
tagged with: math
accepted answer: http://stackoverflow.com/a/49354207
tagged with: python
has comment: http://stackoverflow.com/comment/85708796
has comment: http://stackoverflow.com/comment/85708635
has body: I have tried to create a program to calculate the base-10 logarithm based on the Taylor series-based algorithm described in "The Mathematical-Function Computation Handbook" (I found an online copy via my University's library). A similar algorithm is given on another question on StackOverflow for which I cannot find the link right now. 10.3.2 Computing logarithms in a decimal base For a decimal base, the base-10 logarithm is the natural choice, and the decomposition of the argument into an exponent and a fraction gives us a decimal representation: x = (−1)^s × f × 10^n, either f = 0 exactly, or f is in [1/10, 1). If f ≤√1/10, set f = 10 × f and n = n − 1, so that f is now in the interval (√1/10,√10]. Then introduce a change of variable, a Taylor-series expansion, and a polynomial representation of that expansion: z = (f − 1)/( f + 1), f = (1 + z)/(1 − z), D = 2 log10(e) = 2/ log(10) log10( f) = D × (z + z3/3 + z5/5 + z7/7 + z9/9 + z11/11 + · · · ) ≈ D × z + z3Q(z2), polynomial fit incorporates D in Q(z2). For f in (√1/10,√10], we have z in roughly [−0.5195,+0.5195]. The wider range of z requires longer polynomials compared to the binary case, and also makes the correction term z3Q(z2) relatively larger. Its magnitude does not exceed |0.35z|, so it provides barely one extra decimal digit of precision, instead of two. Accurate computation of z is easier than in the binary case: just set z = fl(fl(f−12)−12)/fl(f+1). For this I wrote this program in Python: def log10(x): n = 0.0 #Start exponent of base 10 while (x &gt;= 1.0): x = x/10.0 n+=1 # if x &lt;= sqrt(1/10) if(x&lt;=0.316227766016838): x = x*10.0 n = n-1 #Produce a change of variable z = (x-1.0)/(x+1.0) D = 4.60517018598809 #2*log10(e) sum = z for k in range(3,111,2): sum+=(z**k)/k return D*n*sum I compared the results to the math.log10 function, and the results are not as expected. My biggest issue when debugging is understanding the algorithm and why it works.
has comment: http://stackoverflow.com/comment/85723918
linked to: http://stackoverflow.com/q/42107700
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85708385
has comment: http://stackoverflow.com/comment/85708447
score: 1
has comment: http://stackoverflow.com/comment/85708453

http://stackoverflow.com/a/49403928
answers question: http://stackoverflow.com/q/49403645
has comment: http://stackoverflow.com/comment/85809180
score: 0
has body: you have &lt;h1 id='titel'&gt;{{artikel_titel[0]}}&lt;/h1&gt; &lt;img id=plaatje src="{{artikel_image[0]}}"&gt; &lt;div id='tekst'&gt;{{artikel_tekst[0]}}&lt;/div&gt; which should be &lt;h1 id='titel'&gt;{{artikel_titel[0]}}&lt;/h1&gt; &lt;img id='plaatje' src="{{artikel_image[0]}}"&gt; &lt;div id='tekst'&gt;{{artikel_tekst[0]}}&lt;/div&gt; later in your code you have var elem1 = document.getElementById("titel"); var elem2 = document.getElementById("plaatje"); var elem3 = document.getElementById("plaatje"); which should be changed to var elem1 = document.getElementById("titel"); var elem2 = document.getElementById("plaatje"); var elem3 = document.getElementById("text");
type: Answer
has comment: http://stackoverflow.com/comment/85812133
has comment: http://stackoverflow.com/comment/85811983
has comment: http://stackoverflow.com/comment/85812289

http://stackoverflow.com/q/49296167
answer count: 2
upvote count: 1
tagged with: classification
type: UnansweredQuestion
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/49297347
has comment: http://stackoverflow.com/comment/85594402
score: 0
has comment: http://stackoverflow.com/comment/85596288
has body: I've been using NTLK classifiers to train datasets and classify single record. For training the records I use this function, nltk.NaiveBayesClassifier.train(train_set) For classifying a single record, nltk.NaiveBayesClassifier.classify(record) where, "record" is the variable name. In Scikit classifiers, for training dataset, the function used is, from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier() classifier.fit(X_train, y_train) What is the function to classify single record in scikit learn classifiers? i.e., is there something like this classifier.classify() ? Predict method only classifies for whole test set converted into a sparse matrix vector, like y_pred = classifier.predict(X_test) y_pred = classifier.predict(X_test) I couldn't classify for a single record; I get this error : File "C:\Users\HSR\Anaconda2\lib\site-packages\sklearn\utils\validation.py", line 433, in check_array array = np.array(array, dtype=dtype, order=order, copy=copy) ValueError: could not convert string to float: This is a bot If predict can be used to classify a single record, then how to do it?
has answer: http://stackoverflow.com/a/49301013
has title: Is there a classify function for Scikit learn classifiers?
downvote count: 1
tagged with: python
type: Question

http://stackoverflow.com/comment/85679879
type: Comment
type: AnswerComment
has text: Thanks lot!!!!! I tried this one and it works as well. But I decided to use the one from @Jean-FrançoisFabre too keep my code short. Many thanks again!
score: 0
comment on: http://stackoverflow.com/a/49339613

http://stackoverflow.com/q/49351494
favorite count: 0
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/85703579
has answer: http://stackoverflow.com/a/78668885
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/85750140
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85704935
has body: I'm setting up python unit tests in VS Code using unittest, and running into some issues. I am able to run my tests by selecting Run Tests from the status bar, and by right-clicking my test file in Explorer. When I do either of these, I see unit test output (e.g. "test_name ... ok" and "Ran 1 test in 0.002s") in the Python Test Log window, but I get a VS Code notification saying "No tests ran, please check the configuration settings for the tests." I am also not seeing the Run Test | Debug Test code lens in the test file. I have followed the setup instructions in the VS Code docs here: https://code.visualstudio.com/docs/python/unit-testing, but I'm wondering if there are other steps I'll need to follow to get proper integration with the IDE? I am using VS Code version 1.12.1, on Windows.
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/106482208
has title: VS Code Python unittest "No tests ran"
answer count: 2
has comment: http://stackoverflow.com/comment/93289884
downvote count: 0
has answer: http://stackoverflow.com/a/53200732

http://stackoverflow.com/q/49414776
downvote count: 0
score: 1
has body: I set Firewall Rule for my local google compute instance at host '0.0.0.0' and port 7000. And I executed python server.py, it was running on https://0.0.0.0:7000 but when I enter https://external-ip:7000 on my local browser it did not work. So how can I run flask on google compute engine and open in my local computer browser? server.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World’ if __name__ == '__main__': app.run(debug=1,port=7000,host='0.0.0.0')
answer count: 1
tagged with: python
favorite count: 0
type: Question
upvote count: 1
type: UnansweredQuestion
tagged with: google-compute-engine
tagged with: flask
has answer: http://stackoverflow.com/a/49418302
has title: Can't access Flask app running on 0.0.0.0 on GCE

plot
tags question: http://stackoverflow.com/q/49363806
tags question: http://stackoverflow.com/q/49281006
type: Tag
tags question: http://stackoverflow.com/q/49370254
tags question: http://stackoverflow.com/q/49383135
tags question: http://stackoverflow.com/q/49282688
tags question: http://stackoverflow.com/q/49352276
tags question: http://stackoverflow.com/q/49295779
tag name: plot
tags question: http://stackoverflow.com/q/49429160
tags question: http://stackoverflow.com/q/49360258
tags question: http://stackoverflow.com/q/49392606
tags question: http://stackoverflow.com/q/49326496
tags question: http://stackoverflow.com/q/49307738
tags question: http://stackoverflow.com/q/49303263
tags question: http://stackoverflow.com/q/49436120
tags question: http://stackoverflow.com/q/49289179
tags question: http://stackoverflow.com/q/49414358
tags question: http://stackoverflow.com/q/49374685
tags question: http://stackoverflow.com/q/49290456
tags question: http://stackoverflow.com/q/49376514
tags question: http://stackoverflow.com/q/49294705

http://stackoverflow.com/q/49405831
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49407099
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85812498
accepted answer: http://stackoverflow.com/a/49407292
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49407292
answer count: 3
has comment: http://stackoverflow.com/comment/85816536
has comment: http://stackoverflow.com/comment/85814095
downvote count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/1871524
has title: How to write nested dictionaries to a CSV file
tagged with: opencsv
has comment: http://stackoverflow.com/comment/85813033
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49406482
tagged with: python-3.x
has body: i have a dictionary as count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'C': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} } i want to write this dictionary in a CSV format like this ..as you can see in this picture what i want is pic the keys from lt60, ge60le90, gt90 and want to write them in a row. like i pick 'a' and its value from all the nested dictionaries and write its value in that row.
has answer: http://stackoverflow.com/a/49406482

dataframe
tags question: http://stackoverflow.com/q/49407096
tags question: http://stackoverflow.com/q/49410786
tags question: http://stackoverflow.com/q/49360617
tags question: http://stackoverflow.com/q/49429194
tags question: http://stackoverflow.com/q/49439103
tags question: http://stackoverflow.com/q/49353752
tags question: http://stackoverflow.com/q/49290471
tags question: http://stackoverflow.com/q/49403610
tags question: http://stackoverflow.com/q/49323159
tags question: http://stackoverflow.com/q/49394694
tags question: http://stackoverflow.com/q/49335168
tags question: http://stackoverflow.com/q/49319384
tags question: http://stackoverflow.com/q/49368546
tags question: http://stackoverflow.com/q/49348647
tags question: http://stackoverflow.com/q/49329097
tags question: http://stackoverflow.com/q/49392840
tags question: http://stackoverflow.com/q/49412844
tags question: http://stackoverflow.com/q/49340876
tags question: http://stackoverflow.com/q/49341706
tags question: http://stackoverflow.com/q/49373065
tags question: http://stackoverflow.com/q/49361776
tags question: http://stackoverflow.com/q/49392915
tags question: http://stackoverflow.com/q/49354702
tags question: http://stackoverflow.com/q/49312775
tags question: http://stackoverflow.com/q/49323995
tags question: http://stackoverflow.com/q/49391349
tags question: http://stackoverflow.com/q/49367519
tags question: http://stackoverflow.com/q/49384880
tags question: http://stackoverflow.com/q/49432081
tags question: http://stackoverflow.com/q/49291593
tags question: http://stackoverflow.com/q/49315127
tags question: http://stackoverflow.com/q/49349824
tags question: http://stackoverflow.com/q/49292728
tags question: http://stackoverflow.com/q/49433555
tags question: http://stackoverflow.com/q/49337764
tags question: http://stackoverflow.com/q/49348396
tags question: http://stackoverflow.com/q/49301344
tags question: http://stackoverflow.com/q/49309523
tags question: http://stackoverflow.com/q/49422329
tags question: http://stackoverflow.com/q/49376077
tags question: http://stackoverflow.com/q/49419530
tags question: http://stackoverflow.com/q/49425727
tags question: http://stackoverflow.com/q/49328040
tags question: http://stackoverflow.com/q/49409988
tags question: http://stackoverflow.com/q/49351496
tags question: http://stackoverflow.com/q/49372435
tags question: http://stackoverflow.com/q/49379537
tags question: http://stackoverflow.com/q/49357302
tags question: http://stackoverflow.com/q/49287395
tags question: http://stackoverflow.com/q/49319227
tags question: http://stackoverflow.com/q/49307001
tags question: http://stackoverflow.com/q/49434247
tags question: http://stackoverflow.com/q/49342465
tags question: http://stackoverflow.com/q/49420730
tags question: http://stackoverflow.com/q/49375968
tags question: http://stackoverflow.com/q/49393454
tags question: http://stackoverflow.com/q/49343929
tags question: http://stackoverflow.com/q/49352824
tags question: http://stackoverflow.com/q/49392489
tags question: http://stackoverflow.com/q/49433222
tags question: http://stackoverflow.com/q/49288117
tags question: http://stackoverflow.com/q/49427382
tags question: http://stackoverflow.com/q/49411605
tags question: http://stackoverflow.com/q/49329183
tags question: http://stackoverflow.com/q/49331497
tags question: http://stackoverflow.com/q/49350385
tags question: http://stackoverflow.com/q/49438907
tags question: http://stackoverflow.com/q/49353619
tags question: http://stackoverflow.com/q/49419104
tags question: http://stackoverflow.com/q/49300960
tags question: http://stackoverflow.com/q/49356166
tags question: http://stackoverflow.com/q/49285184
tags question: http://stackoverflow.com/q/49326784
tags question: http://stackoverflow.com/q/49283249
tags question: http://stackoverflow.com/q/49412615
tags question: http://stackoverflow.com/q/49318170
tags question: http://stackoverflow.com/q/49419073
tags question: http://stackoverflow.com/q/49394616
tags question: http://stackoverflow.com/q/49395923
tags question: http://stackoverflow.com/q/49312137

http://stackoverflow.com/a/49343602
has body: Mistake #1: .readlines(). File can be arbitrary large and this operation will read it entirely into memory. Since you are iterating it anyway, removing readlines() is absolutely safe: start_urls = [url.strip() for url in open('urls.txt','r')] Mistake #2: using list instead of an iterator. Lists are still stored completely in memory; iterators are used on demand (only one element is stored). If you don't iterate this list several times, it should be safe to change to an iterator: start_urls = (url.strip() for url in open('urls.txt','r'))
type: Answer
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49342937
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49342937

http://stackoverflow.com/comment/107542443
type: Comment
score: 0
type: QuestionComment
has text: Yes -- see https://gist.github.com/ag-castro/88bd803a43ed80f978453d76b4e7b890
comment on: http://stackoverflow.com/q/49366684

http://stackoverflow.com/comment/85704613
has text: If you really want static type checking, you can run Mypy, and annotate whatever can't be inferred (or, if you can't/don't want to change existing code, write typesheds). Up-to-date IDEs will take advantage of this to statically type-check on the fly, and to show more information in their auto-complete and so on. It's still just going to tell you `Dict[str, file]`, but if you need that, you can have it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49352146
score: 2

http://stackoverflow.com/a/49594324
has comment: http://stackoverflow.com/comment/94385732
has body: I searched a lot and could find that you are missing crypto.dll file. Your code is looking for this dll file and it is unable to find it. Please note this wont be installed by pip install crypto as this is python library and the code is looking for a dll file. ctypes.util.find_library searches for dll file from windows environment path variable. Reference : find_library() in ctypes To verify I checked. find_library('l2gpstore') &gt;&gt;'C:\\WINDOWS\\system32\\l2gpstore.dll' find_library('java') &gt;&gt;'C:\\Program Files\\Java\\jdk-9.0.4\\bin\\java.dll' Furthermore you should install OpenSSL with libcrypto module from here OpenSSL OpenSSL installation instructions The master sources are maintained in our git repository, which is accessible over the network and cloned on GitHub, at https://github.com/openssl/openssl. Bugs and pull patches (issues and pull requests) should be file on the GitHub repo. Please familiarize yourself with the license. libcrypto with respect to OpenSSL reference : GitHub libcrypto (with platform specific naming): Provides general cryptographic and X.509 support needed by SSL/TLS but not logically part of it. Once you install binaries and check crypto.dll is available in one of the path strings in your environment variables this issue should be resolved. If not add it into path variable and check. Update: Update since the question has been updated and the issue has recurred. There are architectural changes with OpenSSL 1.1.0 as compared to 1.0.2 September 13, 2018 - OpenSSL 1.1.0 and later are quite different from previous releases. Users should install BOTH the 1.0.2 series (LTS) and the 1.1.1 (LTS) series for maximum application compatibility. Developers need to recompile their software to support 1.1.1. See the official OpenSSL release strategy document for more details. – Prateek yesterday If you open 1.0.2 from Github you can see crypto.h file , the same file is missing in latest version. Also OpenSSL there is change in DLL names , they …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94385767
answers question: http://stackoverflow.com/q/49302516
has comment: http://stackoverflow.com/comment/94528700
score: 5
accepted answer of: http://stackoverflow.com/q/49302516
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/q/49431548
favorite count: 0
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49431974
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49431974
has body: I have created an application using PyQt5 which runs well on both Windows and Linux but for one form. I am trying to figure out why the form displays appropriately on Windows but not on the Linux systems. The first form is a simple login form which I made using Designer. It has a vertical layout and a grid layout for the fields. It looks like this in designer. This looks fine in windows: But in Linux Mint 17.03, the fields are squashed and are an incorrect height: It is similar in Unbutu 14.04: My code to open the form looks similar to this: import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from login import * import csv class Login(QDialog): """User login """ def __init__(self): QDialog.__init__(self) self.ui = Ui_login_form() self.ui.setupUi(self) self.ui.buttonBox.accepted.connect(lambda: self.handle_login(servers=servers)) servers = {} with open('servers.csv', newline='') as csvfile: server_reader = csv.reader(csvfile) for row in server_reader: self.ui.cbo_db_name.addItem(row[1]) servers[row[1]] = (row[0],row[2],row[3]) def handle_login(self, servers=''): the_key = self.ui.cbo_db_name.currentText() self.server = servers[the_key][0] if __name__=="__main__": app=QApplication(sys.argv) access = Login() access.exec_() print(access.server) myapp = Test_form() myapp.show() sys.exit(app.exec_()) The code for the form from Qt designer looks like this: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_login_form(object): def setupUi(self, login_form): login_form.setObjectName("login_form") login_form.resize(223, 129) self.layoutWidget = QtWidgets.QWidget(login_form) self.layoutWidget.setGeometry(QtCore.QRect(10, 10, 198, 105)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout.setObjectName("verticalLayout") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setObjectName("gridLayout") self.label = QtWidgets.QLabel(self.layoutWidget) self.l…
answer count: 1
tagged with: qt
type: Question
tagged with: pyqt
type: AnsweredQuestion
has title: Form differences in QT between Windows and Linux
has comment: http://stackoverflow.com/comment/85867900
tagged with: pyqt5

http://stackoverflow.com/a/49311411
has comment: http://stackoverflow.com/comment/85624873
score: 3
has body: For each extension you want to add you have to call chrome_options.add_extension like this: chrome_options.add_extension('Path/to/extension/one') chrome_options.add_extension('Path/to/extension/two')
has comment: http://stackoverflow.com/comment/85625266
has comment: http://stackoverflow.com/comment/85625275
type: Answer
answers question: http://stackoverflow.com/q/49311344
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49311344

http://stackoverflow.com/a/49378728
score: 0
has comment: http://stackoverflow.com/comment/85771803
has body: We can do authentication as below article SHAREPOINT ONLINE REMOTE AUTHENTICATION (AND DOC UPLOAD) And we can do operation via REST API. SharePoint REST API
answers question: http://stackoverflow.com/q/49370281
type: Answer

http://stackoverflow.com/a/57091668
answers question: http://stackoverflow.com/q/49404993
has comment: http://stackoverflow.com/comment/120295942
has body: I have an implementation for multiple inputs for TimeseriesGenerator that I have adapted it (I have not been able to test it unfortunately) to meet this example with ImageDataGenerator. My approach was to build a wrapper class for the multiple generators from keras.utils.Sequence and then implement the base methods of it: __len__ and __getitem__: from keras.preprocessing.image import ImageDataGenerator from keras.utils import Sequence class MultipleInputGenerator(Sequence): """Wrapper of 2 ImageDataGenerator""" def __init__(self, X1, X2, Y, batch_size): # Keras generator self.generator = ImageDataGenerator(rotation_range=15, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # Real time multiple input data augmentation self.genX1 = self.generator.flow(X1, Y, batch_size=batch_size) self.genX2 = self.generator.flow(X2, Y, batch_size=batch_size) def __len__(self): """It is mandatory to implement it on Keras Sequence""" return self.genX1.__len__() def __getitem__(self, index): """Getting items from the 2 generators and packing them""" X1_batch, Y_batch = self.genX1.__getitem__(index) X2_batch, Y_batch = self.genX2.__getitem__(index) X_batch = [X1_batch, X2_batch] return X_batch, Y_batch You can use this generator with model.fit_generator() once the generator has been instanced.
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/120289312
has comment: http://stackoverflow.com/comment/113733575
has comment: http://stackoverflow.com/comment/113738764
downvote count: 0
has comment: http://stackoverflow.com/comment/120267567

http://stackoverflow.com/comment/85873749
type: QuestionComment
score: 0
has text: @psak, Many things: *at a minimum* sample data and desired output. If possible, your existing attempt at a solution, where you got stuck, and briefly what else you've tried.
comment on: http://stackoverflow.com/q/49435865
type: Comment

http://stackoverflow.com/a/49363735
answers question: http://stackoverflow.com/q/49352660
score: 2
has body: You can get a bit more detail about the inputs to the spiceypy functions by searching for the relevant function here. In your particular case TIPM will be a 3x3 2D matrix that provides the transformation between an object in the inertial frame and a body fixed frame. The required inputs to the mxvg function are given here. In your case POSTN should be a list (or numpy array) of 3 values giving the x, y, and z positions of the body you're interested in. BODPOS will be the output of mxvg, which will be the matrix TIPM multiplied by the vector POSTN, so will be a vector containing three values: the transformed x, y, and z positions of the body. I'm not entirely sure what you require, but an example might be: from astropy.time import Time from spiceypy import spiceypy as spice # create a time t = Time('2010-03-19 11:09:00', format='iso') # put in spice format - this may require a leap seconds kernel to be # downloaded, e.g. download https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0012.tls # and then load it with spice.furnsh('naif0012.tls') et = spice.str2et(t.iso) # get the transformation matrix - this may require a kernel to be # downloaded, e.g. download https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00010.tpc # and then load it with spice.furnsh('pck00010.tpc') target = 399 # Earth TIPM = spice.tipbod( "J2000", target, et ) # get the position that you want to convert from astropy.coordinates import Angle, ICRS ra = Angle('12:32:12.23', unit='hourangle') dec= Angle('-01:23:52.21', unit='deg') # make an ICRS object (you can also input a proper motion as a radial velocity or using 'pm_dec' and 'pm_ra_cosdec' keyword arguments) sc = ICRS(ra=ra, dec=dec) # get position in xyz xyz = sc.cartesian.xyz.value # perform conversion to body centred frame newpos = spice.mxvg(TIPM, xyz, 3, 3) # convert to latitude and longitude scnew = SkyCoord(x=newpos[0], y=newpos[1], z=newpos[2], representation_type='cartesian') # print out new RA and dec print(scnew.spher…
upvote count: 2
has comment: http://stackoverflow.com/comment/85745740
accepted answer of: http://stackoverflow.com/q/49352660
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85748451
type: Answer
has comment: http://stackoverflow.com/comment/85794321
has comment: http://stackoverflow.com/comment/85748196

scipy
tags question: http://stackoverflow.com/q/49437126
tags question: http://stackoverflow.com/q/49314132
tags question: http://stackoverflow.com/q/49396180
tags question: http://stackoverflow.com/q/49306476
tags question: http://stackoverflow.com/q/49290276
tags question: http://stackoverflow.com/q/49419823
tags question: http://stackoverflow.com/q/49391065
tags question: http://stackoverflow.com/q/49282238
tags question: http://stackoverflow.com/q/49322932
tags question: http://stackoverflow.com/q/49330707
tags question: http://stackoverflow.com/q/49365009
tags question: http://stackoverflow.com/q/49392387
tags question: http://stackoverflow.com/q/49308372
tags question: http://stackoverflow.com/q/49330412
tags question: http://stackoverflow.com/q/49318439
tags question: http://stackoverflow.com/q/49339079
tags question: http://stackoverflow.com/q/49409556
tags question: http://stackoverflow.com/q/49410333
tags question: http://stackoverflow.com/q/49373211
tags question: http://stackoverflow.com/q/49325820
tags question: http://stackoverflow.com/q/49439510
tags question: http://stackoverflow.com/q/49371792
tags question: http://stackoverflow.com/q/49339754
tags question: http://stackoverflow.com/q/49294725
type: Tag
tags question: http://stackoverflow.com/q/49333043
tags question: http://stackoverflow.com/q/49367436
tags question: http://stackoverflow.com/q/49353289
tags question: http://stackoverflow.com/q/49338166
tags question: http://stackoverflow.com/q/49372619
tag name: scipy
tags question: http://stackoverflow.com/q/49359762
tags question: http://stackoverflow.com/q/49437887
tags question: http://stackoverflow.com/q/49390940
tags question: http://stackoverflow.com/q/49392370
tags question: http://stackoverflow.com/q/49332590
tags question: http://stackoverflow.com/q/49374829
tags question: http://stackoverflow.com/q/49361288
tags question: http://stackoverflow.com/q/49286903
tags question: http://stackoverflow.com/q/49408242
tags question: http://stackoverflow.com/q/49406282
tags question: http://stackoverflow.com/q/49293019
tags question: http://stackoverflow.com/q/49280404
tags question: http://stackoverflow.com/q/49324767
tags question: http://stackoverflow.com/q/49319841
tags question: http://stackoverflow.com/q/49394188
tags question: http://stackoverflow.com/q/49318113
tags question: http://stackoverflow.com/q/49418679
tags question: http://stackoverflow.com/q/49368274
tags question: http://stackoverflow.com/q/49369299

http://stackoverflow.com/comment/85794194
type: QuestionComment
has text: There are also Python libraries that can read Excel files directly. Pandas might be a good fit https://stackoverflow.com/questions/3239207/how-can-i-open-an-excel-file-in-python
score: 0
comment on: http://stackoverflow.com/q/49395981
type: Comment

http://stackoverflow.com/q/49346946
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85693616
tagged with: python
has answer: http://stackoverflow.com/a/49346967
has answer: http://stackoverflow.com/a/49346966
upvote count: 3
score: 0
downvote count: 3
has body: I am doing a course in regression and I have to edit a certain jupyter notebook file as an assignment. However, at the end of each cell, they have put 'raise NotImplementedError()'. If I remove it, everything seems to work according to instruction. But if I leave it, naturally, I get an error. I'm not sure why they have done that. For example, this is the column where I have to separate my data: bank_features = None # explanatory features - 16 total bank_output = None # output feature # YOUR CODE HERE raise NotImplementedError() If I separate it without the error line, it works. But the error like breaks it. What should I do, should I just remove it? It's at the end of EVERY cell.
has title: I don't understand why raise NotImplementedError() is necessary here. (python)
favorite count: 0

http://stackoverflow.com/q/49401476
type: Question
has title: Python Object, Dict, Json, List Ask
answer count: 2
upvote count: 0
duplicate of: http://stackoverflow.com/q/25148611
downvote count: 1
favorite count: 0
tagged with: object
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49401532
has body: Hi, I am new in here. I just cannot find any way to solve this. I want to handle some data. r = {'status': 'ok', 'name': 'Market Price (USD)', 'unit': 'USD', 'period': 'day', 'description': 'Average USD market price across major bitcoin exchanges.', 'values': [{'x': 1521158400, 'y': 8530.402}, {'x': 1521244800, 'y': 7993.674643641666}, {'x': 1521331200, 'y': 8171.415}, {'x': 1521417600, 'y': 8412.033333333333}, {'x': 1521504000, 'y': 8986.948333333334}]} and just want to get the 'x'and 'y' in 'values' section. r['values'] [{'x': 1521158400, 'y': 8530.402}, {'x': 1521244800, 'y': 7993.674643641666}, {'x': 1521331200, 'y': 8171.415}, {'x': 1521417600, 'y': 8412.033333333333}, {'x': 1521504000, 'y': 8986.948333333334}] how can i get all the 'x' value from this Dictionary? Must i do index all the funtion like this? r['values'][0]['x'] 1521158400 Is there anyone who can help me? :)
has answer: http://stackoverflow.com/a/49401532
possible better answer: http://stackoverflow.com/a/49401545
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49401545
linked to: http://stackoverflow.com/q/25148611
score: -1

http://stackoverflow.com/a/49336476
upvote count: 2
has comment: http://stackoverflow.com/comment/85676748
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85676446
has comment: http://stackoverflow.com/comment/85676472
answers question: http://stackoverflow.com/q/49336389
has comment: http://stackoverflow.com/comment/85677053
has comment: http://stackoverflow.com/comment/85676615
type: Answer
has comment: http://stackoverflow.com/comment/85676712
accepted answer of: http://stackoverflow.com/q/49336389
score: 2
has body: DetailView inherits from BaseDetailView which inherits from SingleObjectMixin where get_context_data is called

recursion
type: Tag
tags question: http://stackoverflow.com/q/49292216
tags question: http://stackoverflow.com/q/49391076
tags question: http://stackoverflow.com/q/49419049
tags question: http://stackoverflow.com/q/49292756
tags question: http://stackoverflow.com/q/49394478
tags question: http://stackoverflow.com/q/49406653
tag name: recursion
tags question: http://stackoverflow.com/q/49342077
tags question: http://stackoverflow.com/q/49417719
tags question: http://stackoverflow.com/q/49417987
tags question: http://stackoverflow.com/q/49315155
tags question: http://stackoverflow.com/q/49409446
tags question: http://stackoverflow.com/q/49414271
tags question: http://stackoverflow.com/q/49314703
tags question: http://stackoverflow.com/q/49352062
tags question: http://stackoverflow.com/q/49425956
tags question: http://stackoverflow.com/q/49391890
tags question: http://stackoverflow.com/q/49399658
tags question: http://stackoverflow.com/q/49363006

http://stackoverflow.com/q/49292217
answer count: 2
has comment: http://stackoverflow.com/comment/85587006
tagged with: django
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49292553
type: Question
tagged with: windows
tagged with: http://stackoverflow.com/tag/html
has body: This is the views.py file: from django.shortcuts import render from django.views.generic import TemplateView from .models import Report import random class HomePageView(TemplateView): def get(self, request, **kwargs): args = {} data = Report.objects.all() args['data'] = data return render(request, 'index.html',args) I'm finding it difficult to understand the framework since I'm a beginner. So please help me.
has answer: http://stackoverflow.com/a/49292340
has title: How to retrieve data from an existing db file and display it on webpage using Django?
score: 0

http://stackoverflow.com/comment/85768811
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167175/discussion-between-swathis-and-david-dale).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49383384
type: Comment

http://stackoverflow.com/a/49319091
has comment: http://stackoverflow.com/comment/85648176
score: 1
type: Answer
has body: Here is one solution via collections.defaultdict and pandas library, given a list lst: import pandas as pd from collections import defaultdict d = defaultdict(lambda: defaultdict(int)) for i in lst: for j in i[1:]: d[i[0]][j[0]] += 1 df = pd.DataFrame(index=sorted(d.keys()), columns=sorted(set.union(*map(set, d.values())))) for k, v in d.items(): for w in v: df.loc[k, w] = d[k][w] df = df.fillna(0).rename_axis('Name').reset_index() You can then easily send this to Excel: df.to_excel('file.xlsx', index=False) Result: Name MainCategory1 MainCategory2 MainCategory3 MainCategory4 \ 0 Name1 1 0 0 0 1 Name2 0 3 1 1 2 Name3 0 0 1 0 MainCategory5 MainCategory6 0 0 0 1 3 0 2 0 1
answers question: http://stackoverflow.com/q/49318684
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49318684

http://stackoverflow.com/comment/85806689
type: Comment
type: QuestionComment
has text: i set as environment variable . by that it gives me keyerror="environment path"
score: 0
comment on: http://stackoverflow.com/q/49399612

http://stackoverflow.com/q/49423600
has answer: http://stackoverflow.com/a/49462735
has title: How to send message notifications when a state is changed in odoo 10?
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49484304
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49484304
tagged with: odoo-view
answer count: 3
upvote count: 0
has body: In the vendor bills, when a customer invoice has been created,there will be a message_ids field which creates and sends messages to the concerned persons who are all listed in the followers list. By default,this works like when an invoice is created and a message is entered, after that while clicking on the send button, a notification message will be sent to that followers inbox which will be located in discuss module. Without clicking the new message and sending the message, i want to send a notification to the followers that the state has been changed when i change the state
tagged with: odoo-10
tagged with: odoo
tagged with: python
score: -1
type: Question
possible better answer: http://stackoverflow.com/a/49462351
has answer: http://stackoverflow.com/a/49462351

http://stackoverflow.com/a/49346947
accepted answer of: http://stackoverflow.com/q/49346604
answers question: http://stackoverflow.com/q/49346604
has body: You can vectorize this with obnoxious cumulative products and zipping together of other vectors. But it won't end up saving you time. As a matter of fact, it will likely be numerically unstable. Instead, you can use numba to speed up your loop. from numba import njit import numpy as np import pandas as pd @njit def dynamic_alpha(a, b): c = a.copy() for i in range(1, len(a)): c[i] = a[i] + b[i] * c[i - 1] return c df.assign(C=dynamic_alpha(df.A.values, df.B.values)) A B C 0 2 1 2 1 3 1 5 2 -8 4 12 3 -2 2 22 4 1 1 23 For this simple calculation, this will be about as fast as a simple df.assign(C=np.arange(len(df)) ** 2 + 2) df = pd.concat([df] * 10000) %timeit df.assign(C=dynamic_alpha(df.A.values, df.B.values)) %timeit df.assign(C=np.arange(len(df)) ** 2 + 2) 337 µs ± 5.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 333 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/49348469
type: AnsweredQuestion
has title: How to change this for loop into while loop?
tagged with: while-loop
tagged with: if-statement
has body: I have this code that when u pass in aList = [5,8,2,13,1,8,3,1,8] it prints countList= [0, 2, 1, 1, 0, 1, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]. Basically, say index 1 in countList is 2 because there are two number 1's in aList. This is the code in for loop: countList = 20*[0] aList = [5,8,2,13,1,8,3,1,8] for num in aList: countList[num] += 1 And I tried changing it to a while loop but prints countList= [0, 2, 2, 3, 0, 5, 0, 0, 24, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0] instead. This is what I tried: countList = 20*[0] aList = [5,8,2,13,1,8,3,1,8] index=0#initialize index while index&lt;len(aList): number=aList[index] count=0 while count&lt;number: countList[number] += 1 count+=1 index+=1
has comment: http://stackoverflow.com/comment/85696661
downvote count: 1
score: -1
tagged with: loops
has comment: http://stackoverflow.com/comment/85696653
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85697063
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49348526
accepted answer: http://stackoverflow.com/a/49348526
favorite count: 0

http://stackoverflow.com/q/49316810
tagged with: rest
tagged with: python
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/85636035
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49318098
has answer: http://stackoverflow.com/a/49318098
has body: Hi I am new to exposing Ml models as flask API. Below is my code: import numpy as np from nltk.corpus import wordnet from nltk.stem.wordnet import WordNetLemmatizer import re from sklearn.externals import joblib import warnings warnings.filterwarnings('ignore') from flask import Flask, jsonify, request app = Flask(__name__) @app.route("/glcoding", methods=['POST']) def mylemmatize(token): lmtzr = WordNetLemmatizer() lemmas = {} lemma = None if not token in lemmas: lemma = wordnet.morphy(token) if not lemma: lemma = token if lemma == token: lemma = lmtzr.lemmatize(token) lemmas[token] = lemma return lemmas[token] def cleanmytext(text): words = map(mylemmatize,text.lower().split()) return ' '.join(words) def glcoding(): if request.method == 'POST': json_data = request.get_json() data = pd.read_json(json_data, orient='index') data['Invoice line item description'] = data['Invoice line item description'].apply(cleanmytext) return jsonify(data) if __name__ == '__main__': app.run() With the below code I am calling the API: from flask import Flask, jsonify, request import requests, json BASE_URL = "http://127.0.0.1:5000" data = '{"0":{"Vendor Number": "166587","Invoice line item description":"Petrol charges with electricity"}}' response = requests.post("{}/glcoding".format(BASE_URL), json = data) response.json() I am getting a error as mentioned below: Traceback (most recent call last): TypeError: mylemmatize() takes exactly 1 argument (0 given) 127.0.0.1 - - [16/Mar/2018 14:31:51] "POST /glcoding HTTP/1.1" 500 - The above code is working fine when I am not exposing it as an API. But it is throwing up an error only when called from an API. Please help
upvote count: 1
has comment: http://stackoverflow.com/comment/85635114
accepted answer: http://stackoverflow.com/a/49318165
tagged with: flask
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49318165
has title: Error: While calling Flask API (Json Decodeerror)
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85805851
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49401581
has text: @BoarGules it is about element 0 of the list, sorry for the typo
score: 0

http://stackoverflow.com/q/49331686
has answer: http://stackoverflow.com/a/49331788
type: Question
tagged with: tkinter
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/49333052
tagged with: logic
type: AnsweredQuestion
has title: Combination of logic statements in python (and, or)
has answer: http://stackoverflow.com/a/49333052
has body: I am in the process of making a rock, paper, scissors shoot game in tkinter currently, and am trying to write a function that determines who wins. 1 = rock, 2 = paper, 3 = scissors. The script is not printing anything except when comp == 2 and choice == 1. def Winning(): if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or ((comp == 1) and (choice == 3))): messagebox.showinfo("Info", "YOU LOSE!!!") if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2)) or ((choice == 1) and (comp == 3))): messagebox.showinfo("Info", "YOU WIN!!!") else: messagebox.showinfo("Info", "DRAW!!!")
score: 1
accepted answer: http://stackoverflow.com/a/49331788

http://stackoverflow.com/a/51888807
downvote count: 0
answers question: http://stackoverflow.com/q/49392972
has body: Had the same issue. To solve the problem you can simply change in validation_generator and train_generator the class mode from 'binary' to 'categorical' - that's because you have 3 classes-which is not binary.
type: Answer
score: 12
upvote count: 12

http://stackoverflow.com/comment/85595265
has text: Probably the right shift operator, `>>` ([`__rshift__`](https://docs.python.org/3/reference/datamodel.html#object.__rshift__)), would be the closest to the intended syntax: `x = m0 >> m1 >> m2`.
type: Comment
comment on: http://stackoverflow.com/a/49296644
type: AnswerComment
score: 0

bidi
tag name: bidi
tags question: http://stackoverflow.com/q/49384111
type: Tag

http://stackoverflow.com/q/49369171
has answer: http://stackoverflow.com/a/49370065
has body: I am currently in the process of doing some research using sentiment analysis on twitter data regarding a certain topic (isn't necessarily important to this question) using python, of which I am a beginner at. I understand the twitter streaming API limits users to access only to the previous 7 days unless you apply for a full enterprise search which opens up the whole archive. I had recently been given access to the full archive for this research project from twitter but I am unable to specify a start and end date to the tweets I would like to stream into a csv file. This is my code: import pandas as pd from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener ckey = 'xxxxxxxxxxxxxxxxxxxxxxx' csecret = 'xxxxxxxxxxxxxxxxxxxxxxx' atoken = 'xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxx' asecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx' # ============================================================================= # def sentimentAnalysis(text): # output = '0' # return output # ============================================================================= class listener(StreamListener): def on_data(self, data): tweet = data.split(',"text":"')[1].split('","source')[0] saveMe = tweet+'::'+'\n' output = open('output.csv','a') output.write(saveMe) output.close() return True def on_error(self, status): print(status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["#weather"], languages = ["en"]) Now this code streams twitter date from the past 7 days perfectly. I tried changing the bottom line to twitterStream.filter(track=["#weather"], languages = ["en"], since = ["2016-06-01"]) but this returns this error :: filter() got an unexpected keyword argument 'since'. What would be the correct way to filter by a given date frame?
score: 1
tagged with: twitter
tagged with: tweepy
tagged with: mining
favorite count: 0
type: Question
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: twitter-streaming-api
accepted answer: http://stackoverflow.com/a/49370065
has title: How to stream tweets using tweepy from a start date to end date using python?
type: AnsweredQuestion

http://stackoverflow.com/comment/85795062
type: QuestionComment
has text: You need to clearly define what "intersection" means in your case. For my previous answer (now removed) you were getting 0 for IOU because it is very unlikely that there is a position in any 2D slice which has the same label across all 3D slices. Are you saying that there are multiple objects across 3D that you want to collapse into one slice, and find the intersection between those multiple objects?
comment on: http://stackoverflow.com/q/49396180
score: 1
type: Comment

http://stackoverflow.com/comment/86094220
comment on: http://stackoverflow.com/a/49305478
score: 0
type: AnswerComment
has text: Thanks. I should be careful while reading the docs next time. :)
type: Comment

http://stackoverflow.com/comment/85845353
comment on: http://stackoverflow.com/a/49411105
type: AnswerComment
score: 0
type: Comment
has text: Thanks Hannu! I hadn't actually thought of this - i modified the code as you suggested and also added print statement to the start of the while-loop and it the loop seems to restart fine but no data is received from server end. The mechanics here is following: 1. when connecting to server it prompts you with some text in encrypted format 2. cleanmsg-function cleans the coming input to leave only encrypted part of the message 3. decryptmsg decrypts that output 4. then you are supposed to send it back to server, if the encryption is broken correct the server sends another message as a rep

http://stackoverflow.com/comment/85822631
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49410526
has text: _Only_ for the sample data though... may not scale if not all groups have the same number of IDs.

http://stackoverflow.com/q/49328037
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49328354
upvote count: 1
has answer: http://stackoverflow.com/a/49328312
downvote count: 1
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/zip
has body: I'd like to create a new zip file using python. I'd like to zip files from different directories and put it in one zip file with custom folder structure. My source will come from /mydir/sample1.txt /mydir/data/sample1_data.txt The desired zip structure looks like this sample1.txt /Data/sample1_data.txt Please let me know if you have a solution.
accepted answer: http://stackoverflow.com/a/49328312
tagged with: python
has comment: http://stackoverflow.com/comment/85658061
has answer: http://stackoverflow.com/a/49328354
has title: custom structure of zipfile of python
type: AnsweredQuestion

http://stackoverflow.com/a/49384063
has comment: http://stackoverflow.com/comment/85771180
has body: ok based on your comments I see String slicing will do the work for you. Read more about it here Try this - print "us-east1-b"[:-2]
score: 0
answers question: http://stackoverflow.com/q/49383797
type: Answer
has comment: http://stackoverflow.com/comment/85769144

http://stackoverflow.com/comment/85812337
comment on: http://stackoverflow.com/a/49405283
type: Comment
type: AnswerComment
has text: @steves `cur.execute` is calling (1 time) to each iteration of `i` loop... `extract_dbs_tbls` get new `cur` on each iteration of `i`, just like in your function...
score: 1

http://stackoverflow.com/comment/85787339
type: Comment
type: QuestionComment
has text: try not to iterate over a dataframe. the "best" method would depend on exactly what you want to do, so it'd be helpful if you could provide an example of a specific calculation you want to do
comment on: http://stackoverflow.com/q/49392840
score: 0

http://stackoverflow.com/q/49410786
has answer: http://stackoverflow.com/a/49410924
has answer: http://stackoverflow.com/a/49410931
possible better answer: http://stackoverflow.com/a/49410931
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/49306324
has comment: http://stackoverflow.com/comment/85823314
tagged with: string
has title: Is there a way in pandas to filter rows in a column that are contained in a string
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/49410924
has body: There is a way to check if the string in the column contains another string: df["column"].str.contains("mystring") But I'm looking for the opposite, the column string to be contained in another string, without doing an apply function which I guess is slower than the vectorised .contains: df["column"].apply(lambda x: x in "mystring", axis=1) Update with data: mystring = "abc" df = pd.DataFrame({"A": ["ab", "az"]}) df A 0 ab 1 az I would like to show only "ab" because it is contained in mystring.
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85823258
type: AnsweredQuestion

http://stackoverflow.com/a/49394082
type: Answer
has comment: http://stackoverflow.com/comment/85790768
has body: Ajax1234 solution works but is discarding the result of scramble 50% of the time. It also creates an unnecessary list to choose in. That's a waste of CPU power. Just do: for _ in range(20): print('hi' if random.randint(0,1) else scramble('me too thanks')) It's a ternary expression to print one or the other string. The cool thing is that if random.randint(0,1) returns 1, scramble isn't executed at all If you have more cases, you could pick a function at random, so you're only executing the one you need, using lambda for instance: for _ in range(20): reply = [lambda : 'hi',lambda:scramble('me too thanks'),lambda:'hello'] print(random.choice(reply)()) # note the calling of the chosen function with ()
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85791099
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49393974
answers question: http://stackoverflow.com/q/49393974
downvote count: 0

http://stackoverflow.com/a/49415905
type: Answer
answers question: http://stackoverflow.com/q/49408644
score: 1
downvote count: 0
upvote count: 1
has body: Reducing your code to: import argparse class Ci: def build(self,args): print("clonning repository " + args) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-b','-build',action='store_true', help='execute mvn clean install') parser.add_argument('-c','-compress',action='store_true',help='zip a directory recursively') parser.add_argument('-i','-integration',action='store_true',help='execute mvn verify') parser.add_argument('-r','-release',action='store_true',help='execute build,integration and compress respectively') args = parser.parse_args() print(args) if args.b: a = Ci() a.build() I get: 1313:~/mypy$ python3 stack49408644.py -b Namespace(b=True, c=False, i=False, r=False) Traceback (most recent call last): File "stack49408644.py", line 22, in &lt;module&gt; a.build() TypeError: build() missing 1 required positional argument: 'args' The parser runs fine, seeing args.b to True. But the call to build is wrong. It does not match the method's definition. Providing a 'directory' doesn't help either, because -b is True/False 1313:~/mypy$ python3 stack49408644.py -b foo usage: stack49408644.py [-h] [-b] [-c] [-i] [-r] stack49408644.py: error: unrecognized arguments: foo You need to either change -b to take an value, or add another argument that takes a value. @AntiMatterDynamite showed how to change -b. Instead let's add: parser.add_argument('adir', help='a directory for build') and change the build call a.build(args.adir) Now the value is passed on to the method: 1322:~/mypy$ python3 stack49408644.py -b usage: stack49408644.py [-h] [-b] [-c] [-i] [-r] adir stack49408644.py: error: the following arguments are required: adir 1322:~/mypy$ python3 stack49408644.py -b foo Namespace(adir='foo', b=True, c=False, i=False, r=False) clonning repository foo Instead redefining -b: parser.add_argument('-b','-build', help='execute mvn clean install') if args.b is not None: a = Ci() a.build(args.b) test runs: 1322:~/mypy$ python3 stack49408644.py -b us…

http://stackoverflow.com/q/49305174
answer count: 1
has comment: http://stackoverflow.com/comment/85612712
tagged with: loops
favorite count: 0
type: Question
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/85613330
has comment: http://stackoverflow.com/comment/85613122
tagged with: matrix
score: -3
has answer: http://stackoverflow.com/a/49305654
tagged with: python
accepted answer: http://stackoverflow.com/a/49305654
has title: fast way to stack vectors into a matrix in Python
tagged with: numpy
upvote count: 0
has body: I want to stack 100k vector of the same lentgh (500) into a single matrix in python but it takes too much time. here is my code: stacked = all_vectors[0] for i in range(1,100000): stacked = np.column_stack((stacked ,all_vectors[i])) Do you know how to make this quicker?
tagged with: vector

http://stackoverflow.com/q/49295779
has comment: http://stackoverflow.com/comment/85604143
score: 0
has title: Capturing variance when smoothing trend - can I vary the thickness of a line?
tagged with: matplotlib
tagged with: smoothing
linked to: http://stackoverflow.com/q/19390895
type: Question
has comment: http://stackoverflow.com/comment/85595156
tagged with: trend
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/19390895
has body: Here's an example of a trend I have tried smoothing using exponential smoothing: import numpy as np import matplotlib.pyplot as plt y1 = np.random.randn(100) y2 = np.random.randn(100)+2 y3 = 2*np.random.randn(100)+2 y4 = np.random.randn(100) y = np.append(np.append(np.append(y1,y2),y3),y4) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(y) def exp_smoothing(y, alpha): s=np.zeros(len(y)) s[0] = y[0] for i in range(1,len(y)): s[i] = alpha*y[i]+(1-alpha)*s[i-1] return np.array(s) ax.plot(exp_smoothing(y,.05), c='r') plt.show() This gives the following output: The red line gives a good idea about the change in mean that's occurring, but not about the change in variance. I would like to vary the line's thickness, so that thicker parts indicate sections of the original trend with high variance, and thinner parts indicate sections of the original trend with low variance. The only way I can think of this is by plotting not one line, but many smaller lines, with the width of each set using set_lw (see documentation). Is there a better way to go about this?
tagged with: python
tagged with: plot

http://stackoverflow.com/q/49307872
type: AnsweredQuestion
has title: Odoo 10 - XMLRPC - Use external XML identifier
tagged with: odoo-10
tagged with: odoo
score: 1
tagged with: python
tagged with: xml-rpc
favorite count: 0
accepted answer: http://stackoverflow.com/a/49318284
type: Question
has answer: http://stackoverflow.com/a/49318284
tagged with: xmlrpclib
answer count: 1
downvote count: 0
upvote count: 1
has body: I am creating a new record via XMLRPC. Specificaly, I want to populate the field team_id in crm.lead. I would like to populate that field using sales_team.salesteam_website_sales (i.e. the external XML ID) instead of the number 2 (i.e. the regular ID). Is that possible using XMLRPC create, if so, what shall I use? Odoo 10 CE

http://stackoverflow.com/comment/85661547
has text: What kind of features do you want to synchronize?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49329640
score: 0

http://stackoverflow.com/q/49331856
has comment: http://stackoverflow.com/comment/85665737
tagged with: python
has comment: http://stackoverflow.com/comment/85665854
has comment: http://stackoverflow.com/comment/85665872
score: 2
has comment: http://stackoverflow.com/comment/85665863
has answer: http://stackoverflow.com/a/49331896
has title: Trouble understanding class methods
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85665827
has body: class Book: def __init__(self,title,author): self.title = title self.author = author def __str__(self): return '{} by {}'.format(self.title,self.author) class Bookcase: def __init__(self,books=None): self.books = books @classmethod def create_bookcase(cls,book_list): books = [] for title,author in book_list: books.append(Book(title,author)) return cls(books) Hi everyone. I'm trying to understand how class methods work like in the following case above. When we return cls(books), does the __init__ method get called to return an instance of the classes books (cls.books instead of self.books) or does returning cls(books) not have anything to do with using the init method and returning self.books?
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/85697805
type: Comment
comment on: http://stackoverflow.com/a/49348945
has text: The string can sometimes have more than just "AWAY FROM KEYBOARD", for example, it can have "AWAY FROM KEYBOARD HELLO". When its like that, we just remove "AWAY FROM KEYBOARD" with "AFK" but we keep "HELLO", so it would be "AFK HELLO". Would it be possible to keep "HELLO" or anything else the user inputs?
score: 0
type: AnswerComment

http://stackoverflow.com/q/49399245
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49399359
has title: Read JSON file as Pyspark Dataframe using PySpark?
answer count: 3
tagged with: apache-spark
possible better answer: http://stackoverflow.com/a/62187176
has answer: http://stackoverflow.com/a/67125849
tagged with: pyspark
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49399359
tagged with: apache-spark-sql
score: 5
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/62187176
has body: How can I read the following JSON structure to spark dataframe using PySpark? My JSON structure {"results":[{"a":1,"b":2,"c":"name"},{"a":2,"b":5,"c":"foo"}]} I have tried with : df = spark.read.json('simple.json'); I want the output a,b,c as columns and values as respective rows. Thanks.

http://stackoverflow.com/a/49308552
downvote count: 0
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49299808
score: 5
has body: The Python client generator produces object-oriented wrappers for the API. You cannot post a dict or a JSON string directly, you need to create a Pet object using the generated wrapper: api_instance = swagger_client.PetApi() pet = swagger_client.Pet(name="doggie", status="available", photo_urls=["http://img.example.com/doggie.png"], category=swagger_client.Category(id=42)) response = api_instance.add_pet(pet)
answers question: http://stackoverflow.com/q/49299808
type: AcceptedAnswer

http://stackoverflow.com/comment/85706640
type: QuestionComment
has text: @bnaecker It has a while loop that keeps on going until a SHA256 hash of a certain format is found.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49352961

http://stackoverflow.com/q/49301709
has body: I'm trying to use the Pafy library in Python, so i just followed the documentation and tried to create new Pafy object: &gt;&gt;&gt; import pafy &gt;&gt;&gt; myvid=pafy.new("https://youtu.be/kXYiU_JCYtU") but i got the message like Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; myvid=pafy.new("https://youtu.be/kXYiU_JCYtU") File "C:\Python\lib\site-packages\pafy\pafy.py", line 125, in new return Pafy(url, basic, gdata, signature, size, callback, ydl_opts) File "C:\Python\lib\site-packages\pafy\backend_youtube_dl.py", line 29, in __init__ super(YtdlPafy, self).__init__(*args, **kwargs) File "C:\Python\lib\site-packages\pafy\backend_shared.py", line 95, in __init__ self._fetch_basic() File "C:\Python\lib\site-packages\pafy\backend_youtube_dl.py", line 53, in _fetch_basic self._category = self._ydl_info['categories'][0] TypeError: 'NoneType' object is not subscriptable Does anyone know how to fix it?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85605217
has title: Python 'NoneType' object is not subscriptable exception
linked to: http://stackoverflow.com/q/9320766
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49302164
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49302164

http://stackoverflow.com/comment/85769130
type: Comment
comment on: http://stackoverflow.com/q/49384132
type: QuestionComment
has text: how does 'Student Data.txt' looks like?
score: 2

http://stackoverflow.com/q/49349787
has comment: http://stackoverflow.com/comment/85699321
tagged with: pymysql
has comment: http://stackoverflow.com/comment/85709000
tagged with: python
has body: When I try to insert the data into mysql,also create a table in the db "db_of_lj",some error occurs but I do not know the reason. Also, I try to print(cursor.description) but the output is "None". I hope you can help me,thanks! import pymysql def create_city_table(city): #create table global cursor cursor.execute("drop table if exists %s" % (city)) create_table="create table %s(id int(10) not null primary key auto_increment," \ "total_price int(10)," \ "unitPrice int(10)," \ "room_desc varchar(20)," \ "construction_year int(10)," \ "area float," \ "location varchar(20));" try: cursor.execute(create_table % (city)) except : print("Failed to create that table!") return None print("Successfully create table of '%s' in sql_db!" % city) #connect to mysql connect=pymysql.Connect( host="127.0.0.1", port=3306, user="root", password="1111", db="db_of_lj" ) #set a cursor cursor = connect.cursor() create_city_table("hangzhou") insert2db = "insert into hangzhou(id,total_price,unitPrice,room_desc,construction_year,area,location)" \ " values(%d,%d,%d,%s,%d,%lf,%s)" try: print(cursor.description) cursor.execute(insert2db % (1,2,3,"room_desc",2016,2.4,"xiasha")) connect.commit() except: connect.rollback() print("Failed to insert into database!") exit(0) print("Insert into the database successfully!") Without try-catch the error return is: Traceback (most recent call last): File "D:/desktop/Computer/Python/web_scrapping/;project3_lianjia/exm.py", line 40, in &lt;module&gt; cursor.execute(insert2db % (1,2,3,"room_desc",2016,2.4,"xiasha")) File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\cursors.py", line 165, in execute result = self._query(query) File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\cursors.py", line 321, in _query conn.query(q) File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 860, in query self._affected_rows = self._read_query_re…
has comment: http://stackoverflow.com/comment/85702238
score: 0
answer count: 0
tagged with: mysql
has title: Failed to insert data into the table of mysql
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/85576959
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49286903
type: Comment
has text: ... and https://stackoverflow.com/questions/30260642/normalizing-matrix-row-scipy-matrix

http://stackoverflow.com/a/49320548
type: Answer
downvote count: 0
upvote count: 1
has body: You can run like this npm start &amp; mongod &amp; node public/app.js &amp; &amp; makes the process run in the background so once the session is closed the server stops But you can use nohup to keep it running
answers question: http://stackoverflow.com/q/49320231
score: 1

http://stackoverflow.com/q/49336474
has comment: http://stackoverflow.com/comment/85679448
has comment: http://stackoverflow.com/comment/85678602
has comment: http://stackoverflow.com/comment/85680394
linked to: http://stackoverflow.com/q/38131062
score: 0
tagged with: seaborn
has title: SNS Bar plot color intensity is wrong
has comment: http://stackoverflow.com/comment/85678515
linked to: http://stackoverflow.com/q/36271302
has comment: http://stackoverflow.com/comment/85678974
answer count: 1
has body: I am plotting following type of Bar Plot using SNS using the following code. I used cubehelix_palette as I want the bar color intensities according to the values. I am expecting the higher values get darker purple and lower values get lighter. But It seems very different what I am getting here. . It seems less negative values are getting darker and more positive value is neglected. Am I doing something wrong here? x = ["A","B","C","D"] y = [-0.086552691,0.498737914,-0.090153413,-0.075941404] sns.axes_style('white') sns.set_style('white') pal=sns.cubehelix_palette(5) ax = sns.barplot(x, y,palette=pal) for n, (label, _y) in enumerate(zip(x, y)): ax.annotate( s='{:.3f}'.format(_y), xy=(n, _y), ha='center',va='center', xytext=(0,10*(1 if _y &gt; 0 else -1)), textcoords='offset points', size = 8, weight='bold' ) ax.annotate( s=label, xy=(n, 0), ha='left',va='center', xytext=(0,50*(-1 if _y &gt; 0 else 1)), textcoords='offset points', rotation=90, size = 10, weight='bold' ) # axes formatting #ax.set_yticks([]) ax.set_xticks([]) sns.despine(ax=ax, bottom=True, left=True) EDITED As per @ImportanceOfBeingErnest suggestion, I tried the following code too. However, the negative directional intensities are wrong. Also disturbing Legend is also visible. import numpy as np, matplotlib.pyplot as plt, seaborn as sns sns.set(style="whitegrid", color_codes=True) pal = sns.color_palette("Greens_d", 5) ax = sns.barplot(x=x, y=y, palette=pal,hue=y,dodge=False) x = ["A","B","C","D","E","F","G","H","I","J","K"] y = [-0.086552691, 0.498737914, -0.090153413, -0.075941404, -0.089105985, -0.05301275, -0.095927691, -0.083528335, 0.250680624, -0.092506638, -0.082689631, ] for n, (label, _y) in enumerate(zip(x, y)): ax.annotate( s='{:.3f}'.format(_y), xy=(n, _y), ha='center',va='center', xytext=(0,10*(1 if _y &gt; 0 else -1)), textcoords='offset points', size = 8, weight='bold' ) ax.annotate( s=label, xy=(n, 0), ha='left',va='center', xytext=(0,50*(-1 if _y &gt; 0 else 1)), textcoords='offset po…
type: Question
duplicate of: http://stackoverflow.com/q/36271302
has answer: http://stackoverflow.com/a/49336555
has comment: http://stackoverflow.com/comment/85678853
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/85864051
type: AnswerComment
has text: @jezrael ..thats exactly what I need...thank you and thank you again..... iam trying to apply it to my data and I get an error saying "raise IndexingError('Unalignable boolean Series key provided') pandas.core.indexing.IndexingError: Unalignable boolean Series key provided"
comment on: http://stackoverflow.com/a/49429592
type: Comment
score: 0

http://stackoverflow.com/a/49351692
has comment: http://stackoverflow.com/comment/85711155
has comment: http://stackoverflow.com/comment/85711413
type: Answer
answers question: http://stackoverflow.com/q/49340877
has comment: http://stackoverflow.com/comment/85717272
has body: Try this: import sqlite3 import nltk from nltk.tokenize import sent_tokenize, word_tokenize conn = sqlite3.connect('ACE.db') c = conn.cursor() c.execute('SELECT can_answer FROM Can_Answer') // rows will have all the records from the can_answer field rows = c.fetchall() for row in rows: print(word_tokenize(row))
score: 0
has comment: http://stackoverflow.com/comment/85718745

http://stackoverflow.com/comment/86582844
has text: If you build against `conda-forge` packages, you should probably use [conda-forge's recipe](https://github.com/conda-forge/opencv-feedstock). Recipes from anaconda should be used with `defaults` channel. But anyway, **why** are you compiling it on your own? It's precisely the point of `conda` to provide precompiled and compatible binaries... just `conda install -c conda-forge opencv` (or `-c defaults` for the Anaconda version of source)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49433383
type: Comment

http://stackoverflow.com/a/49382743
has comment: http://stackoverflow.com/comment/85812280
type: Answer
accepted answer of: http://stackoverflow.com/q/49320993
answers question: http://stackoverflow.com/q/49320993
score: 7
type: AcceptedAnswer
downvote count: 0
has body: I've built the OpenSSL-FIPS module using regular flags (e.g.: no-asm, shared, some ancient ciphers disabled): [cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q049320993]> ~/sopr.sh ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [064bit-prompt]> ls ssl/build/bin ssl/build/lib ssl/build/bin: c_rehash openssl ssl/build/lib: engines libcrypto.a libcrypto.so libcrypto.so.1.0.0 libssl.a libssl.so libssl.so.1.0.0 pkgconfig And started playing a little bit with it: [064bit-prompt]> ssl/build/bin/openssl version OpenSSL 1.0.2h-fips 3 May 2016 (Library: OpenSSL 1.0.2g 1 Mar 2016) Note the "(Library: OpenSSL 1.0.2g 1 Mar 2016)" part. That (being present) states that the openssl executable is OK (expected version), but it's using a wrong libcrypto (it's the one that comes installed by default on the system - under /lib - and typically that one isn't built with FIPS support). It must load our libraries, and that is done by setting LD_LIBRARY_PATH (the same behavior could have also been achieved by setting an env var when building OpenSSL that would have set the rpath in the openssl executable, but I forgot, and I didn't want to build it again): [064bit-prompt]> LD_LIBRARY_PATH=ssl/build/lib ssl/build/bin/openssl version OpenSSL 1.0.2h-fips 3 May 2016 Now, that the setup is successful, let's dive into OPENSSL_FIPS env var: [064bit-prompt]> LD_LIBRARY_PATH=ssl/build/lib ssl/build/bin/openssl md5 ./code00.py MD5(./code00.py)= 47fb26ec5d1ca16d3537fe7fd12ea529 [064bit-prompt]> LD_LIBRARY_PATH=ssl/build/lib ssl/build/bin/openssl sha1 ./code00.py SHA1(./code00.py)= 5188a221ba61309e78e70004285bc6fd148701b6 [064bit-prompt]> OPENSSL_FIPS=1 LD_LIBRARY_PATH=ssl/build/lib ssl/build/bin/openssl sha1 ./code00.py SHA1(./code00.py)= 5188a221ba61309e78e70004285bc6fd148701b6 [064bit-prompt]> OPENSSL_FIPS=1 LD_LIBRARY_PATH=ssl/build/lib ssl/build/bin/openssl md5 ./code00.py Error setting digest md5 139778679649944:error:060A80A3:digital envelope routines:FI…
upvote count: 7
has comment: http://stackoverflow.com/comment/95074533
has comment: http://stackoverflow.com/comment/85822493
has comment: http://stackoverflow.com/comment/85990608

http://stackoverflow.com/q/49374199
tagged with: abstract-syntax-tree
accepted answer: http://stackoverflow.com/a/49378090
has title: How to get ast for every function in Python using ANTLR
has body: I have a Python grammar already. I want to generate a separate AST for every Function defined in Python. Here is my code: public class TestGrammar extends Python3BaseListener { public static void main(String[] args) throws IOException { PlagiarismPercentage obj = new PlagiarismPercentage(); String source = obj .readFile("C:\\Users\\Paridhi\\quickSort.py"); ANTLRInputStream inputCharStream = new ANTLRInputStream(new StringReader(source)); TokenSource lexer = new Python3Lexer(inputCharStream); // Python3Lexer lexer = new Python3Lexer(CharStreams.fromString(source)); Python3Parser parser = new Python3Parser(new CommonTokenStream(lexer)); ParseTreeWalker.DEFAULT.walk(new Python3BaseListener() { AstPrinter astPrinter = new AstPrinter(); @Override public void enterFuncdef(Python3Parser.FuncdefContext ctx) { System.out.printf("NAME=%s\n", ctx.NAME().getText()); // System.out.println(ctx.toString()); TestGrammar grammar = new TestGrammar(); StringBuilder str = grammar.explore(ctx, false, 0, new StringBuilder("")); System.out.println("----------------------------"); System.out.println(str); System.out.println("----------------------------"); } }, parser.single_input()); } private StringBuilder explore(RuleContext ctx, boolean verbose, int indentation, StringBuilder str) { boolean toBeIgnored = !verbose &amp;&amp; ctx.getChildCount() == 1 &amp;&amp; ctx.getChild(0) instanceof ParserRuleContext; if (!toBeIgnored) { String ruleName = Python3Parser.ruleNames[ctx.getRuleIndex()]; for (int i = 0; i &lt; indentation; i++) { System.out.print(" "); } System.out.println(ruleName + " " + ctx.getText()); if (indentation != 0) { str.append(ruleName + " "); } } for (int i = 0; i &lt; ctx.getChildCount(); i++) { ParseTree element = ctx.getChild(i); if (element instanceof RuleContext) { explore((RuleContext) element, verbose, indentation + (toBeIgnored ? 0 : 1), str); } } return str; } } My Python code for quicksort in file quicksort is given below: def quickSort(alist): quickSortHelper(ali…
has answer: http://stackoverflow.com/a/49378090
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: antlr4
tagged with: java
answer count: 1
type: Question

http://stackoverflow.com/a/49332712
has body: If you want to be a bit fancy and save some memory, use generator: def get_responses(*urls, **kwargs): for url in urls: yield requests.get(url, **kwargs) urls = ['http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com'] for response in get_responses(*urls): # do something to the response
type: Answer
has comment: http://stackoverflow.com/comment/85667292
score: 0
answers question: http://stackoverflow.com/q/49332610

http://stackoverflow.com/q/49427944
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/56769160
has answer: http://stackoverflow.com/a/52682313
has title: Type hints for Sized Iterable in Python
tagged with: python
has answer: http://stackoverflow.com/a/64868551
tagged with: python-typing
answer count: 4
score: 85
upvote count: 85
has body: I have a function that uses the len function on one of it's parameters and iterates over the parameter. Now I can choose whether to annotate the type with Iterable or with Sized, but both gives errors in mypy. from typing import Sized, Iterable def foo(some_thing: Iterable): print(len(some_thing)) for part in some_thing: print(part) Gives error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized" While def foo(some_thing: Sized): ... Gives error: Iterable expected error: "Sized" has no attribute "__iter__" Since there is no Intersection as discussed in this issue I need to have some kind of mixed class. from abc import ABCMeta from typing import Sized, Iterable class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta): pass def foo(some_thing: SizedIterable): print(len(some_thing)) for part in some_thing: print(part) foo(['a', 'b', 'c']) This gives an error when using foo with a list. error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable" This is not too surprising since: >>> SizedIterable.__subclasscheck__(list) False So I defined a __subclasshook__ (see docs). class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta): @classmethod def __subclasshook__(cls, subclass): return Sized.__subclasscheck__(subclass) and Iterable.__subclasscheck__(subclass) Then the subclass check works: >>> SizedIterable.__subclasscheck__(list) True But mypy still complains about my list. error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable" How can I use type hints when using both the len function and iterate over my parameter? I think casting foo(cast(SizedIterable, ['a', 'b', 'c'])) is not a good solution.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49434182

http://stackoverflow.com/comment/85751866
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49356261
has text: This is a comment, not an answer.

http://stackoverflow.com/q/49293287
type: Question
has answer: http://stackoverflow.com/a/49293352
tagged with: python-3.x
tagged with: cron
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85588974
tagged with: python
has comment: http://stackoverflow.com/comment/85589867
has comment: http://stackoverflow.com/comment/85589894
tagged with: bash
answer count: 2
score: 1
has title: Running python file from inside a bash script through cron
downvote count: 0
tagged with: shell
upvote count: 1
has body: I have created a bash script which first activates a python virtual environment, and then runs a python file. When I execute the bash script manually, the python file runs as intended. Bash script code: sample.sh #!/usr/bin/env bash source ./project/bin/activate python3 /home/abc/project/server/sample.py However, when I try to run this bash script using cron, the python file does not execute. cron: 16 12 * * * /home/abc/sample.sh &gt; /home/abc/bulkcat.log 2&gt;&amp;1 When this cron triggers at the specified time, the python file inside my bash script does not run and the log file is empty. What seems to be wrong with my code?
has answer: http://stackoverflow.com/a/49296652
favorite count: 0

list
tags question: http://stackoverflow.com/q/49312298
tags question: http://stackoverflow.com/q/49339423
type: Tag
tags question: http://stackoverflow.com/q/49396526
tags question: http://stackoverflow.com/q/49311922
tags question: http://stackoverflow.com/q/49279901
tags question: http://stackoverflow.com/q/49367756
tags question: http://stackoverflow.com/q/49398522
tags question: http://stackoverflow.com/q/49407037
tags question: http://stackoverflow.com/q/49354699
tags question: http://stackoverflow.com/q/49308665
tags question: http://stackoverflow.com/q/49288777
tags question: http://stackoverflow.com/q/49330219
tags question: http://stackoverflow.com/q/49363247
tags question: http://stackoverflow.com/q/49345400
tags question: http://stackoverflow.com/q/49396973
tags question: http://stackoverflow.com/q/49398594
tags question: http://stackoverflow.com/q/49389332
tags question: http://stackoverflow.com/q/49348944
tags question: http://stackoverflow.com/q/49418627
tags question: http://stackoverflow.com/q/49288679
tags question: http://stackoverflow.com/q/49328936
tags question: http://stackoverflow.com/q/49306963
tags question: http://stackoverflow.com/q/49336100
tags question: http://stackoverflow.com/q/49331802
tags question: http://stackoverflow.com/q/49335177
tags question: http://stackoverflow.com/q/49306038
tags question: http://stackoverflow.com/q/49338078
tags question: http://stackoverflow.com/q/49309574
tags question: http://stackoverflow.com/q/49418926
tags question: http://stackoverflow.com/q/49339291
tags question: http://stackoverflow.com/q/49353986
tags question: http://stackoverflow.com/q/49410978
tags question: http://stackoverflow.com/q/49349782
tags question: http://stackoverflow.com/q/49419744
tags question: http://stackoverflow.com/q/49370459
tags question: http://stackoverflow.com/q/49405442
tags question: http://stackoverflow.com/q/49386988
tags question: http://stackoverflow.com/q/49377878
tags question: http://stackoverflow.com/q/49409902
tags question: http://stackoverflow.com/q/49351717
tags question: http://stackoverflow.com/q/49419049
tags question: http://stackoverflow.com/q/49374773
tags question: http://stackoverflow.com/q/49344683
tags question: http://stackoverflow.com/q/49376099
tags question: http://stackoverflow.com/q/49286039
tags question: http://stackoverflow.com/q/49364677
tags question: http://stackoverflow.com/q/49354977
tags question: http://stackoverflow.com/q/49395904
tags question: http://stackoverflow.com/q/49439902
tags question: http://stackoverflow.com/q/49288533
tags question: http://stackoverflow.com/q/49342471
tags question: http://stackoverflow.com/q/49369548
tags question: http://stackoverflow.com/q/49308562
tags question: http://stackoverflow.com/q/49397750
tags question: http://stackoverflow.com/q/49344761
tags question: http://stackoverflow.com/q/49361899
tags question: http://stackoverflow.com/q/49387559
tags question: http://stackoverflow.com/q/49304729
tags question: http://stackoverflow.com/q/49400083
tags question: http://stackoverflow.com/q/49313609
tags question: http://stackoverflow.com/q/49332300
tags question: http://stackoverflow.com/q/49324838
tags question: http://stackoverflow.com/q/49351191
tags question: http://stackoverflow.com/q/49437653
tags question: http://stackoverflow.com/q/49398737
tags question: http://stackoverflow.com/q/49371667
tags question: http://stackoverflow.com/q/49323426
tags question: http://stackoverflow.com/q/49437318
tags question: http://stackoverflow.com/q/49423324
tags question: http://stackoverflow.com/q/49417232
tags question: http://stackoverflow.com/q/49431714
tags question: http://stackoverflow.com/q/49320238
tags question: http://stackoverflow.com/q/49366161
tags question: http://stackoverflow.com/q/49380994
tags question: http://stackoverflow.com/q/49325796
tags question: http://stackoverflow.com/q/49305976
tags question: http://stackoverflow.com/q/49352970
tags question: http://stackoverflow.com/q/49345234
tags question: http://stackoverflow.com/q/49373333

http://stackoverflow.com/a/49304141
downvote count: 0
upvote count: 1
score: 1
has body: Not sure if your last line is correct, fairly sure it should be [(i,j) for i in range(6,9) for j in range(6,9)] not [(i,j) for i in range(6,9) for j in range(3,9)] as this is for a 3x6 grid. Nonetheless this is a cleaner list comp for creating 9 3x3 grids: [[(x0*3 + i, y0*3 + j) for x in range(3) for y in range(3)] for x0 in range(3) for y0 in range(3)]
type: Answer
accepted answer of: http://stackoverflow.com/q/49303178
answers question: http://stackoverflow.com/q/49303178
type: AcceptedAnswer

http://stackoverflow.com/comment/85736275
score: 0
has text: You have to start flask on the RPi. You need to set the host to 0.0.0.0 so other devices on the network can access your webserver using your RPi's IP address : `app.run(host='0.0.0.0')` or `flask run --host=0.0.0.0` depending on how you start flask
comment on: http://stackoverflow.com/q/49367052
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85665662
comment on: http://stackoverflow.com/a/49331535
type: Comment
has text: @SirJohnson I updated with an example code you can use.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85873907
type: QuestionComment
comment on: http://stackoverflow.com/q/49435968
score: 0
has text: `'Apple' in mainDict`...`mainDict['Apple']={}`......`mainDict['Apple']['American']=33`
type: Comment

http://stackoverflow.com/a/49372331
upvote count: 1
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49372306
has body: Use the number, not the string: &gt;&gt;&gt; "{0:08b}".format(10) '00001010' To print all: &gt;&gt;&gt; for i in range(0, 256): ... print("{0:08b}".format(i)) ... 00000000 00000001 00000010 00000011 00000100 ... 11111011 11111100 11111101 11111110 11111111

http://stackoverflow.com/q/49332961
downvote count: 1
favorite count: 0
type: Question
has body: I have a CSV file which actually contains edge list like this: "YDR143C","YER068W" "YMR207C","YNR016C" "YIL135C","YMR139W" "YNL316C","YOL082W" "YHR211W","YNL255C" "YJL125C","YNL062C" "YDL014W","YKL125W" Now I need to create a graph from this and need to plot in Python. I m a new user of Python language and don't know how to read this file. How can I do this?
tagged with: http://stackoverflow.com/tag/csv
has title: Creating Graph object from CSV file in Python
has comment: http://stackoverflow.com/comment/85668039
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49333513
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85668141
has answer: http://stackoverflow.com/a/49333513
upvote count: 0
answer count: 1

http://stackoverflow.com/q/49364525
tagged with: gstreamer
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: Installation of Pyobject in windows 10 Anaconda environment.
upvote count: 1
tagged with: python-gstreamer
tagged with: anaconda
score: 1
tagged with: python
has body: I am trying to use gstreamer with my Anaconda environment on Windows 10 machine. I get gstreamer successfully installed on my machine. The version of Gstreamer is 1.13, the latest for windows. But now I want to use it through Python IDE. But as my machine does not have installed Pyobject ,it throws error like no module named gi.I have used pip install, downloaded the zip file and then run python setup.py install and also through conda install command, but nothing works. How can I install pyobject and pygst on Anaconda environment ?
favorite count: 0
type: Question

http://stackoverflow.com/comment/85739589
type: QuestionComment
has text: Thank you Martijn Peters, I didn't know about getattr() and it seems perfect for solving my problem. What I thought class_x=x, class_y=y would do is allow me to define what class attribute I was trying to pull a value from. which seems to be what getattr() is for.
score: 0
comment on: http://stackoverflow.com/q/49369089
type: Comment

http://stackoverflow.com/a/49390906
type: Answer
has comment: http://stackoverflow.com/comment/85846076
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49377836
has body: As described on MSDN for ??: ?? Expression and looking up the linked C++ numbers and operators: LValue = Value &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Assign you can simply ?? &lt;variable name&gt; = &lt;value&gt; As an alternative, you can also use the e* commands to edit values in memory, e.g. eb &lt;address&gt; &lt;byte1&gt; &lt;byte2&gt;
answers question: http://stackoverflow.com/q/49377836

http://stackoverflow.com/q/49387205
tagged with: time-series
has answer: http://stackoverflow.com/a/49387275
has title: Pandas .resample() or .asfreq() fill forward times
downvote count: 0
tagged with: resampling
tagged with: python
accepted answer: http://stackoverflow.com/a/49387275
type: AnsweredQuestion
score: 3
tagged with: pandas
upvote count: 3
answer count: 1
has body: I'm trying to resample a dataframe with a time series from 1-hour increments to 15-minute. Both .resample() and .asfreq() do almost exactly what I want, but I'm having a hard time filling the last three intervals. I could add an extra hour at the end, resample, and then drop that last hour, but it feels hacky. Current code: df = pd.DataFrame({'date':pd.date_range('2018-01-01 00:00', '2018-01-01 01:00', freq = '1H'), 'num':5}) df = df.set_index('date').asfreq('15T', method = 'ffill', how = 'end').reset_index() Current output: date num 0 2018-01-01 00:00:00 5 1 2018-01-01 00:15:00 5 2 2018-01-01 00:30:00 5 3 2018-01-01 00:45:00 5 4 2018-01-01 01:00:00 5 Desired output: date num 0 2018-01-01 00:00:00 5 1 2018-01-01 00:15:00 5 2 2018-01-01 00:30:00 5 3 2018-01-01 00:45:00 5 4 2018-01-01 01:00:00 5 5 2018-01-01 01:15:00 5 6 2018-01-01 01:30:00 5 7 2018-01-01 01:45:00 5 Thoughts?
favorite count: 0
type: Question

http://stackoverflow.com/a/49431180
answers question: http://stackoverflow.com/q/49429147
score: 3
has comment: http://stackoverflow.com/comment/130406472
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85914398
has body: I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using mask as follows. # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a So, your implementation will be something like L_1 = torch.tril(torch.randn((D, D))) v = torch.exp(torch.diag(L_1)) mask = torch.diag(torch.ones_like(v)) L_1 = mask*torch.diag(v) + (1. - mask)*L_1 Not as elegant as numpy, but not too bad either.
has comment: http://stackoverflow.com/comment/85912804
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49429147
has comment: http://stackoverflow.com/comment/85870360
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85699124
score: 0
type: Comment
has text: Can you write a function that returns a printable representation of the linked list? It should be easier to see what items are getting removed using that.
type: QuestionComment
comment on: http://stackoverflow.com/q/49349644

http://stackoverflow.com/q/49392489
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/49392581
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/49392581
has title: Dataframe column based on 4 conditions, nested np.where
downvote count: 0
upvote count: 1
has body: The dataframe with which I am working has 4 possible combinations over 2 columns and several hundred groups. | Group | Before | After | |:-----:|:----------:|:----------:| | G1 | Injection | Injection | | G1 | Injection | Production | | G1 | Production | Injection | | G1 | Production | Production | There are 3 pre-calculated columns which need to be pulled based on the Before/After combination as seen below. | Group | Before | After | Output | |:-----:|:----------:|:----------:|:----------------------:| | G1 | Injection | Injection | df['DTI'] | | G1 | Injection | Production | df['DTWF'] + df['DTP'] | | G1 | Production | Injection | df['DTWF'] + df['DTI'] | | G1 | Production | Production | df['DTP'] | I have tried nesting multiple np.where's np.where(df['Before'] == 'Injection' &amp; df['After'] == 'Injection', df['DTI'], np.where(....)) Which resulted in: ValueError: either both or neither of x and y should be given and nesting multiple np.logical: np.where(np.logical_and(df['Before'] == 'Injection' &amp; df['After'] == 'Injection'), df['DTP']) Which resulted in: the truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have reached the upper limit of what I can do and need some ideas!
possible better answer: http://stackoverflow.com/a/49392721
type: Question
has answer: http://stackoverflow.com/a/49392721
type: AnsweredQuestion

http://stackoverflow.com/a/49341001
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85682695
has comment: http://stackoverflow.com/comment/85682535
has comment: http://stackoverflow.com/comment/85682330
has comment: http://stackoverflow.com/comment/85682692
has comment: http://stackoverflow.com/comment/85684980
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85682773
answers question: http://stackoverflow.com/q/49340778
has body: You have a subquery, so create one first: all_emails_stmnt = session.query(customerEmails.parent_id).subquery() and then you can use that to filter your other table: translations_with_no_email = session.query(customerTranslations).filter( ~customerTranslations.id.in_(all_emails_stmnt)) This produces the same SQL (but with all the column names expanded, rather than using *, the ORM then can create your objects): &gt;&gt;&gt; all_emails_stmnt = session.query(customerEmails.parent_id).subquery() &gt;&gt;&gt; print(all_emails_stmnt) SELECT customer_emails.parent_id FROM customer_emails &gt;&gt;&gt; translations_with_no_email = session.query(customerTranslations).filter( ... ~customerTranslations.id.in_(all_emails_stmnt)) &gt;&gt;&gt; print(translations_with_no_email) SELECT customer_translation.id AS customer_translation_id FROM customer_translation WHERE customer_translation.id NOT IN (SELECT customer_emails.parent_id FROM customer_emails) You could also use NOT EXISTS: from sqlalchemy.sql import exists has_no_email_stmnt = ~exists().where(customerTranslations.id == customerEmails.parent_id) translations_with_no_email = session.query(customerTranslations).filter(has_no_email_stmnt) or, if you have a a backreference on the customerTranslations class pointing to emails, named emails, use .any() on the relationship and invert: session.query(customerTranslations).filter( ~customerTranslations.emails.any()) Back in 2010 NOT EXISTS was a little slower on MySQL but you may want to re-assess if that is still the case.
accepted answer of: http://stackoverflow.com/q/49340778
has comment: http://stackoverflow.com/comment/85682757

http://stackoverflow.com/q/49383613
type: Question
has answer: http://stackoverflow.com/a/49383713
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has title: Cant run Machine Learning codes with virtual environment
has body: im trying to test Machine Learning codes from this site :https://github.com/lyuboraykov/flight-genie im really new to machine learning and im using windows. i already installed the requirements to run the code (python, virtualenv, numpy, sklearn, scipy, etc) but i got stuck when i try to run the main code, it shows notification like this : please help, thanks
tagged with: virtual-environment
has comment: http://stackoverflow.com/comment/85768148
answer count: 3
has answer: http://stackoverflow.com/a/49383703
downvote count: 3
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49383757
favorite count: 0

http://stackoverflow.com/comment/85817093
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49407765
has text: Class A is not meant to be run as a unit test, just B. I want B to instantiate one of A's fields (not happening in this example) via that constructor.

http://stackoverflow.com/a/49350017
score: 0
has body: This is a possible solution: import sys aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] mininum = sys.maxsize for j, ele in enumerate(aList): cur_min = min(float(i) for i in ele if i is not None) if cur_min &lt; mininum: minimum = cur_min pos_index = ele.index(minimum) list_index = j print(aList[list_index][pos_index])
answers question: http://stackoverflow.com/q/49349782
type: Answer

http://stackoverflow.com/a/49549152
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: I'd recommend Thespian actors for Python instead of Pykka for a much more complete and feature-full implementation (http://thespianpy.com, disclaimer: I am the author of that package). Using Thespian, you could have a test like: Scenario something Given a running actor system ... Then it completes successfully And in your implementation @given('a running actor system') def step_impl(context): ActorSystem('simpleSystemBase') @then('it completes successfully') def step_impl(context): asys = ActorSystem() asys.createActor(TestActor) response = asys.ask(testActor, 'test data', 5) assert response == 'data is valid' class TestActor(Actor): def receieveMessage(self, msg, sender): if msg == 'test data': self.send(sender, 'data is valid') def after_all(context): ActorSystem().shutdown() This will allow individual tests to access actors, and you can also increase parallelism using other actor system bases: @given('a running multi-process actor system') def step_impl(context): ActorSystem('multiprocTCPBase') Unfortunately, based on a quick review of behave, the core runner is not extensible, so behave itself will probably run your tests serially; if there was a way to run each test in a separate actor that would further increase concurrency beyond what behave currently supports.
answers question: http://stackoverflow.com/q/49365580

http://stackoverflow.com/q/49311795
has comment: http://stackoverflow.com/comment/86188971
tagged with: python
has answer: http://stackoverflow.com/a/49344170
tagged with: kubernetes-helm
answer count: 2
has answer: http://stackoverflow.com/a/49590670
upvote count: 3
type: UnansweredQuestion
downvote count: 2
has body: I am looking for any code example that deploys Helm chart without via CLI call. The reason behind this is: My company got couple existing pipelines written with AWS CodePipeline / CodeBuild / CodeDeploy. They don't like to investigate more time on re-writing all pipelines. My company does not have any plan to maintain extra instance(s) just for deployment. AWS CodePipeline could trigger Lambda, and theoretically I could write some Python code to do the job if Helm provides Python client. Currently I steal Lambda function from this: https://github.com/aws-samples/aws-kube-codesuite Whereas this does not provide same level features as Helm does. We have to provide our release-name system, template system, etc. In other words, it functions poorly if I have big change on the manifest, and does not handle the first time deployment (means deploying manifest to an empty K8S cluster) Also we use Github, although not really relevant. For python client of Helm chart, the best I could find is pyhelm listed on pip. But it does not have sample code for calling deployment, and from some user group / forum feedback the installation process is painful. Somebody also points to azure/draft and another repo but I have no clue on how to come out a solid example that only use Python to deploy Helm chart. Please let me know where I miss. Thanks.
tagged with: amazon-web-services
favorite count: 0
type: Question
has title: Code sample to deploy a Helm chart via API?
linked to: http://stackoverflow.com/q/49540061
score: 1
tagged with: kubernetes

http://stackoverflow.com/q/49402800
tagged with: selenium-chromedriver
answer count: 3
has title: Selenium + XPath: element not found
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I have a Selenium + Python + Chromedriver script which should log in to a website and click on a download button which will download a CSV file. Inspect details of download button is: &lt;button id="csv-button" class="block tiny-margin-top" data-args="csv"&gt; CSV &lt;/button&gt; and XPath is: //*[@id="csv-button"] but it says XPath element not found when I run the script. Please find the code below: click_button = driver.find_element_by_xpath('//*[@id="csv-button"]') click_button.click()
downvote count: 0
tagged with: selenium
possible better answer: http://stackoverflow.com/a/49402972
has answer: http://stackoverflow.com/a/64443694
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49402884
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/49402972
accepted answer: http://stackoverflow.com/a/49402884

http://stackoverflow.com/q/49433896
has answer: http://stackoverflow.com/a/49436644
accepted answer: http://stackoverflow.com/a/49436644
answer count: 1
tagged with: pip
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: setuptools
tagged with: python
has title: Define mirror repositories in dependency_links of python package
has body: Python's package manager allows defining non-PyPI dependencies via dependency_links argument of the setup script. But is it possible to have mirrors defined in a similar way as well? (so, same package, same version, everything the same,- just in two different repositories,- and I want a second one to act as a fallback in case if the first one fails - e.g. host unreachable, authentication failed, etc). UPD I did already try to define more that one URL for the same package in dependency_links. Unfortunately, this does not work as I would like it to. In case if the very first repository that is resolved as a correct match for the requested package/version fails for some reason, then the whole setup script just fails (i.e. it does not try to iterate through all other correct matches until either a good one is found, or all of them fail).
downvote count: 0

http://stackoverflow.com/a/49386138
score: 0
has body: Try converting the string to Unicode and the encode to "utf-8" Ex: string = u"Ľubomír Mezovský" print string[0].encode('utf-8') Output: Ľ Tested in python2.7
type: Answer
answers question: http://stackoverflow.com/q/49386034
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85629057
comment on: http://stackoverflow.com/a/49308418
has text: How would i get the values in same order
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85757702
type: Comment
comment on: http://stackoverflow.com/q/49378547
type: QuestionComment
score: 1
has text: [this answer](https://stackoverflow.com/questions/15900338/python-request-post-with-param-data) may help. you'd neet to [`requests.post`](http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests) your (encoded) image.

http://stackoverflow.com/comment/129705159
has text: Does this answer your question? [Remove duplicates from json data](https://stackoverflow.com/questions/17076345/remove-duplicates-from-json-data)
comment on: http://stackoverflow.com/q/49435728
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49390972
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85783888
upvote count: 1
has answer: http://stackoverflow.com/a/49391341
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49391047
has title: Pythonic way to get initial diff between two lists
has body: I am currently working on a project with Python3, and was needed to implement such code, where I use an API that passes items with limit count, and need to figure out the latest items that have been added. I'm sure there must be a more pythonic way, but couldn't think of any. Kindly let me know if there's similar duplicate question cause I could not find one. list1 = ["d", "e", "f", "g", "h", "i", "j"] # items requested before list2 = ["a", "b", "c", "d", "e", "f", "g"] # items requested now for index, item in enumerate(list2): if item is list1[0]: print(list2[:index]) break UPDATE: I have thousands of items in those lists, and majority of list2 duplicates with items in list1. I need somewhat more efficient way to process those diffs.
tagged with: python
possible better answer: http://stackoverflow.com/a/49391341
has comment: http://stackoverflow.com/comment/85783693
accepted answer: http://stackoverflow.com/a/49391078
has comment: http://stackoverflow.com/comment/85783500
has comment: http://stackoverflow.com/comment/85783486
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85783805
has answer: http://stackoverflow.com/a/49391078
answer count: 3
has comment: http://stackoverflow.com/comment/85783759

http://stackoverflow.com/comment/85856966
score: 0
has text: can you specifically type the desired output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49427866

http://stackoverflow.com/q/49433627
tagged with: python-3.x
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/49493232
tagged with: spacy
type: UnansweredQuestion
has body: I am currently processing texts with the NLP library Spacy. Spacy, however, does not lemmatize all words correctly, therefore I want to extend the lookup table. Currently I am merging Spacy's constant lookup table with my extension and subsequently overwrite Spacy's native lookup table. I have the feeling, however, that this approach may not be the best and most consistent one. Question: Is there another possibility to update the lookup table in Spacy, e.g. an update or extend function? I have read the Docs and could not find something like that. Or is this approach "just fine"? Working example of my current approach: import spacy nlp = spacy.load('de') Spacy_lookup = spacy.lang.de.LOOKUP New_lookup = {'AAA':'Anonyme Affen Allianz','BBB':'Berliner Bauern Bund','CCC':'Chaos Chaoten Club'} Spacy_lookup.update(New_lookup) spacy.lang.de.LOOKUP = Spacy_lookup tagged = nlp("Die AAA besiegt die BBB und den CCC unverdient.") [ print(each.lemma_) for each in tagged] Die Anonyme Affen Allianz besiegen der Berliner Bauern Bund und der Chaos Chaoten Club unverdient .
has answer: http://stackoverflow.com/a/52697695
answer count: 1
has title: Extending Lemma Lookup Table in Spacy
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86106074
downvote count: 0
tagged with: nlp
type: Question

http://stackoverflow.com/comment/118226597
has text: In my case, this works: sudo apt-get install libnss3
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/66166241

http://stackoverflow.com/comment/85912036
comment on: http://stackoverflow.com/a/49438960
type: AnswerComment
has text: You are trying to apply the method to a `Series`, so I assume your "dataframe" is not actually a "dataframe". I can't tell what format your data is in, but I would recommend you look for a method to turn it into an actual dataframe. Look [here](https://stackoverflow.com/questions/26047209/what-is-the-difference-between-a-pandas-series-and-a-single-column-dataframe) for reference
score: 0
type: Comment

http://stackoverflow.com/comment/85670687
score: 0
comment on: http://stackoverflow.com/q/49334378
has text: see this if it helps: https://stackoverflow.com/questions/49315872/how-to-convert-string-containing-unicode-escape-u-to-utf-8-string
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49340877
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49351692
has comment: http://stackoverflow.com/comment/85682102
tagged with: sqlite
has body: I want assign the data which is retrieve from database (sqlit3) particular column for a variable and call that variable for word tokenize. please help with this I know tokenize part but I want to know how to assign the db value to a variable in python.
type: Question
has title: how to assign db column value to variable and call it to tokenize in python
has comment: http://stackoverflow.com/comment/85703025
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85688832
tagged with: python
has answer: http://stackoverflow.com/a/49361558

http://stackoverflow.com/comment/85752343
type: QuestionComment
score: 1
has text: Try to remove the `encode()` call. It creates a bytes type which is always represeted as an escape sequence.
comment on: http://stackoverflow.com/q/49375525
type: Comment

http://stackoverflow.com/comment/85664215
type: AnswerComment
comment on: http://stackoverflow.com/a/49331077
has text: We don't know if it is JSON string or a fraction of a string. Regex is the only solution as the question was written.
score: 1
type: Comment

http://stackoverflow.com/a/49304361
accepted answer of: http://stackoverflow.com/q/49297339
has body: raw() is new in Scapy 2.4.0 (including release candidates, aka 2.4.0-rc*). You can either install Scapy 2.4.0 or newer, or use str() for now.
answers question: http://stackoverflow.com/q/49297339
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49374851
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49374881
type: UnansweredQuestion
has title: Decoding nonbreaking space in pandas read_html
tagged with: python
has body: The default behavior of pandas.read_html appears to be to convert &amp;nbsp; characters to unicode \xa0 codes: url = 'http://www.reuters.com/finance/stocks/company-officers/IBM' ibm = pd.read_html(url, header=0)[0] ibm.iloc[0,0] 'Virginia\xa0Rometty' I know I can use a converter to convert these to spaces as follows: spacer = lambda s: s.replace(u'\xa0', ' ') ibm = pd.read_html(url, header=0, converters={'Name':spacer})[0] ibm.iloc[0,0] 'Virginia Rometty' This seems unnecessarily complicated for something that must be a pretty common. Is there another way? Perhaps an encoding option?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/comment/85578160
type: AnswerComment
comment on: http://stackoverflow.com/a/49287543
has text: However for the sake of debugging, is there an alternative to building and running new images when things are changed? My current work flow has been making edits to docker -> docker build -> docker run. Each time creating new images, which is obviously bad practice, and takes hours when there are 15 different requirements.txt files that are installed each build.
score: 0
type: Comment

http://stackoverflow.com/comment/85787588
has text: I added the metadata and also disable the dictionary but there is no change. sqlContext.setConf('parquet.enable.dictionary', False)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49378466
type: Comment

http://stackoverflow.com/comment/85663916
comment on: http://stackoverflow.com/q/49330829
type: Comment
has text: Uhhh this looks a lot like it's going to fail at some point. However, in order to help you here it would make sense to tell us what exactly you are trying to achieve with this code. Why are you using multiprocessing in the first place? How is the desired output to look like? What are the different parts in the code supposed to do?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85787004
type: AnswerComment
comment on: http://stackoverflow.com/a/49392405
score: 0
has text: @AndreaCorbellini: I'd say it's not the _only_ way to start the task; you can use `.wait` if you don't care about the result. Still, without a `.get` or `.wait`, the task will not start, AFAICT. Thanks for pointing at it; I'll update my answer.
type: Comment

http://stackoverflow.com/q/49413602
has comment: http://stackoverflow.com/comment/85829183
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/85832597
has title: Clean up clunky for loop
upvote count: 1
has comment: http://stackoverflow.com/comment/85828858
score: 1
favorite count: 0
type: Question
has body: I am looking for a nicer way to clean up this clunky nest for-loop that I have. names = ['name1', 'name2', 'name3', ...] values = [[1, 2, 3, ...], [10, 20, 30, ...], [100, 200, 300, ...]] for i in range(len(values[0])): for name, value in zip(names, values): print(name, value[i]) Output: name1 1 name2 10 name3 100 name1 2 name2 20 name3 200 name1 3 name2 30 name3 300 ... The above snippet gives the desired output but is certainly not very pythonic.
accepted answer: http://stackoverflow.com/a/49414366
tagged with: python
has answer: http://stackoverflow.com/a/49414366
possible better answer: http://stackoverflow.com/a/49415017
linked to: http://stackoverflow.com/q/47945761
tagged with: for-loop
has answer: http://stackoverflow.com/a/49415017
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49289429
has answer: http://stackoverflow.com/a/49289470
tagged with: python
has comment: http://stackoverflow.com/comment/85582411
tagged with: environment
score: 0
has comment: http://stackoverflow.com/comment/85582600
tagged with: environment-variables
answer count: 1
has comment: http://stackoverflow.com/comment/85615033
has comment: http://stackoverflow.com/comment/85582260
upvote count: 1
has comment: http://stackoverflow.com/comment/85582373
has comment: http://stackoverflow.com/comment/85582118
has comment: http://stackoverflow.com/comment/85582076
downvote count: 1
favorite count: 0
type: Question
has body: Hi I am in the end trying to get PyQt to convert a ui to a py file via pyuic. That being said, all of the commands I am trying are being rejected as inoperable. Images below! Any help with this is greatly appreciated! Thank you!! Image 1 is the cmd returning the script Image 2 is the user environment variables Image 3 is the system environment variables
has title: How can you fix the environment variables when having Python 2.7 installed for both a x32 and x64 bit system?
type: UnansweredQuestion

http://stackoverflow.com/comment/85571170
comment on: http://stackoverflow.com/a/49281755
has text: I get an error: at line : pd.concat([gfeb,gmacth]).sort_values(by=['date'], ascending=[False]).The error is: TypeError: cannot concatenate object of type "<class 'pandas.core.groupby.DataFrameGroupBy'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85715233
comment on: http://stackoverflow.com/a/49324565
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your answer!when I run the code on 'train' mode,It shows that 'SummarizationModel' object has no attribute '_train_op' and 'INFO:tensorflow:Error reported to Coordinator: Attempted to use a closed Session'.Do you know the problem？Does tensorflow1.6 have other changes aboout the train_op or the sess or the supervisior?

http://stackoverflow.com/q/49352488
tagged with: python
tagged with: django-testing
has body: By running './manage.py test', data from local 'postgres' database are populated into 'test_postgres' database. I am not able to find way, how to disable this behavior. By running './manage.py test', I want to get non populated database with applied migrations. class Local(Common): DEBUG = True # Testing INSTALLED_APPS = Common.INSTALLED_APPS INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ BASE_DIR, '-s', '--nologcapture', '--with-coverage', '--with-progressive' ] # Postgres DATABASES = { 'default': dj_database_url.config( default='postgres://postgres:@postgres:5432/postgres', conn_max_age=int(os.getenv('POSTGRES_CONN_MAX_AGE', 600)), ) }
type: AnsweredQuestion
score: 0
upvote count: 1
tagged with: django-tests
accepted answer: http://stackoverflow.com/a/49352517
answer count: 1
downvote count: 1
favorite count: 0
tagged with: unit-testing
has answer: http://stackoverflow.com/a/49352517
type: Question
has title: Django: How to run tests against empty (non populated) database
tagged with: django

http://stackoverflow.com/a/49400299
type: Answer
has body: I'm not sure what your evaluation function is supposed to do, so I took a guess and implemented a wrapper for it. I took value_list = module.eval(point_matrix, func_id) to mean you want to return a list of result of evaluating some function against each row of data points, and came up with the following. Things I changed: The typemaps replace the first four parameters with a Python list of lists of numbers. space for the results in f was malloced. To accept other numeric types except float, PyFloat_AsDouble was called on each value, and PyErr_Occurred was called to see if it failed to convert. The freearg typemap now frees both allocations. The argout typemap now handles the f output parameter correctly. I added a sample eval implementation. %module cec17 %typemap(in) (double *x, int nx, int mx, double* f) %{ if (PyList_Check($input)) { $3 = PyList_Size($input); $2 = PyList_Size(PyList_GetItem($input, 0)); $1 = malloc($2 * $3 * sizeof(double)); $4 = malloc($3 * sizeof(double)); for (int i = 0; i &lt; $3; i++) { for (int j = 0; j &lt; $2; j++) { PyObject *o = PyList_GetItem(PyList_GetItem($input, i), j); double tmp = PyFloat_AsDouble(o); if(PyErr_Occurred()) SWIG_fail; $1[i * $2 + j] = PyFloat_AsDouble(o); } } } else { PyErr_SetString(PyExc_TypeError, "not a list"); return NULL; } %} %typemap(freearg) (double *x, int nx, int mx, double* f) %{ free($1); free($4); %} %typemap(argout) (double *x, int nx, int mx, double* f) (PyObject* tmp) %{ tmp = PyList_New($3); for (int i = 0; i &lt; $3; i++) { PyList_SET_ITEM(tmp, i, PyFloat_FromDouble($4[i])); } $result = SWIG_Python_AppendOutput($result, tmp); %} %inline %{ void eval(double *x, int nx, int mx, double *f, int func_num) { for(int i = 0; i &lt; mx; ++i) { f[i] = 0.0; for(int j = 0; j &lt; nx; ++j) f[i] += x[i*nx+j]; } } %} Output: &gt;&gt;&gt; import cec17 &gt;&gt;&gt; cec17.eval([[1,2,3],[4,5,6]],99) [6.0, 15.0] Error checking could be improved. For example, checking for sequences instead of lists. Only the outer lis…
score: 0
has comment: http://stackoverflow.com/comment/85820504
answers question: http://stackoverflow.com/q/49398631

http://stackoverflow.com/q/49413504
answer count: 3
has answer: http://stackoverflow.com/a/61980959
has title: brew-installed Python not overriding system python
possible better answer: http://stackoverflow.com/a/61980959
upvote count: 20
tagged with: homebrew
has comment: http://stackoverflow.com/comment/85828632
downvote count: 0
linked to: http://stackoverflow.com/q/19340871
has answer: http://stackoverflow.com/a/49415242
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I just used brew to install Python 3 on OS X. The python3 command now starts the interpreter using brew Python 3.6, but python still opens the interpreter with the default system Python 2.7. My understanding was that, by default, brew Python should now override system Python. (I.e., see Order of /usr/bin and /usr/local/bin and more in $PATH). In my PATH, /usr/local/bin comes before /usr/bin, so it shouldn't be a PATH issue. I have tried restarting Terminal, with no effect. Here is my full PATH in case that is relevant. /Users/**/.rvm/gems/ruby-1.9.3-p362/bin:/Users/**/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/**/.rvm/rubies/ruby-1.9.3-p362/bin:/Users/**/.rvm/bin:/Users/**/.rvm/bin:/Users/**/Python/PmagPy/programs/conversion_scripts2/:/Users/**/Python/PmagPy/programs/conversion_scripts/:/Users/**/Python/PmagPy/programs:/usr/local/heroku/bin:./bin:/usr/local/sbin:/usr/local/bin:/usr/local/share/npm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/opt/X11/bin Why isn't brew Python taking precedence? And how can I fix (or troubleshoot) this? If I can't find another option, I can create an alias, but I prefer to understand what's happening and get to the root of the problem. Update: I checked out the "possible duplicate" question, but my issue doesn't appear to be a linking problem: ~ brew link --overwrite --dry-run python Warning: Already linked: /usr/local/Cellar/python/3.6.4_4 To relink: brew unlink python &amp;&amp; brew link python ~
tagged with: path
tagged with: python
linked to: http://stackoverflow.com/q/34984870
linked to: http://stackoverflow.com/q/6908143
tagged with: macos
has answer: http://stackoverflow.com/a/51939526
accepted answer: http://stackoverflow.com/a/51939526
score: 20

http://stackoverflow.com/q/49432661
has answer: http://stackoverflow.com/a/49440351
upvote count: 6
has title: Zlib compress in python
has comment: http://stackoverflow.com/comment/85867627
type: AnsweredQuestion
answer count: 2
tagged with: compression
has comment: http://stackoverflow.com/comment/85867107
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/34443793
has body: Why is the size of the compressed string bigger? Doesn't the zlib need to compress ?? Example: import zlib import sys str1 = "abcdefghijklmnopqrstuvwxyz" print "size1: ", sys.getsizeof(str1) print "size2: ", sys.getsizeof(zlib.compress(str1)) The output: size1: 47 size2: 55
accepted answer: http://stackoverflow.com/a/49432741
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49432741
has comment: http://stackoverflow.com/comment/85867128
possible better answer: http://stackoverflow.com/a/49440351
has comment: http://stackoverflow.com/comment/85867768
tagged with: python
has comment: http://stackoverflow.com/comment/85867182

http://stackoverflow.com/q/49330708
score: 6
has answer: http://stackoverflow.com/a/49330756
has body: How do you count the amount of zero rows of a numpy array? array = np.asarray([[1,1],[0,0],[1,1],[0,0],[0,0]]) -> has three rows with all zero's, hence should give 3 Took me sometime to figure out this one and also couldn't find an answer on SO
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49330744
has answer: http://stackoverflow.com/a/49330744
possible better answer: http://stackoverflow.com/a/49330756
has answer: http://stackoverflow.com/a/49330709
tagged with: python
upvote count: 6
type: AnsweredQuestion
has title: Count zero rows in 2D numpy array
answer count: 3
downvote count: 0

http://stackoverflow.com/q/49375222
has comment: http://stackoverflow.com/comment/85755385
has title: How to click elements in lightbox using python
tagged with: selenium-webdriver
has body: I'm trying to automate an e-commerce website, after i click 'add to cart' a lightbox will be displayed for user to proceed to view cart and to continue to check out. Here is my sample code, i think my code doesn't find the button because the lightbox is still loading. driver.find_element_by_id("qty").send_keys("4") driver.find_element_by_class_name("add_to_cart_btn").click() Lightbox loading here driver.find_element_by_class_name("button_primary").click() #for clicking the view cart driver.find_element_by_link_text("Proceed to Checkout").click()
score: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85752467
has comment: http://stackoverflow.com/comment/85886319
type: Question
has answer: http://stackoverflow.com/a/49376490
tagged with: automation
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85752949

http://stackoverflow.com/q/49394478
has comment: http://stackoverflow.com/comment/85791650
has comment: http://stackoverflow.com/comment/85790712
has comment: http://stackoverflow.com/comment/85790769
has title: Python Hamming distance rewrite countless for cycles into recursion
tagged with: python
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/49394710
type: AnsweredQuestion
score: 0
tagged with: hamming-distance
has answer: http://stackoverflow.com/a/49394710
has body: I have created a code generating strings which have hamming distance n from given binary string. Though I'm not able to rewrite this in a simple recursive function. There are several sequences (edit: actually only one, the length change) in the for loops logic but I don't know how to write it into the recursive way (the input for the function is string and distance (int), but in my code the distance is represented by the count of nested for cycles. Could you please help me? (e.g. for string '00100' and distance 4, code returns ['11010', '11001', '11111', '10011', '01011'], for string '00100' and distance 3, code returns ['11000', '11110', '11101', '10010', '10001', '10111', '01010', '01001', '01111', '00011']) def change(string, i): if string[i] == '1': return string[:i] + '0' + string[i+1:] else: return string[:i] + '1' + string[i+1:] #'0' on input def hamming_distance(number): array = [] for i in range(len(number)-3): #change first bit a = number a = change(a, i) #change bit on index i for j in range(i+1, len(number)-2): #change second bit b = a b = change(b, j) for k in range(j+1, len(number)-1): #change third bit c = b c = change(c, k) for l in range(k+1, len(number)): #change fourth bit d = c d = change(d, l) array.append(d) return array print(hamming_distance('00100')) Thank you!
answer count: 1
tagged with: recursion
type: Question

http://stackoverflow.com/a/49431872
score: 1
downvote count: 1
type: Answer
upvote count: 2
has body: One way is to use a nested list comprehension with zip: paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't']] res = [[i, j] for x in paths for i, j in zip(x, x[1:])] Result: [['s', 'a'], ['a', 'b'], ['b', 't'], ['s', 'c'], ['c', 'd'], ['d', 't']]
answers question: http://stackoverflow.com/q/49431714

http://stackoverflow.com/q/49292064
has comment: http://stackoverflow.com/comment/85588073
has comment: http://stackoverflow.com/comment/85588003
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85587279
has title: Cannot get correct html from VB
tagged with: vb.net
has body: In VB, I wrote: Dim client As New System.Net.WebClient() Dim sourceString As String = client.DownloadString("https://www.facebook.com/audi/posts/10155153026226470") However, the two string does not contain the content of the webpage. How to write the correct VB code?
type: Question
has comment: http://stackoverflow.com/comment/85588859
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85588730

http://stackoverflow.com/comment/85869113
score: 0
has text: You could use a multiIndex, with the record and date
comment on: http://stackoverflow.com/q/49433283
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85634500
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49316345
has text: @David you can use * to unpack iterables like: ```print(*l)```
type: QuestionComment

http://stackoverflow.com/comment/85819002
has text: Thanks for the explanation. In this instance it is such that it is not present but when I try to run the same code for another record which does have the 5th item, it still doesn't work. try `print records[1]`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49407868
type: Comment

http://stackoverflow.com/q/49396521
type: UnansweredQuestion
tagged with: list-comprehension
has body: I have huge list of tuples that looks like: data =[ ('-0.167969896634', '0.475981802514', ''), ('-0.186100643368', '0.47510168705', ''), ('-0.205064369305', '0.476225633961', ''), ...] I need to remove the ' ' and convert them all to floats, but I am not sure how to do it. I tried this: [tuple(float(x) for x in t) for t in data] It however will tell me that a str cannot be converted to type float and I suspect it may be the '' part?
has comment: http://stackoverflow.com/comment/85795115
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49396962
has answer: http://stackoverflow.com/a/49396559
downvote count: 0
answer count: 3
score: 1
upvote count: 1
has title: Remove Element of list of tuple when it is ''
favorite count: 0
has comment: http://stackoverflow.com/comment/85794797
has comment: http://stackoverflow.com/comment/85794897
type: Question
has answer: http://stackoverflow.com/a/49396546
has comment: http://stackoverflow.com/comment/85795125
has comment: http://stackoverflow.com/comment/85795038
tagged with: python
has comment: http://stackoverflow.com/comment/85795191

http://stackoverflow.com/comment/85743066
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49370719
has text: Thanks, like i said i'm fairly new to python so could you please give me an example of what that would look like in code if you have the time?

http://stackoverflow.com/q/49300023
has comment: http://stackoverflow.com/comment/85602459
has body: Python 3.6 here. I have a DataFrame that I reduce to 2 columns, the text and the date (type datetime). I'm trying to filter by row where it's a certain hour with this code : import pandas as pd laDataBrute = {'timestamp':['1519245127727', '1519246924475'], 'date creation': ['Wed Feb 21 20:32:07 +0000 2018', 'Wed Feb 21 21:02:04 +0000 2018' ], 'texte':['GE CFO says no plans for an equity raise', 'Baker Hughes rises after GE CFO signals plans']} laDataBrute = pd.DataFrame(laDataBrute) laDataBrute['date creation'] = pd.to_datetime(laDataBrute['timestamp'], unit='ms') resultat = laDataBrute.loc[laDataBrute["texte"].str.contains(r'\bGE\b', regex=True) &amp; laDataBrute["date creation"].dt.hour == 21, ["texte","date creation"]] print(resultat) Here is the ouput : Empty DataFrame Columns: [texte, date creation] Index: [] Don't know what i did wrong, thanks !
has title: Filter DataFrame row by hour
score: 1
has comment: http://stackoverflow.com/comment/85602757
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85602022
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49300571
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85602055
has answer: http://stackoverflow.com/a/49300571
has comment: http://stackoverflow.com/comment/85601839
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49301389
has answer: http://stackoverflow.com/a/49304525
has title: Boundingbox defintion for opencv object tracking
tagged with: video-tracking
favorite count: 0
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/49301979
has body: How is the boundingbox object defined that takes opencv's tracker.init() function? is it (xcenter,ycenter,boxwidht,boxheight) or (xmin,ymin,xmax,ymax) or (ymin,xmin,ymax,xmax) or something completely different? I am using python and OpenCV 3.3 and i basically do the following on each object i want to track for each frame of a video: tracker = cv2.trackerKCF_create() ok = tracker.init(previous_frame,bbox) bbox = tracker.update(current_frame)
score: 7
has answer: http://stackoverflow.com/a/49301979
has comment: http://stackoverflow.com/comment/85605688
tagged with: python
has comment: http://stackoverflow.com/comment/85605119
has comment: http://stackoverflow.com/comment/85605310
has comment: http://stackoverflow.com/comment/85605223
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49304525
downvote count: 0
upvote count: 7

http://stackoverflow.com/q/49394654
has title: object not iterable when implementing transformers for a pipeline in skit
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
has body: I have a list of strings which I watn to classify. I'm using a pipeline object. I implemented two dummies transformers: one convert the data to an specific format (to be accepted by another transformer) and the other converts the data again to its original form (a kind of inverse). X and y are list of strings, suppose X=['London is great', 'London is beautiful', 'I hate London'] and y=['p','p','n']. I want X to be converted to a list of lists of strings: X=[['London is great'], ['London is beautiful'], ['I hate London']] My code is the following: from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_selection import SelectKBest, chi2 from sklearn.pipeline import Pipeline from sklearn.base import TransformerMixin, BaseEstimator vectorizer = CountVectorizer(input=u'content', analyzer=u'word', lowercase=True, stop_words=cached_stopwords, strip_accents=u'unicode', ngram_range=(1, 3), binary=False) estimators = [('pre_ds', PreprocessPreDS()), ('post_ds', PreprocesarPostDS()), ('vectorizer', vectorizer), ('feature_selector', SelectKBest(chi2, k=100)), ('clf', MultinomialNB())] # create the pipeline pipe = Pipeline(estimators) pipe.fit(X_train, y_train) where my costume transformers are the following: class PreprocessPreDS(BaseEstimator, TransformerMixin): def __init__(self): pass def transform(self, X, *_): return [[x] for x in X] def fit(self, *_): return self def fit_transform(self, X, y=None, **fit_params): return self.fit(X) def get_params(self, deep=True): """ :param deep: ignored, as suggested by scikit learn's documentation :return: dict containing each parameter from the model as name and its current value """ return {} def set_params(self, **parameters): """ set all parameters for current objects :param parameters: dict containing its keys and values to be initialised :return: self """ for parameter, value in parameters.items(): setattr(self, parameter, value) return self class PreprocesarPo…
type: Question
accepted answer: http://stackoverflow.com/a/49399780
has answer: http://stackoverflow.com/a/49399780

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/49344080
tags question: http://stackoverflow.com/q/49417788
tags question: http://stackoverflow.com/q/49373619
tags question: http://stackoverflow.com/q/49386293
tags question: http://stackoverflow.com/q/49371340
type: Tag

http://stackoverflow.com/comment/85825577
comment on: http://stackoverflow.com/q/49411721
score: 3
has text: Possible duplicate of [Convert hex string to int in Python](https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85653423
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49324838
has text: have you tried df.to_json(orient='index')
score: 0

urllib2
tags question: http://stackoverflow.com/q/49349186
tag name: urllib2
tags question: http://stackoverflow.com/q/49423082
tags question: http://stackoverflow.com/q/49341173
type: Tag

http://stackoverflow.com/comment/85730726
score: 0
has text: Possible duplicate of [Setting Time Limit on specific task with celery](https://stackoverflow.com/questions/11672179/setting-time-limit-on-specific-task-with-celery)
comment on: http://stackoverflow.com/q/49363095
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49322932
has comment: http://stackoverflow.com/comment/85666256
tagged with: smoothing
tagged with: python
type: Question
score: 2
tagged with: numpy
has title: Scipy implementation of Savitzky-Golay filter
upvote count: 2
has answer: http://stackoverflow.com/a/49330505
answer count: 1
downvote count: 0
has body: I was looking at the scipy cookbook implementation of the Savitzky-Golay algorithm: #!python def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.…
has comment: http://stackoverflow.com/comment/85654206
tagged with: scipy
has comment: http://stackoverflow.com/comment/85663480
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49330505
tagged with: trend
has comment: http://stackoverflow.com/comment/85662360

http://stackoverflow.com/comment/85962930
has text: Can you reduce this to a simpler example, without any irrelevant code, that has the same problem, and where a solution to your example would let you build a solution for your real code? That would make this a lot easier to solve. See [mcve] in the help for pointers. (This is definitely an answerable question as-is, it could just be a more easily answerable question.)
comment on: http://stackoverflow.com/q/49429368
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49439816
has comment: http://stackoverflow.com/comment/85881669
has body: I got an error of 'list' object has no attribute 'get'. Usually, it worked fine, weather_1D_ago = data['city']['weather']['daily'][0]['actual']['fmt'] weather_2D_ago = data['city']['weather']['daily'][1]['actual']['fmt'] 'city': {'weather': {'daily': [{'actual': {'fmt': '1.2', 'raw': 1.2}, 'date': '1D_ago', 'estimate': {'fmt': '1.3', 'raw': 1.3}}, {'actual': {'fmt': '2.2', 'raw': 2.2}, 'date': '2D_ago', 'estimate': {'fmt': '2.3', 'raw': 2.3}},, Until the path was missing, as shown below: 'city': {'weather': {'daily': []}, Update: I tried to use .get() to achieve the data, and make it return as None if the value is missing. weather_1D_ago = data['city']['weather'].get('daily', {})[0].get('actual', {}).get('fmt', {}) weather_2D_ago = data['city']['weather'].get('daily', {})[1].get('actual', {}).get('fmt', {}) But I just got an error of list index out of range I'd avoid using try-except blocks because it will mix up my other codes when referred to weather_1D_ago and another error will generate: local variable 'weather_1D_ago' referenced before assignment So, how would you make it return None using .get() even if the path is not valid? Thanks!
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85881686
accepted answer: http://stackoverflow.com/a/49440062
answer count: 1
has comment: http://stackoverflow.com/comment/85881847
has comment: http://stackoverflow.com/comment/85882186
type: Question
has comment: http://stackoverflow.com/comment/85881797
has comment: http://stackoverflow.com/comment/85881929
tagged with: python
has answer: http://stackoverflow.com/a/49440062
has title: list index out of range using get()

http://stackoverflow.com/a/49355027
answers question: http://stackoverflow.com/q/49355011
has body: (user) evaluates to user in Python; however, sqlite requires a list or tuple object. Therefore, you need to add a comma to the tuple: use = conn.execute("SELECT * FROM users WHERE USERS = ?",(user,)) ... passw = conn.execute("SELECT * FROM users WHERE PASS = ?", (password,))
type: Answer
has comment: http://stackoverflow.com/comment/85716894
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49355011

http://stackoverflow.com/q/49341960
has title: TypeError from use of "|" in re.search("RE"|"RE"|"RE", string)
has answer: http://stackoverflow.com/a/49341976
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85684099
answer count: 1
has comment: http://stackoverflow.com/comment/85684147
tagged with: regex
has body: According to the docs, "|" can be used to create a regular expression that matches either of the patterns separated by "|". I am trying to use the following to see if moves contains a string that matches one of "UP""DOWN""LEFT""RIGHT": moves = input("UP 9") m = re.search("UP"|"DOWN"|"LEFT"|"RIGHT", moves) But I keep getting the "TypeError: unsupported operand type(s) for |: 'str' and 'str'". How to fix it? I tried looking online but there are few samples that show the use of "|" in re. Is it not commonly used for some reason?
has comment: http://stackoverflow.com/comment/85684190

http://stackoverflow.com/comment/85604914
has text: This will not give dict as OP needs. How to generate the dict op wants from new_df
score: 0
comment on: http://stackoverflow.com/a/49301415
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49351717
has comment: http://stackoverflow.com/comment/85703749
downvote count: 1
favorite count: 0
has body: Suppose L = [{'C', 'T'}, {'L'}, {'M'}] let c1 = 'C' and c2 = 'M' I want to union if c1 and c2 are in different sets. How would I check that 'C' is in a different set than 'M' so that I can union it efficiently. I am trying to avoid multiple loops. (If c1 and c2 are in same set then do nothing) For this example the output would be: [{'C', 'T', 'M'}, {'L'}]
has comment: http://stackoverflow.com/comment/85703446
tagged with: list
has comment: http://stackoverflow.com/comment/85703553
score: 1
tagged with: set
has comment: http://stackoverflow.com/comment/85703657
has comment: http://stackoverflow.com/comment/85703415
has comment: http://stackoverflow.com/comment/85703767
type: Question
has title: Python Check if item in different set, union them
answer count: 2
has answer: http://stackoverflow.com/a/49351990
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49351961

http://stackoverflow.com/q/49360384
has comment: http://stackoverflow.com/comment/85761261
has comment: http://stackoverflow.com/comment/85732306
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85723865
downvote count: 0
has comment: http://stackoverflow.com/comment/85733423
score: 6
has comment: http://stackoverflow.com/comment/85722360
tagged with: python
has comment: http://stackoverflow.com/comment/85723685
has comment: http://stackoverflow.com/comment/85735322
has comment: http://stackoverflow.com/comment/85932653
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/85726556
has body: I encountered a similar problem as dicussed in here: Firebird embedded installation issue: library could not be determined I'm running a python(3.5.2) script via ubuntu (16.04.4 LTS) which is connected to a firebird database. For installing firebird I followed the instructions provided in here: https://firebirdsql.org/manual/ubusetup.html Now, when I run the python code the following error is displayed: Soft limit starts as :-1 Soft limit changed to :1024 Traceback (most recent call last): File "clustering_setup.py", line 30, in &lt;module&gt; graph, posi_knoten, kanten_bewertung, auslassliste = build_netzwerk.create_graph() File "/home/ubuntu/Documents/Code/build_netzwerk.py", line 113, in create_graph datenbank_custom.start(config.idbf_file) File "/home/ubuntu/Documents/Code/datenbank_custom.py", line 19, in start con = fdb.connect(database=idbf_file, user='sysdba', password='pass') File "/home/ubuntu/.local/lib/python3.5/site-packages/fdb/fbcore.py", line 682, in connect load_api(fb_library_name) File "/home/ubuntu/.local/lib/python3.5/site-packages/fdb/fbcore.py", line 181, in load_api setattr(sys.modules[__name__],'api',fbclient_API(fb_library_name)) File "/home/ubuntu/.local/lib/python3.5/site-packages/fdb/ibase.py", line 1398, in __init__ raise Exception("The location of Firebird Client Library could not be determined.") Exception: The location of Firebird Client Library could not be determined. if I examine where the files are located this is what is shown to me: ubuntu@ubuntu:~$ dpkg -L firebird2.5-classic-common /. /usr /usr/share /usr/share/lintian /usr/share/lintian/overrides /usr/share/lintian/overrides/firebird2.5-classic-common /usr/share/doc /usr/bin /usr/bin/qli /usr/bin/nbackup /usr/bin/fbstat /usr/bin/fbtracemgr /usr/bin/gdef /usr/bin/gsec /usr/bin/isql-fb /usr/bin/gpre /usr/bin/gbak /usr/bin/fbsvcmgr /usr/bin/gfix /usr/lib /usr/lib/firebird /usr/lib/firebird/2.5 /usr/lib/firebird/2.5/UDF /usr/lib/firebird/2.5/UDF/ib_udf.so /usr/lib/firebird/2.5/U…
favorite count: 0
has answer: http://stackoverflow.com/a/77441525
has comment: http://stackoverflow.com/comment/85731529
tagged with: linux
has comment: http://stackoverflow.com/comment/85765067
has comment: http://stackoverflow.com/comment/85734556
tagged with: client-library
has answer: http://stackoverflow.com/a/49364963
has comment: http://stackoverflow.com/comment/85932674
has comment: http://stackoverflow.com/comment/85723839
has comment: http://stackoverflow.com/comment/85742474
upvote count: 6
linked to: http://stackoverflow.com/q/48035341
has comment: http://stackoverflow.com/comment/85934240
has comment: http://stackoverflow.com/comment/85732387
has title: "The location of Firebird Client Library could not be determined."
type: Question
answer count: 2
tagged with: firebird
has comment: http://stackoverflow.com/comment/85742824
has comment: http://stackoverflow.com/comment/85722758

http://stackoverflow.com/comment/85784145
comment on: http://stackoverflow.com/q/49391213
type: QuestionComment
has text: Can you please put your code into a proper code block? It is really hard to read this way. On a side note, you should remove `plik.close()` and `plik1.close()`, since your `with`-statements already take care of that.
score: 0
type: Comment

http://stackoverflow.com/q/49399892
tagged with: python
has comment: http://stackoverflow.com/comment/85805639
has body: Example: import cProfile, random, copy def foo(lIn): return [i*i for i in lIn] lIn = [random.random() for i in range(1000000)] lIn1 = copy.copy(lIn) lIn2 = sorted(lIn1) cProfile.run('foo(lIn)') cProfile.run('foo(lIn2)') Result: 3 function calls in 0.075 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.005 0.005 0.075 0.075 :1() 1 0.070 0.070 0.070 0.070 test.py:716(foo) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 3 function calls in 0.143 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.006 0.006 0.143 0.143 :1() 1 0.137 0.137 0.137 0.137 test.py:716(foo) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
score: 2
has title: why python process a sorted list cost more time than a unsorted list
has comment: http://stackoverflow.com/comment/85801756
has comment: http://stackoverflow.com/comment/85807784
answer count: 1
linked to: http://stackoverflow.com/q/42107442
has answer: http://stackoverflow.com/a/49402908
favorite count: 0
has comment: http://stackoverflow.com/comment/85805107
type: Question
has comment: http://stackoverflow.com/comment/85806371
has comment: http://stackoverflow.com/comment/85811254
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85807003
downvote count: 0

http://stackoverflow.com/comment/85812565
has text: you will need `pd.set_option('display.max_colwidth',-1)' if data vary enough, but thanks, this is easier to look
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49405833
score: 1

http://stackoverflow.com/q/49420864
tagged with: python
tagged with: paramiko
linked to: http://stackoverflow.com/q/31964108
accepted answer: http://stackoverflow.com/a/49424057
has body: On Linux Machine A, i have a script running which is supposed to ssh into Linux Machine B, sync the p4 workspace on B and then execute a piece of code. I've set up Perforce on B and I'm able to manually execute p4 client and other commands on B and they work. However, when i attempt to do the same thing while sshing from Machine A, i get the following error: Perforce client error: Connect to server failed; check $P4PORT. TCP connect to perforce:1666 failed. Temporary failure in name resolution Here's my piece of code: def ssh_connect(ip,user,pwd): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=user, password=pwd) return ssh def execute_command(device_details, command): try: ip = device_details.get('ip') username = device_details.get('username') password = device_details.get('password') ssh_ns_obj = ssh_connect(ip, username, password) ssh_stdin, ssh_stdout, ssh_stderr = ssh_ns_obj.exec_command(command) print ssh_stdout.read() print ssh_stderr.read() print ssh_stdin.read() return ssh_stdout.read() except Exception as e: print_exception_details() perforce_sync_command = "cd /root/hello/;chmod -R 444 *;p4 sync ...;chmod -R 755 *" output = execute_command(device_details, perforce_sync_command) What am i missing?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49424057
has title: Python: Perforce client error while remotely executing command
answer count: 1
tagged with: ssh
duplicate of: http://stackoverflow.com/q/31964108
type: Question
tagged with: perforce

http://stackoverflow.com/q/49374951
has answer: http://stackoverflow.com/a/49375485
has body: I am having some issues setting up django-crontab in my django project. I have followed the instructions given on the official documentation :- https://pypi.python.org/pypi/django-crontab I have defined my cron.py under an app named ciscoaci. So its location is project/ciscoaci(which is the app)/cron.py. Inside cron.py, is a function named sshpostGetMACIP_scheduler(). I have defined 'django_crontab' under my settings.py in INSTALLED_APPS. CRONTAB_COMMAND_SUFFIX = '2&gt;&amp;1' CRONJOBS = [ ('*/1 * * * *', 'ciscoaci.cron.sshpostGetMACIP_scheduler', '&gt;&gt; /axphome/xxx/netadc/ciscoaci/tmp/scheduled_job.log'), ] Nothing shows up in my logs. I have also tried changing /axphome/xxx/netadc/ciscoaci/tmp/scheduled_job.log to ciscoaci/tmp/scheduled_job.log and it doesn't work. Also when I do crontab -l, the cron shows up. */1 * * * * /root/.venvs/netadc/bin/python /home/xxx/netadc/manage.py crontab run 4a2a96ea204eb26917961a9946493f0d &gt;&gt; /axphome/xxxx/netadc/ciscoaci/tmp/scheduled_job.log 2&gt;&amp;1 # django-cronjobs for netadc But nothing shows up in my logs. Any help would be appreciated. I do not want to use celery at this point as this is used for a temporary feature in my project.
has answer: http://stackoverflow.com/a/57883510
has title: Issue setting up django-crontab
type: Question
tagged with: django-cron
tagged with: cron
tagged with: python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49392412
answer count: 3
tagged with: django
tagged with: scheduler

http://stackoverflow.com/q/49384685
has comment: http://stackoverflow.com/comment/86390099
has comment: http://stackoverflow.com/comment/86343976
accepted answer: http://stackoverflow.com/a/49689432
type: Question
has answer: http://stackoverflow.com/a/49689432
has title: Python Looping over an argument in a function
linked to: http://stackoverflow.com/q/9152431
tagged with: python
tagged with: xero-api
type: AnsweredQuestion
score: 0
tagged with: function
has body: I am being a noob trying to loop over a function from pyxero: invoices = xero.invoices.filter(page = 1) The above call returns a list of dictionaries which becomes blank when there are no more pages left: [] . So the iteration would stop when the count of elements in the current list/page would become 0. I am trying to loop and create one big list that contains the elements from page 1 and 2 etc appended Thanks!
answer count: 1
tagged with: loops

http://stackoverflow.com/a/49324971
has body: The problem is mainly caused because you only have to have a QApplication, so when you create another one you get that unexpected behavior. In addition, that task ends quickly so when a dialog is a local variable is deleted and therefore the window is also closed, so that it does not happen you must make a dialog member of the class. def accept(self): if self.user_name.text() == "123" and self.password.text() == "123": self.dialog = QDialog() ui = Ui_Dialog() ui.setupUi(self.dialog) self.dialog.show() else: print("wrong imformation")
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85663954
accepted answer of: http://stackoverflow.com/q/49323961
has comment: http://stackoverflow.com/comment/85664042
answers question: http://stackoverflow.com/q/49323961
score: 0
has comment: http://stackoverflow.com/comment/85665891
has comment: http://stackoverflow.com/comment/85663929
type: Answer

http://stackoverflow.com/comment/85780073
type: QuestionComment
has text: @Rafael I wrote it in question: `from tools import my_strings`
score: 0
comment on: http://stackoverflow.com/q/49389107
type: Comment

http://stackoverflow.com/comment/85942950
comment on: http://stackoverflow.com/a/49452712
type: Comment
score: 0
type: AnswerComment
has text: Yes, it is possible to set a current schema with a session pool. Be aware that it will be retained when you return the connection to the pool.

http://stackoverflow.com/q/49344445
accepted answer: http://stackoverflow.com/a/49356817
has answer: http://stackoverflow.com/a/49356817
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49349662
has title: Child window failed to trigger mouse event in PyQt5
tagged with: pyqt5
type: Question
has body: I want to capture mouse events for the child window,but the problem is Mouse events are not passed to this child window.... After finding information on the Internet, I found that I need to customize the button.But I still did not get any respond after doing this. Can anyone tell me what else I need to do to capture mouse events inside this Child window? Here is my code: from PyQt5 import QtCore,QtWidgets from PyQt5.QtWidgets import * import sys class My_top_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 532) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.Products = MyButton() self.verticalLayout.addWidget(self.Products) self.Products.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.Products.setText(_translate("Dialog", "top window")) def accept(self): self.dialog = QDialog() ui = My_second_Dialog() ui.setupUi(self.dialog) self.dialog.show() class My_second_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 480) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.fetch = MyButton() self.verticalLayout.addWidget(self.fetch) self.fetch.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.fetch.setText(_translate("Dialog", "second window")) def accept(self): QMessageBox.information(self, "success", "success.") class MyButton(QPushButton): def __init__(self, parent=None): super(MyButton, self).__init__(parent) self.setFixedSize(111, 111) def mousePressEvent(self, QMouseEvent): if QMouseEvent.button() == QtCore.Qt.LeftButton: self.clicked.emit(True) self.parent().mousePressEvent(QMouseEvent) if __name__ == '__main__': app = QApplication(sys.argv) dialog = QDialog() ui = My_top_Dialog() ui.setupUi(dialog…
answer count: 2
possible better answer: http://stackoverflow.com/a/49349662
tagged with: python

http://stackoverflow.com/comment/85786838
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49392595
has text: flask_cors is your answer .... keep chasing that

http://stackoverflow.com/q/49388700
tagged with: django
has title: Change GET to POST request in 'sort' of tables2
answer count: 1
has body: I need to have a sorting request back to my template page in the POST request form, but the sort of the column provide by django-tables2 give a GET request form like that : http://127.0.0.1:8000/mypage?sort=mycolumn mytemplate.html {% csrf_token %} #somes buttons and filters {% load django_tables2 %} {% render_table table %} How transform this 'sort' in POST request instead of the GET request ? Thanks in advance.
has answer: http://stackoverflow.com/a/49402760
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: django-tables2
tagged with: python-3.x
score: 0

http://stackoverflow.com/a/49408792
has comment: http://stackoverflow.com/comment/85821460
has body: You can use mask for check midnight and add one day: f['Date'] = pd.to_datetime(f['Date']) m = f['Hour'] == '00:00' f['Date'] = f['Date'].mask(m, f['Date'] + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y') Solution with loc: m = f['Hour'] == '00:00' dates = pd.to_datetime(f['Date']) f.loc[m, 'Date'] = (dates + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y') #alternative #f.loc[m, 'Date'] = (dates[m] + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y') Solution with numpy.where: m = f['Hour'] == '00:00' dates = (pd.to_datetime(f['Date']) + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y') f['Date'] = np.where(m, dates, f['Date']) print (f) Date Hour 0 19/06/2016 23:30 1 19/06/2016 23:45 2 20/06/2016 00:00 3 20/06/2016 00:15 4 20/06/2016 00:30 Within Code: for fname in glob.glob(path): fname = fname.replace(r'\2016', '/2016') f = pd.DataFrame(pd.read_csv(fname)) f = f.replace({'Hour': {'24:00:00': '00:00'}}) f['Date'] = pd.to_datetime(f['Date']).dt.strftime('%d/%m/%Y') f['Hour'] = pd.to_datetime(f['Hour']).dt.strftime('%H:%M') m = f['Hour'] == '00:00' dates = (pd.to_datetime(f['Date']) + pd.Timedelta(1, unit='d')).dt.strftime('%d/%m/%Y') f['Date'] = np.where(m, dates, f['Date']) print(fname) if a == 0: f_2016['Date'] = f['Date'] f_2016['Hour'] = f['Hour'] a = 1 f_2016 = pd.merge(f_2016, f, on=['Date', 'Hour']) print(pd.DataFrame.head(f_2016, n=100))
score: 1
has comment: http://stackoverflow.com/comment/85820192
type: Answer
has comment: http://stackoverflow.com/comment/85819871
has comment: http://stackoverflow.com/comment/85820483
has comment: http://stackoverflow.com/comment/85819838
has comment: http://stackoverflow.com/comment/85821691
has comment: http://stackoverflow.com/comment/85820134
answers question: http://stackoverflow.com/q/49408660
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85820001
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49408660

http://stackoverflow.com/q/49319760
tagged with: python-2.7
tagged with: nao-robot
type: UnansweredQuestion
answer count: 1
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/85763431
has comment: http://stackoverflow.com/comment/85900025
has comment: http://stackoverflow.com/comment/85640406
has comment: http://stackoverflow.com/comment/85808762
score: 0
has body: import naoqi Traceback (most recent call last): File "", line 1, in File "/home/pi/Downloads/pynaoqi-python2.7-2.1.4.13-linux32/naoqi.py", line 7, in import qi File "/home/pi/Downloads/pynaoqi-python2.7-2.1.4.13-linux32/qi/init.py", line 72, in from _qi import Application as _Application ImportError: /home/pi/Downloads/pynaoqi-python2.7-2.1.4.13-linux32/_qi.so: cannot open shared object file: No such file or directory I tried all the things below export DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:/home/pi/Downloads/pynaoqi-python2.7-2.1.4.13-linux32/ export PYTHONPATH=${PYTHONPATH}:/home/pi/Downloads/pynaoqi-python2.7-2.1.4.13-linux32/ sudo ldconfig -v too nothing works
has comment: http://stackoverflow.com/comment/85716961
has title: Naoqi python SDK error in raspberry pi during installation
has comment: http://stackoverflow.com/comment/85762661
has answer: http://stackoverflow.com/a/50343993
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85762189
has comment: http://stackoverflow.com/comment/85808791

http://stackoverflow.com/q/49381367
accepted answer: http://stackoverflow.com/a/57396208
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/57396208
has title: Django customise Default Group model
favorite count: 0
type: Question
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I m fairly new to Django and I want customise Django's default Group model with my own requirements, Default django's Group model look like this: class Group(models.Model): name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) I want to add a new field and make name field and that new field as one composite primary key. Is there anyway this could be done? Any suggestions would be appreciated. Thanks
score: 1
tagged with: models
answer count: 1

http://stackoverflow.com/comment/85629117
type: QuestionComment
comment on: http://stackoverflow.com/q/49313692
type: Comment
has text: Yes, it does. He provided a minimal test case.
score: 0

http://stackoverflow.com/a/49290277
downvote count: 0
answers question: http://stackoverflow.com/q/49290238
type: Answer
upvote count: 1
has body: You can just filter your result accordingly: grp = grp[grp['count'] &gt;= 30] Example with data import pandas as pd df = pd.DataFrame({'code': [1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3], 'note': ['A', 'B', 'A', 'A', 'C', 'C', 'C', 'A', 'A', 'B', 'B', 'C', 'A', 'B'] }) res = df.groupby('code')['note'].agg(['count', 'first']).sort_values('count', ascending=False) # count first # code # 2 5 C # 3 5 B # 1 4 A res2 = res[res['count'] &gt;= 5] # count first # code # 2 5 C # 3 5 B
score: 1

http://stackoverflow.com/q/49384368
accepted answer: http://stackoverflow.com/a/49384463
has comment: http://stackoverflow.com/comment/85769993
tagged with: if-statement
score: -2
possible better answer: http://stackoverflow.com/a/49384390
tagged with: python
has answer: http://stackoverflow.com/a/49384390
has comment: http://stackoverflow.com/comment/85770323
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/49384392
duplicate of: http://stackoverflow.com/q/15112125
tagged with: loops
has title: Trying to append List/array based on condition
has body: I'm trying to add to an array based on a condition. Can someone clarify why the if statement isn't working as I intend it to? all_staff = ["Judith", "Harry", "Jonathan", "Reuben"] new_staff = [] def person_finder(staff): for x in staff: if x == "Reuben" or "Harry" or "Jonathan": new_staff.append(x) else: continue return new_staff selected = person_finder(all_staff) def the_men(people): for x in people: print(x + " is a man") the_men(selected) This returns: Judith is a man
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49384463

http://stackoverflow.com/comment/85836895
score: 0
has text: @AndreiCioara With the current code, the turtle will move randomly until it hits a wall. After that the loop stops and when I click the window it closes. I'm trying so that when it hits a wall it bounces in a random direction and continues on until forcibly closed.
comment on: http://stackoverflow.com/q/49417524
type: Comment
type: QuestionComment

avro
type: Tag
tags question: http://stackoverflow.com/q/49332239
tags question: http://stackoverflow.com/q/49396727
tags question: http://stackoverflow.com/q/49286955
tag name: avro

http://stackoverflow.com/comment/85754686
has text: if you don't mind telling me how were you able to figure out validators required a list, and my passing a tuple was bug? Thanks a lot.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49376921
type: Comment

http://stackoverflow.com/q/49332935
accepted answer: http://stackoverflow.com/a/49333709
has title: How to click randomly with a randomly selected page
has body: I want to click an add to cart button in an ecommerce website, my problem is every item has a different button id. and i notice that the id is located in the div. i try to select a wild card since every item has a different id. addcart = driver.find_elements_by_css_selector("div[id*=\"addtocart-\"]") addcart.click() here is the sample code, i want to click the addtocart-49831, how can i click that button?
has answer: http://stackoverflow.com/a/49333709
tagged with: python
tagged with: wildcard
possible better answer: http://stackoverflow.com/a/49333109
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85667988
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49333109
has comment: http://stackoverflow.com/comment/85667745
tagged with: selenium
has comment: http://stackoverflow.com/comment/85685958
type: Question
tagged with: testing
tagged with: automation

http://stackoverflow.com/comment/85583796
type: Comment
score: 0
type: QuestionComment
has text: What is your desired output from the data in your question?
comment on: http://stackoverflow.com/q/49290338

http://stackoverflow.com/q/49310278
tagged with: format
has comment: http://stackoverflow.com/comment/85622743
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85622915
tagged with: twitter
score: -1
has title: How do I make a correct JSON file format from this tweepy-script?
has comment: http://stackoverflow.com/comment/85623940
has comment: http://stackoverflow.com/comment/85622635
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85622831
has comment: http://stackoverflow.com/comment/85622578
upvote count: 0
has body: I'm trying to get a JSON format of a search query using Tweepy but there's a problem: my final JSON file is in a unreadable format for any program, after checking the file, it seems like the script writes all the data without any correct spacing (for a JSON format) So, I've been trying to look for the problem but I really can't find any with the script. Does anyone have an idea of what could be wrong with the writing part? This is the script: def write_tweets(tweets, filename): ''' Function that appends tweets to a file. ''' with open(filename, 'a') as f: for tweet in tweets: json.dump([tweet._json], f) f.write('\n') . . . . for search_phrase in search_phrases: print('Search phrase =', search_phrase) ''' other variables ''' name = search_phrase.split()[0] json_file_root = name + '/' + name os.makedirs(os.path.dirname(json_file_root), exist_ok=True) read_IDs = False # open a file in which to store the tweets if max_days_old - min_days_old == 1: d = dt.datetime.now() - dt.timedelta(days=min_days_old) day = '{0}-{1:0&gt;2}-{2:0&gt;2}'.format(d.year, d.month, d.day) else: d1 = dt.datetime.now() - dt.timedelta(days=max_days_old-1) d2 = dt.datetime.now() - dt.timedelta(days=min_days_old) day = '{0}-{1:0&gt;2}-{2:0&gt;2}_to_{3}-{4:0&gt;2}-{5:0&gt;2}'.format( d1.year, d1.month, d1.day, d2.year, d2.month, d2.day) json_file = json_file_root + '_' + day + '.json' if os.path.isfile(json_file): print('Appending tweets to file named: ',json_file) read_IDs = True # authorize and load the twitter API api = load_api() # set the 'starting point' ID for tweet collection if read_IDs: # open the json file and get the latest tweet ID with open(json_file, 'r') as f: lines = f.readlines() max_id = json.loads(lines[-1])['id'] print('Searching from the bottom ID in file') else: # get the ID of a tweet that is min_days_old if min_days_old == 0: max_id = -1 else: max_id = get_tweet_id(api, days_ago=(min_days_old-1)) # set the smallest ID to search for since_id = get_tweet_id(api, days_ago=(max…
accepted answer: http://stackoverflow.com/a/49310543
has comment: http://stackoverflow.com/comment/85622826
answer count: 1
has comment: http://stackoverflow.com/comment/85622797
tagged with: python
has comment: http://stackoverflow.com/comment/85622858
tagged with: tweepy
has answer: http://stackoverflow.com/a/49310543
downvote count: 1
has comment: http://stackoverflow.com/comment/85622731
type: AnsweredQuestion

http://stackoverflow.com/q/49322733
has comment: http://stackoverflow.com/comment/85646716
type: AnsweredQuestion
score: 0
has title: How to define a variable when we defined it in a while loop?
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85646907
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49322825
has body: G = float(6.67 * (10**-11)) print("Choose from the following '\n a) Gravitational Force '\n b) Density '\n c) Kinetic Energy '\n d) Potential Energy '\n e) Work Done '\n f) Weight '\n g) Force ") Answer = input("Choice: ") while Answer == 'a': M1 = float(input("Enter mass of first body: ")) M2 = float(input("Enter mass of second body: ")) r = float(input("Enter distance between them: ")) break while Answer == 'b': vol = float(input("Enter volume of the object: ")) m = float(input("Enter mass of the body: ")) break while Answer == 'c': m1 = float(input("Enter mass of the body: ")) v = float(input("Enter velocity of the body: ")) break while Answer == 'd': g = float(input("Enter value of acceleration due to gravity: ")) m2 = float(input("Enter mass of the body: ")) h = float(input("Enter height of the object: ")) break while Answer == 'e': f = float(input("Enter vaue of force applied: ")) s = float(input("Enter value of displacement: ")) break while Answer =='f': g1 = float(input("Enter value of acceleration due to gravity: ")) m3 = float(input("Enter mass of the body: ")) break while Answer == 'g': m4 = float(input("Enter mass of the body: ")) acc = float(input("Enter value of acceleration: ")) break D = m/vol W = m3*g1 F = m4*acc GF = (G * M1*M2)/r**2 WD = f*s KE = (1/2 * m1 * v**2) PE = m2*g*h if Answer == 'a': print(GF) elif Answer == 'b': print(D) elif Answer == 'c': print(KE) elif Answer == 'd': print(PE) elif Answer == 'e': print(WD) elif Answer == 'f': print(W) elif Answer == 'g': print(F) Now I want to know that while running the code, it keeps saying variable not declared and it says that in the formulas the variable I am using are not defined but I already defined them in while loop, I want to bring only certain inputs when the user chooses a certain calculation. Please help! What are things I am doing wrong? please help Thanks
has answer: http://stackoverflow.com/a/49322825
tagged with: coding-style

http://stackoverflow.com/q/49382244
tagged with: python
type: UnansweredQuestion
tagged with: python-2.7
has title: Using readlines() to write a template txt file to 'x' new files
score: 0
has answer: http://stackoverflow.com/a/49382497
has answer: http://stackoverflow.com/a/49382661
has body: I have a template txt file. This template needs to be written as 10 new files where I can then make amendments to each file based on certain conditions (not relevant to the question). I read my template file as follows: with open('template.txt', 'r') as template_file: file_lines = template_file.readlines() file_lines = [line.rstrip('\n') for line in file_lines] for i in range(10): new_file = open('output_%s' % i, 'w') new_file.write(file_lines) new_file.close() It won't work as I cannot write a list to each file, it must be a string, but I don't know how to get every element from that list to be written in the same file 10 times...Each time I try it a different way I end up getting each line on different files, rather than all lines in all files. Something wrong in my logic I cannot work out. Another way I can do it as : template_file = open('template.txt', 'r') template_lines = template_file.read() for i in range(10): new_files = open('output_%s' % i, 'w') new_files.write(template_lines) But I want to be able amendment particular lines which makes it more convenient to write into each new file line by line (via readlines())
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49382573
has answer: http://stackoverflow.com/a/49382594
answer count: 4
type: Question

http://stackoverflow.com/comment/85851945
score: 0
comment on: http://stackoverflow.com/q/49423186
type: Comment
type: QuestionComment
has text: Sorry, you are right ofc. Lets say freq = 3H. I edited my post. So in the Sales_in_TF column it says: 2 Apples have been sold in store 1 within 3 hours. Same goes for Bananas in store 2, etc

http://stackoverflow.com/q/49354615
possible better answer: http://stackoverflow.com/a/49356666
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/85709665
type: AnsweredQuestion
score: 0
has body: how can I get these loops and if statements into a comprehension? raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']] for one in raw: if one[0] == '-': for two in raw: if two[1] == one[1] and two[0] == '=': two[0] = '--' So far: [two+one for two in raw for one in raw] But not sure where to put the if statements: if one[0] == '-' and if two[1] == one[1] and two[0] == '=': two[0] = '--'
answer count: 2
has title: Modifying lists within lists via list comprehension
has comment: http://stackoverflow.com/comment/85709755
has answer: http://stackoverflow.com/a/49354708
accepted answer: http://stackoverflow.com/a/49354708
type: Question
tagged with: python-3.x
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/85709594
tagged with: python
has answer: http://stackoverflow.com/a/49356666

http://stackoverflow.com/comment/85776920
comment on: http://stackoverflow.com/q/49387425
score: 0
has text: for example: first random number 0.0199999999999 so i need select row with 0.024732 value of sum. And the same for next 4999 generated random numbers
type: Comment
type: QuestionComment

string
tags question: http://stackoverflow.com/q/49366169
tags question: http://stackoverflow.com/q/49364531
tags question: http://stackoverflow.com/q/49427151
tags question: http://stackoverflow.com/q/49320891
type: Tag
tags question: http://stackoverflow.com/q/49386824
tags question: http://stackoverflow.com/q/49287528
tags question: http://stackoverflow.com/q/49397609
tags question: http://stackoverflow.com/q/49355224
tags question: http://stackoverflow.com/q/49286358
tags question: http://stackoverflow.com/q/49425715
tags question: http://stackoverflow.com/q/49330438
tags question: http://stackoverflow.com/q/49329046
tags question: http://stackoverflow.com/q/49381154
tags question: http://stackoverflow.com/q/49419104
tags question: http://stackoverflow.com/q/49318538
tags question: http://stackoverflow.com/q/49357413
tags question: http://stackoverflow.com/q/49418929
tags question: http://stackoverflow.com/q/49407129
tags question: http://stackoverflow.com/q/49433107
tags question: http://stackoverflow.com/q/49402113
tags question: http://stackoverflow.com/q/49434120
tags question: http://stackoverflow.com/q/49354977
tags question: http://stackoverflow.com/q/49411263
tags question: http://stackoverflow.com/q/49315829
tags question: http://stackoverflow.com/q/49344577
tags question: http://stackoverflow.com/q/49310989
tags question: http://stackoverflow.com/q/49373835
tags question: http://stackoverflow.com/q/49371343
tags question: http://stackoverflow.com/q/49390948
tags question: http://stackoverflow.com/q/49372306
tags question: http://stackoverflow.com/q/49348530
tags question: http://stackoverflow.com/q/49386034
tags question: http://stackoverflow.com/q/49413005
tags question: http://stackoverflow.com/q/49371667
tags question: http://stackoverflow.com/q/49314033
tags question: http://stackoverflow.com/q/49408938
tags question: http://stackoverflow.com/q/49312298
tags question: http://stackoverflow.com/q/49344301
tags question: http://stackoverflow.com/q/49371629
tags question: http://stackoverflow.com/q/49289969
tags question: http://stackoverflow.com/q/49396526
tags question: http://stackoverflow.com/q/49395064
tags question: http://stackoverflow.com/q/49374120
tags question: http://stackoverflow.com/q/49434055
tags question: http://stackoverflow.com/q/49352985
tags question: http://stackoverflow.com/q/49364664
tags question: http://stackoverflow.com/q/49395363
tags question: http://stackoverflow.com/q/49417023
tags question: http://stackoverflow.com/q/49418627
tags question: http://stackoverflow.com/q/49308068
tags question: http://stackoverflow.com/q/49354400
tags question: http://stackoverflow.com/q/49426254
tags question: http://stackoverflow.com/q/49309574
tags question: http://stackoverflow.com/q/49366378
tags question: http://stackoverflow.com/q/49351326
tags question: http://stackoverflow.com/q/49339291
tags question: http://stackoverflow.com/q/49326487
tags question: http://stackoverflow.com/q/49382217
tags question: http://stackoverflow.com/q/49389292
tags question: http://stackoverflow.com/q/49321247
tags question: http://stackoverflow.com/q/49370459
tag name: string
tags question: http://stackoverflow.com/q/49374773
tags question: http://stackoverflow.com/q/49414271
tags question: http://stackoverflow.com/q/49280700
tags question: http://stackoverflow.com/q/49300686
tags question: http://stackoverflow.com/q/49344683
tags question: http://stackoverflow.com/q/49413515
tags question: http://stackoverflow.com/q/49379301
tags question: http://stackoverflow.com/q/49422899
tags question: http://stackoverflow.com/q/49358590
tags question: http://stackoverflow.com/q/49393269
tags question: http://stackoverflow.com/q/49410786
tags question: http://stackoverflow.com/q/49281051
tags question: http://stackoverflow.com/q/49320238
tags question: http://stackoverflow.com/q/49354949
tags question: http://stackoverflow.com/q/49293803

http://stackoverflow.com/comment/85811489
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49405208
has text: Possible duplicate of [Negative list index?](https://stackoverflow.com/questions/11367902/negative-list-index)
score: 1

http://stackoverflow.com/comment/85666951
score: 0
has text: @Bob That means your text file has one column. For that you can use. `data.columns = ["a"]`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49327053

http://stackoverflow.com/a/49456044
answers question: http://stackoverflow.com/q/49411333
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85923874
has comment: http://stackoverflow.com/comment/85935146
has comment: http://stackoverflow.com/comment/85923894
has body: input_shape=(None, x_train.shape[1], 1), where None is the batch size, x_train.shape[1] is the length of each sequence of features, and 1 is each feature length. (Not sure if batch size is necessary for Sequential model). And then reshape your data into x_train = x_train.reshape(-1, x_train.shape[1], 1).
downvote count: 0

http://stackoverflow.com/q/49312139
has answer: http://stackoverflow.com/a/49312184
tagged with: python
accepted answer: http://stackoverflow.com/a/49312184
has title: Is there a way to do the same thing in tensorflow as it's done below in numpy?
type: AnsweredQuestion
score: 0
answer count: 2
has body: By using numpy, I could index an array as below x[mask==1] Assuming x and mask are both numpy array and mask contains only 1 and 0. Now I have both x and mask as Tensors and want to mimic above behavior. What should I do?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49312191
possible better answer: http://stackoverflow.com/a/49312191
linked to: http://stackoverflow.com/q/48978984

http://stackoverflow.com/q/49361068
tagged with: python
has comment: http://stackoverflow.com/comment/85722328
has comment: http://stackoverflow.com/comment/85724620
linked to: http://stackoverflow.com/q/10756427
upvote count: 2
score: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49364500
tagged with: http://stackoverflow.com/tag/json
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/6027558
has title: pandas: convert nested json to flattened table
type: UnansweredQuestion
has body: I have a JSON of the following structure: { "a": "a_1", "b": "b_1", "c": [{ "d": "d_1", "e": "e_1", "f": [], "g": "g_1", "h": "h_1" }, { "d": "d_2", "e": "e_2", "f": [], "g": "g_2", "h": "h_2" }, { "d": "d_3", "e": "e_3", "f": [{ "i": "i_1", "j": "j_1", "k": "k_1", "l": "l_1", "m": [] }, { "i": "i_2", "j": "j_2", "k": "k_2", "l": "l_2", "m": [{ "n": "n_1", "o": "o_1", "p": "p_1", "q": "q_1" }] }], "g": "g_3", "h": "h_3" }] } And I want to convert it into pandas data frame of the following type: How can I achieve that? Following is my attempt but the direction is completely diff. code: from pandas.io.json import json_normalize def flatten_json(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out sample_object = { "a": "a_1", "b": "b_1", "c": [{ "d": "d_1", "e": "e_1", "f": [], "g": "g_1", "h": "h_1" }, { "d": "d_2", "e": "e_2", "f": [], "g": "g_2", "h": "h_2" }, { "d": "d_3", "e": "e_3", "f": [{ "i": "i_1", "j": "j_1", "k": "k_1", "l": "l_1", "m": [] }, { "i": "i_2", "j": "j_2", "k": "k_2", "l": "l_2", "m": [{ "n": "n_1", "o": "o_1", "p": "p_1", "q": "q_1" }] }], "g": "g_3", "h": "h_3" }] } intermediate_json = flatten_json(sample_object) flattened_df = json_normalize(intermediate_json) transposed_df = flattened_df.T print(transposed_df.to_string()) OUTPUT: 0 a a_1 b b_1 c_0_d d_1 c_0_e e_1 c_0_g g_1 c_0_h h_1 c_1_d d_2 c_1_e e_2 c_1_g g_2 c_1_h h_2 c_2_d d_3 c_2_e e_3 c_2_f_0_i i_1 c_2_f_0_j j_1 c_2_f_0_k k_1 c_2_f_0_l l_1 c_2_f_1_i i_2 c_2_f_1_j j_2 c_2_f_1_k k_2 c_2_f_1_l l_2 c_2_f_1_m_0_n n_1 c_2_f_1_m_0_o o_1 c_2_f_1_m_0_p p_1 c_2_f_1_m_0_q q_1 c_2_g g_3 c_2_h h_3
tagged with: dataframe

http://stackoverflow.com/comment/85765713
type: Comment
type: QuestionComment
has text: I added this alternative approach to my original question.
comment on: http://stackoverflow.com/q/49378987
score: 0

http://stackoverflow.com/q/49426565
tagged with: multiprocessing
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I'm trying to write script using subprocess workers to download many files at once. Whole process would look somewhat like that: Manager Process ├ Worker ├ Worker ├ Worker └ Worker I've achieved something like that using multiprocessing.JoinableQueue with links to files created in Manager Process, while workers were get()ing files urls from it. Whole process was runnig untill Queue was empty, but there was no way to for example pause downloading. Now I'm trying to create async communication between Parent and Child processes so I could do somethin like that: Worker » Manager: "Give me new link" Manager » Worker: Gives new link (Worker starts downloading) or: Worker » Manager: "Give me new link" Manager » Worker: "Wait for now" (Worker is waiting) Manager » Worker: "I've got new job for you" (Worker starts downloading) Add to that more workers and we have: Worker1 » Manager: "Give me new link" Worker2 » Manager: "Give me new link" Manager » Worker1: Gives new link (Worker1 starts downloading) Manager » Worker2: Gives new link (Worker2 starts downloading) Unfortunetly I don't know how to achieve such communication and I'd like to use pure multiprocessing without external packages so I could easly use my script on other machines. Thanks in advance! Edit: The real problem is: I'm looking for effective way of communicating between processes. If one process receives msgs from many processes, it needs to infinitely loop over every connection to check if there is msg pending. Is there a way for process to wait/freeze for msg from any of child processes?
has comment: http://stackoverflow.com/comment/85856219
tagged with: python
has comment: http://stackoverflow.com/comment/85855665
has comment: http://stackoverflow.com/comment/85854496
has comment: http://stackoverflow.com/comment/85855556
has title: Python multiprocessing - Asynchronous communication between Parent and many Child processes
has comment: http://stackoverflow.com/comment/85857545
has comment: http://stackoverflow.com/comment/85855465
answer count: 0
has comment: http://stackoverflow.com/comment/85922358
has comment: http://stackoverflow.com/comment/85855142
score: 0
has comment: http://stackoverflow.com/comment/85855802
has comment: http://stackoverflow.com/comment/85854288

http://stackoverflow.com/comment/85569342
type: Comment
type: AnswerComment
has text: I edited the title, added some extra text and improved the example
score: 1
comment on: http://stackoverflow.com/a/49281770

http://stackoverflow.com/a/49412157
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49411932
type: Answer
has body: Simplest solution: format your references list before printing, ie # print(references) print("\n".join(references)) or print them one by one (might be a bit longer but well): # print(references) for ref in references: print(ref) and then use your OS redirections to redirect the output to a file (linux example): $ python yourscript.py &gt; myurls.txt
answers question: http://stackoverflow.com/q/49411932

http://stackoverflow.com/comment/85893575
score: 0
comment on: http://stackoverflow.com/a/49437123
type: Comment
has text: Sorry I don't understand what you are doing there, the range of the row and columns with non-zero elements should be 2 and 3 respectively for this array. I don't understand what the numbers 4 and 6 represent. But looking at your code I think I've figured it out now, this works yCoords,xCoords = np.nonzero(A) deltaY = np.ptp(yCoords)+1 deltaX = np.ptp(xCoords)+1
type: AnswerComment

http://stackoverflow.com/q/49359744
score: 0
answer count: 0
tagged with: installation
has comment: http://stackoverflow.com/comment/85742105
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/85719653
type: Question
has comment: http://stackoverflow.com/comment/85719576
has comment: http://stackoverflow.com/comment/85749456
has comment: http://stackoverflow.com/comment/85733915
has comment: http://stackoverflow.com/comment/85727867
tagged with: python
has body: Nothing ive tried has worked and nothing ive found online has worked, including upgrading setuptools and a couple other things as well as installing visual studio. Heres what I get back, minus some because stackoverflow doesnt like it. C:\Users\ejhsc&gt;py -m pip install pandas Collecting pandas #ifndef _NPY_NPY_CONFIG_H_ #error config.h should never be included directly, include npy_config.h instead #endif EOF _configtest.c _configtest.c(6): fatal error C1189: #error: gcc &gt;= 4 required File: build\src.win-amd64-3.7\numpy\core\include/numpy\_numpyconfig.h #define NPY_SIZEOF_SHORT SIZEOF_SHORT #define NPY_SIZEOF_INT SIZEOF_INT #define NPY_SIZEOF_LONG SIZEOF_LONG #define NPY_SIZEOF_FLOAT 4 #define NPY_SIZEOF_COMPLEX_FLOAT 8 #define NPY_SIZEOF_DOUBLE 8 #define NPY_SIZEOF_COMPLEX_DOUBLE 16 #define NPY_SIZEOF_LONGDOUBLE 8 #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 16 #define NPY_SIZEOF_PY_INTPTR_T 8 #define NPY_SIZEOF_OFF_T 4 #define NPY_SIZEOF_PY_LONG_LONG 8 #define NPY_SIZEOF_LONGLONG 8 #define NPY_NO_SIGNAL 1 #define NPY_NO_SMP 0 #define NPY_HAVE_DECL_ISNAN #define NPY_HAVE_DECL_ISINF #define NPY_HAVE_DECL_SIGNBIT #define NPY_HAVE_DECL_ISFINITE #define NPY_USE_C99_COMPLEX 1 #define NPY_RELAXED_STRIDES_CHECKING 1 #define NPY_USE_C99_FORMATS 1 #define NPY_VISIBILITY_HIDDEN #define NPY_ABI_VERSION 0x01000009 #define NPY_API_VERSION 0x0000000C #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif EOF ### Warning: Using unoptimized lapack ### ### Warning: Using unoptimized lapack ### warning: no previously-included files matching '*.pyo' found anywhere in distribution warning: no previously-included files matching '*.pyd' found anywhere in distribution warning: no previously-included files matching '*.swp' found anywhere in distribution warning: no previously-included files matching '*.bak' found anywhere in distribution warning: no previously-included files matching '*~' found anywhere in distribution C:\Users\ejhsc\AppData\Local\Programs\Python\Python37\lib\si…
has title: python pip install not working, failed with error code 1

http://stackoverflow.com/a/49438141
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49438025
has comment: http://stackoverflow.com/comment/85879051
upvote count: 2
answers question: http://stackoverflow.com/q/49438025
has comment: http://stackoverflow.com/comment/85879104
type: AcceptedAnswer
type: Answer
has body: Use: (df.groupby('Name', as_index=False) .agg({'Count':'sum','Address':lambda x: ' \n '.join(x)})) Output: Name Address Count 0 Jake XXXXXXXXX \n YYYYYYYYY \n ZZZZZZZZZ 3 1 Jon AAAAAAA \n BBBBBBBB 2

http://stackoverflow.com/a/49407162
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85889990
upvote count: 1
has body: With the risk of being obvious... You can simply plot lossHistory with matplotlib. Or am I missing something? EDIT: apparently the OP asked what the Gradient Descent (GD) is minimizing. I will try to answer here and I hope I can answer the original question. The GD algorithm is a generic algorithm to find the minimum of a function in parameter space. In your case (and that is how is usually used with Neural Networks) you want to find the minimum of a loss function: the MSE (Mean Squared Error). You implement the GD algorithm updating the weights as you did with gradient = X.T.dot(error) / X.shape[0] W += - 0.44 * gradient The gradient is just the partial derivative of your loss function (the MSE) with respect to the weights. So are effectively minimizing the loss function (MSE). Then you update your weights with a learning rate of 0.44. Then you simply save the value of your loss function in the array loss = np.sum(error ** 2) lossHistory.append(loss) and therefore the lossHistory array contains your cost (or loss) function that you can plot to check your learning process. The plot should show something decreasing. Does this explanation help you? Best, Umberto
has comment: http://stackoverflow.com/comment/85869475
has comment: http://stackoverflow.com/comment/85816815
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49394377
accepted answer of: http://stackoverflow.com/q/49394377

http://stackoverflow.com/comment/85619525
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49308645
type: Comment
has text: (and N.B. that even if `str.strip` did accept a regular expression, `[.*]` would be the character class containing the literals `.` and `*`)

http://stackoverflow.com/a/49438675
score: 2
accepted answer of: http://stackoverflow.com/q/49438246
answers question: http://stackoverflow.com/q/49438246
type: Answer
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: (1) No, the consumer is not holding a lock; it's merely blocked until the request is satisfied, but the queue is still available. If there are multiple consumers, then this one is in the pool of potential recipients; the resolution function will choose the order of satisfaction. (2) Any performance difference depends on the implementation. Don't ask us -- you have the foremost authority in front of you: your computer. Use a test scenario of your choice, and the timeit facility.

azure
tags question: http://stackoverflow.com/q/49378776
tags question: http://stackoverflow.com/q/49299103
tags question: http://stackoverflow.com/q/49292942
type: Tag
tags question: http://stackoverflow.com/q/49340998
tags question: http://stackoverflow.com/q/49410682
tags question: http://stackoverflow.com/q/49324754
tags question: http://stackoverflow.com/q/49387388
tag name: azure

http://stackoverflow.com/comment/85669980
type: QuestionComment
has text: **Why not**, you should first read the code and understand what it does.
type: Comment
comment on: http://stackoverflow.com/q/49334210
score: 0

http://stackoverflow.com/comment/85696030
type: QuestionComment
comment on: http://stackoverflow.com/q/49347310
score: 0
type: Comment
has text: AssertionError: Lists differ: ['battleaxe', 'dagger', 'dagger', 'dagger', 'gold coin'] != [] First list contains 5 additional elements. First extra element 0: 'battleaxe' - ['battleaxe', 'dagger', 'dagger', 'dagger', 'gold coin'] + []

http://stackoverflow.com/a/49413787
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49413525
has body: if you want to format the output you can use \n wherever you need the output to go to a newline. data = {'sku: ***'+sku0+'*** Size: ***'+size0+'*** Stock: ***'+stock0+'***\n' if you want to format the code I would suggest using a variables holding each line and then use + to add all of them together
score: 0
answers question: http://stackoverflow.com/q/49413525

http://stackoverflow.com/q/49370281
score: 1
has answer: http://stackoverflow.com/a/49378728
answer count: 1
has comment: http://stackoverflow.com/comment/86655904
tagged with: python
has comment: http://stackoverflow.com/comment/86655937
has title: Flask authenticate with Sharepoint Online
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: oauth-2.0
downvote count: 0
upvote count: 1
tagged with: sharepoint
has body: I am trying to write a web service which uses some data from a Sharepoint Online site using the flask_oauthlib module. I've set it up like this: from flask import Flask, session from . import settings app = Flask(__name__) app.config.from_object(settings) # To get SECRET_KEY from flask_oauthlib import OAuth oauth = OAuth(app) sharepoint = oauth.remote_app( 'sharepoint', consumer_key = '&lt;redacted&gt;', consumer_secret = '&lt;redacted&gt;', request_token_params = {'scope': 'AllSites.Manage'}, base_url = 'https://&lt;redacted&gt;.sharepoint.com/_layouts/15/OAuthAuthorize.aspx', request_token_url = None, access_token_method = 'GET', access_token_url = 'https://&lt;redacted&gt;.sharepoint.com/_layouts/15/OAuthAuthorize.aspx' ) @sharepoint.tokengetter def get_sharepoint_token(token=None): return session.get('sharepoint_token') @app.route('/') def index(): return sharepoint.authorize(callback='https://localhost:5000/login') @app.route('/login') def login(): resp = sharepoint.authorized_response() if resp is None: return 'Login failed: ' + request.args.get('error_description') session['sharepoint_token'] = ( resp['auth_token'], resp['auth_token_secret'] ) session['sharepoint_user'] = resp['screen_name'] return 'Hello, ' + resp['screen_name'] if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True, ssl_context=('server.crt', 'server.key')) This successfully redirects to a Sharepoint authorisation screen where I'm asked if I trust my app. When I click the 'Trust It' button, I get an internal server error with this on the console: 127.0.0.1 - - [19/Mar/2018 14:48:15] "GET /login?code=IAAAAJ2%5FBr9vn6qSXfgVMvTH8zRV7l%2DFvowYYRZ4jRO52i5u7RA%2DKwgdswowaS4Msg79Oz%2Dl70kgUvpSwE8VtzJ7cXlw8EEN5lR6znN6XgaGSJrdZoYLTkVQuXMlN%5FAVy1TTnNCe5R5TFqL1sm6kphH7PnvxZQ6IX...&lt;redacted&gt; HTTP/1.1" 500 - Traceback (most recent call last): File "/home/tkcook/Envs/venv/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_respo…
tagged with: flask-oauthlib

http://stackoverflow.com/comment/85801063
comment on: http://stackoverflow.com/q/49399962
score: 0
type: Comment
type: QuestionComment
has text: Your indentation is broken, please fix.

http://stackoverflow.com/comment/85871816
comment on: http://stackoverflow.com/q/49431995
type: QuestionComment
has text: I am using the Breast Cancer Wisconsin (Diagnostic) Data Set. It contains 569 cases of either malignant or benign tumors, described with 30 features. Link: https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Diagnostic)
score: 0
type: Comment

http://stackoverflow.com/comment/85691473
type: Comment
has text: `savez`'s documentation explains exactly what it does, and hpaulj just explained it even more clearly. You can do the same thing yourself. Just read the docs for `zipfile` and it should be obvious how to do it, if you're not actually worried about creating a `.npz` file. Or you can just leave them as separate files.
type: QuestionComment
comment on: http://stackoverflow.com/q/49345482
score: 0

azure-blob-storage
tags question: http://stackoverflow.com/q/49410682
tags question: http://stackoverflow.com/q/49387388
tags question: http://stackoverflow.com/q/49333233
type: Tag
tag name: azure-blob-storage

http://stackoverflow.com/q/49360576
type: AnsweredQuestion
score: 2
tagged with: interpolation
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49361239
accepted answer: http://stackoverflow.com/a/49361239
answer count: 1
has body: I need a clarification on what tool to use and how to interpolate missing in Python. Refer to the code below: import matplotlib.pyplot as plt from scipy import interpolate # Create data with missing y values x = [i for i in range(0, 10)] y = [i**2 + i**3 for i in range(0, 10)] y[4] = np.nan y[7] = np.nan # Interpolation attempt 1: Use scipy's interpolate.interp1d f = interpolate.interp1d(x, y) ynew = f(x) # Interpolate attempt 2: Use pandas.Series.interpolate yp = pd.Series(y) yp = yp.interpolate(limit_direction='both', kind='cubic') plt.plot(x, y, 'o', x, ynew, '-', x, yp, 'x') plt.show() Code above yields the following diagram Notice how the interp1d line (as documented) does not handle NaN values. My question is: How do I handle NaN values while using the x values as does the scipy's interpolation.interp1d function? Thanks
favorite count: 0
type: Question
has title: Interpolating missing data in Python keeping in mind x values
tagged with: missing-data
tagged with: python
upvote count: 2

http://stackoverflow.com/comment/85783762
type: Comment
comment on: http://stackoverflow.com/q/49384111
type: QuestionComment
has text: the **arabic_reshaper** not do any thing if i remove it will get same result. about **s[::-1]** what line you think should add it ?
score: 0

http://stackoverflow.com/a/49341013
upvote count: 2
has comment: http://stackoverflow.com/comment/85682219
downvote count: 0
answers question: http://stackoverflow.com/q/49340971
type: Answer
has body: Replace: image = PhotoImage(file="image.gif") Label(image=image).pack() with: self.image = PhotoImage(file="image.gif") Label(image=self.image).pack() The image reference needs not to be garbage collected in order to be displayed.
has comment: http://stackoverflow.com/comment/85682273
score: 2

http://stackoverflow.com/a/49313015
type: Answer
accepted answer of: http://stackoverflow.com/q/49292192
has body: So I finally got it working, thanks to Jabir's comment, the link really did helped me solve the problem. Here is how I got it working HttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(true).build()) .setRedirectStrategy(new LaxRedirectStrategy() { public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { boolean isRedirect=false; try { isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { e.printStackTrace(); } if (!isRedirect) { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 301 || responseCode == 302) { return true; } } return isRedirect; } @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { String cokeis = response.getHeaders("Set-Cookie")[0].getValue(); HttpRequestBase requestBase = new HttpRequestBase() { @Override public String getMethod() { return "GET"; } }; requestBase.setURI(getLocationURI(request, response, context)); requestBase.setHeader("Cookie", cokeis); return requestBase; } }) .build(); HttpUriRequest request = RequestBuilder.get() .setUri("https://example.com/") .setHeader("Authorization", "&lt;key&gt;") .build(); HttpResponse resp = httpClient.execute(request); System.out.println(resp.getStatusLine().getStatusCode()); I still cant believe though the complexity involve in apache java http client to do simple http get request that redirects compared to other languages.
answers question: http://stackoverflow.com/q/49292192
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49400426
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/57151959
has comment: http://stackoverflow.com/comment/85802201
has title: Serializer validate function is not called DRF
has answer: http://stackoverflow.com/a/63005557
tagged with: python
has answer: http://stackoverflow.com/a/63693135
has body: class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class ParentSerializer(serializers.ModelSerializer): """ Serializer for task """ def validate_title(self, data): if not data.get('title'): raise serializers.ValidationError('Please set title') return data Validate Function is not called when Post ,Also how can i give custom errors to ChildSerializer ,
has comment: http://stackoverflow.com/comment/85802308
has answer: http://stackoverflow.com/a/49420550
score: 12
type: Question
upvote count: 12
has comment: http://stackoverflow.com/comment/122582135
has answer: http://stackoverflow.com/a/69559655
tagged with: api
answer count: 5

http://stackoverflow.com/comment/85713808
score: 0
type: Comment
type: QuestionComment
has text: @Andersson, 'Open' means open in the browser.
comment on: http://stackoverflow.com/q/49354201

http://stackoverflow.com/q/49343637
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/10665889
answer count: 1
has comment: http://stackoverflow.com/comment/85687600
favorite count: 0
type: Question
tagged with: indexing
score: 3
tagged with: dataframe
tagged with: python
has body: Please consider this df: df = pd.DataFrame({'a':[1,2], 'b':[1,2], 'c':[1,2], 'd':[1,2], 'e':[1,2], 'f':[1,2], 'g':[1,2], 'h':[1,2]}) a b c d e f g h 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 How can I select the 1st, 4th, and 5th-7th columns? What I tried: df.iloc[:, [0, 3, np.arange(5,8)]] ValueError: setting an array element with a sequence.
has answer: http://stackoverflow.com/a/49343653
accepted answer: http://stackoverflow.com/a/49343653
type: AnsweredQuestion
upvote count: 3
has title: How to select dataframe columns with lists and ranges combined

http://stackoverflow.com/comment/97806838
comment on: http://stackoverflow.com/a/49323161
score: 1
type: Comment
has text: After `brew cask install chromedriver` you can initialize in the python script via `driver = webdriver.Chrome("/usr/local/bin/chromedriver")`
type: AnswerComment

http://stackoverflow.com/comment/85772061
type: QuestionComment
has text: My problem is that in my case, if I use exec, df is still containing only 2 columns (Atr0, and Atr1)... I have the code into a function
comment on: http://stackoverflow.com/q/49384880
score: 0
type: Comment

http://stackoverflow.com/q/49433367
upvote count: 1
has answer: http://stackoverflow.com/a/49450715
favorite count: 0
type: Question
tagged with: apache-kafka
type: UnansweredQuestion
has body: I have a error when connect to kafka brokers the confluent console log show this error. [2018-03-22 11:46:03,545] WARN Failed to send SSL Close message (org.apache.kafka.common.network.SslTransportLayer) java.io.IOException: Broken pipe at sun.nio.ch.FileDispatcherImpl.write0(Native Method) at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47) at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93) at sun.nio.ch.IOUtil.write(IOUtil.java:65) at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471) at org.apache.kafka.common.network.SslTransportLayer.flush(SslTransportLayer.java:212) at org.apache.kafka.common.network.SslTransportLayer.close(SslTransportLayer.java:157) at org.apache.kafka.common.utils.Utils.closeAll(Utils.java:703) at org.apache.kafka.common.network.KafkaChannel.close(KafkaChannel.java:70) at org.apache.kafka.common.network.Selector.doClose(Selector.java:717) at org.apache.kafka.common.network.Selector.close(Selector.java:708) at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:500) at org.apache.kafka.common.network.Selector.poll(Selector.java:398) at kafka.network.Processor.poll(SocketServer.scala:535) at kafka.network.Processor.run(SocketServer.scala:452) at java.lang.Thread.run(Thread.java:748) My configuration on the kafka server is as follows: listeners=PLAINTEXT://:9092,SSL://:9093 # Broker security settings ssl.truststore.location=/home/xcode/Descargas/ssl/server.truststore.jks ssl.truststore.password=123456 ssl.keystore.location=/home/xcode/Descargas/ssl/server.keystore.jks ssl.keystore.password=123456 ssl.key.password=123456 ssl.client.auth=required security.inter.broker.protocol=SSL I have tried to perform operations using the KafkaClient of the kafka-pyton package and return the following error. assert broker, 'Broker id %s not in current metadata' % node_id AssertionError: Broker id None not in current metadata
tagged with: ssl
tagged with: python
tagged with: kafka-python
score: 1
has title: Error to Access with ssl to kafka brokers
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85874700
type: QuestionComment
score: 0
has text: The error is near the line starting with 966. Can you show that section?
type: Comment
comment on: http://stackoverflow.com/q/49435781

http://stackoverflow.com/q/49358473
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49358837
tagged with: concurrent.futures
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-multithreading
accepted answer: http://stackoverflow.com/a/49358837
tagged with: multithreading
has title: How to use concurrent.futures in Python
tagged with: python
has body: Im struggling to get multithreading working in Python. I have i function which i want to execute on 5 threads based on a parameter. I also needs 2 parameters that are the same for every thread. This is what i have: from concurrent.futures import ThreadPoolExecutor def do_something_parallel(sameValue1, sameValue2, differentValue): print(str(sameValue1)) #same everytime print(str(sameValue2)) #same everytime print(str(differentValue)) #different main(): differentValues = ["1000ms", "100ms", "10ms", "20ms", "50ms"] with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(do_something_parallel, sameValue1, sameValue2, differentValue) for differentValue in differentValues] But i don't know what to do next
score: 4
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/85819871
type: Comment
score: 0
type: AnswerComment
has text: The loc solution gives the date the incorrect way round: `31/01/2016 23:15 31/01/2016 23:30 31/01/2016 23:45 02/01/2016 00:00 01/02/2016 00:15 01/02/2016 00:30 `
comment on: http://stackoverflow.com/a/49408792

http://stackoverflow.com/q/49419056
answer count: 1
has comment: http://stackoverflow.com/comment/85839691
has answer: http://stackoverflow.com/a/49419179
type: Question
has title: Bowling scores program
downvote count: 1
score: -1
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/85839864
has body: I am having trouble completing this program. This program is supposed to have a team of 4 members. Each member bowls a total of 3 games. I need to write a program that asks each member their name and asks them for each of their 3 games for each member. These names need to be saved in a text file called "bowling.txt" and display them. Another separate program should be written to read the records from the "bowling.txt" file and should also display the average score for each bowler. This is my program so far: # This program will ask # the user for # bowling scores 'W'. def game(bowling): bowling_file = open('bowling.txt', 'w') for count in range(1, 5, + 1): print('Enter the name and the score for each game for member #', count, sep='') name = input('Name: ') game1 = input('Score for game 1: ') game2 = input('Score for game 2: ') game3 = input('Score for game 3: ') bowling_file.write(name + '\n') bowling_file.write(game1 + '\n') bowling_file.write(game2 + '\n') bowling_file.write(game3 + '\n') print() bowling_file.close() print('All games have been printed to bowling.txt') def main(): game('') main() -----------------This is the separate 'R' file--------------- # This program will keep # bowling scores 'R'. def game(bowling): bowling_file = open('bowling.txt', 'r') total = 0 NumLines = 0 line = bowling_file.readline() while line != "": NumLines += 1 bowling = int(line) total += bowling print(bowling) line = bowling_file.readline() average = total / NumLines print('The average score for member #', count, sep='') average = total / NumLines def main(): game('bowling.txt') main()
tagged with: python
has comment: http://stackoverflow.com/comment/85839706
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85839739

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

http://stackoverflow.com/q/49306963
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49307034
tagged with: random
has title: Remove from list as choices are made
has comment: http://stackoverflow.com/comment/85616145
has answer: http://stackoverflow.com/a/49307015
type: Question
type: UnansweredQuestion
has body: I am trying to create a program that creates a character by randomly assigning it a race, class, and stats. However I want each stat to have a unique value. So if strength is 8, then none of the other stats can be 8. How would I go about doing this? Do I need to delete list entries as choices are made? My code import random races = ["Human", "Dwarf", "Elf"] classes = ["Fighter", "Wizard", "Rogue"] stats = [8, 10, 11, 12, 14, 15] Strength = 0 Dexterity = 0 Constution = 0 Intelligence = 0 Wisdom = 0 Charisma = 0 Strength = random.choice(stats) Dexterity = random.choice(stats) Constution = random.choice(stats) Intelligence = random.choice(stats) Wisdom = random.choice(stats) Charisma = random.choice(stats) race = random.choice(races) clse = random.choice(classes)
has comment: http://stackoverflow.com/comment/85616169
has answer: http://stackoverflow.com/a/49307406
tagged with: python
has answer: http://stackoverflow.com/a/49307031
answer count: 4

http://stackoverflow.com/comment/85749325
type: QuestionComment
has text: Possible duplicate of [What's the best way to grab/parse command line arguments passed to a Python script?](https://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scri)
type: Comment
comment on: http://stackoverflow.com/q/49373647
score: 0

qwidget
tags question: http://stackoverflow.com/q/49383369
tag name: qwidget
type: Tag
tags question: http://stackoverflow.com/q/49334963

http://stackoverflow.com/q/49437366
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85876769
has comment: http://stackoverflow.com/comment/85876824
has comment: http://stackoverflow.com/comment/85876926
tagged with: datetime
tagged with: python
score: -1
has body: I have an issue that I am encountering with one of the modules. Due to the requirement of data handlers, one of the modules has to use the datetime library and the strptime function. But the code behavior does not seem to be consistent, when the left most zero from a date series in format MMDDYYYY is truncated especially for Jan month. Below are some example,you can see the 2nd and third command are identical but the month is getting corrupted. Anyways around how to handle it? &gt;&gt;&gt; datetime.strptime('01082018',"%m%d%Y") datetime.datetime(2018, 1, 8, 0, 0) &gt;&gt;&gt; datetime.strptime('1082018',"%m%d%Y") datetime.datetime(2018, 10, 8, 0, 0) &gt;&gt;&gt; datetime.strptime('8082018',"%m%d%Y") datetime.datetime(2018, 8, 8, 0, 0) &gt;&gt;&gt; datetime.strptime('08082018',"%m%d%Y") datetime.datetime(2018, 8, 8, 0, 0)
has comment: http://stackoverflow.com/comment/85876804
has comment: http://stackoverflow.com/comment/85876908
has answer: http://stackoverflow.com/a/49437519
has comment: http://stackoverflow.com/comment/85877007
has title: Python datetime library not able to handle 01022018 i.e as in MMDDYYYY format when left most zero is truncated
has comment: http://stackoverflow.com/comment/85876934
upvote count: 0
has comment: http://stackoverflow.com/comment/85876684
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85876780
downvote count: 1

http://stackoverflow.com/comment/85702527
type: QuestionComment
has text: how does lookarounds help with longer chunks? can you explain little more?
comment on: http://stackoverflow.com/q/49351273
score: 0
type: Comment

http://stackoverflow.com/comment/87496932
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49339355
type: QuestionComment
has text: Is this the code you are referring to? - https://github.com/keras-team/keras/blob/master/keras/applications/inception_v3.py The line numbers seems to have changed. Where exactly are you changing the code?

http://stackoverflow.com/q/49375881
score: -2
has comment: http://stackoverflow.com/comment/85752910
has comment: http://stackoverflow.com/comment/85753213
has comment: http://stackoverflow.com/comment/85753315
has answer: http://stackoverflow.com/a/54303238
has title: ImportError: no module named BeautifulSoup or BeautifulSoup4 - Python
has comment: http://stackoverflow.com/comment/85753164
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85752994
has comment: http://stackoverflow.com/comment/85752963
has comment: http://stackoverflow.com/comment/85753236
has comment: http://stackoverflow.com/comment/85752975
has comment: http://stackoverflow.com/comment/85752802
has comment: http://stackoverflow.com/comment/85752905
has comment: http://stackoverflow.com/comment/85752831
has answer: http://stackoverflow.com/a/49375913
tagged with: python
has body: On MacOS, I installed homebrew, then installed pip. Trying to use a Python scraper that uses "BeautifulSoup" package. Ran: pip install -r requirements.txt requirements.txt includes: BeautifulSoup ipython BeautifulSoup gives an error, after googling I realized that there is a new version. so I ran: pip install beautifulsoup4 seems to have installed correctly. Then I ran the scraping script and I got the following error: Traceback (most recent call last): File "scrape.py", line 3, in &lt;module&gt; from BeautifulSoup import BeautifulSoup ImportError: No module named BeautifulSoup I tried changing BeautifulSoup to BeautifulSoup4 in the script, but it is the same error. Anything else I can try? This is the script I am trying to use: https://github.com/jojurajan/wp-content-scraper
has comment: http://stackoverflow.com/comment/85753126
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85752865
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85753233
type: UnansweredQuestion

http://stackoverflow.com/q/49311773
downvote count: 0
accepted answer: http://stackoverflow.com/a/49312033
tagged with: pickle
upvote count: 1
has body: I have a button that can create another buttons, but when I close the program, the buttons I just created disappear. I know how to save things in a file using pickle, but how should I write the code so that it saves the buttons and creates them again when I open the program. code: def CreateButton(): global name,clicked,started started=True name = str(input("Write a Student Name...")) print('variable changed...') clicked=True def update(): global MainWindow,changed,clicked,name #global clicked if clicked and started: #name = input("Write a Student Name: ") button_new=needed_but(MainWindow=MainWindow,color="#E6E6E6",text=name) clicked=False buttonred=False MainWindow.after(1*1000,update) class needed_but: def __init__(self,MainWindow,color,text): console = Button(MainWindow, text=text,bg=color, command=self.changecolor) console.pack() self.instance=console def changecolor(self): buttonred,buttongreen,buttonblue=get_color() global clicked,misses_dict #clicked=True #global buttoncolor if buttonred == True: self.instance.configure(bg = "#ff0000") dun = self.instance.cget('text') print(dun) if dun in misses_dict: misses_dict[('%s' %(dun))] += 1 else: misses_dict[('%s' %(dun))] = 1 pickle.dump(dictionary, open("%s\SI\SIA.dat" %(path), 'wb')) print(misses_dict) buttonred = False elif buttongreen == True: self.instance.configure(bg = "#00ff00") elif buttonblue == True: self.instance.configure(bg = "#2e9afe")
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85625484
tagged with: python
has answer: http://stackoverflow.com/a/49312033
tagged with: python-3.x
tagged with: tkinter
has title: Python 3 Save Buttons
score: 1
answer count: 1
tagged with: button

http://stackoverflow.com/q/49311848
type: Question
tagged with: python-3.x
has title: Why doesn't Python have a "continue if" statement?
answer count: 3
possible better answer: http://stackoverflow.com/a/49312043
tagged with: python
has comment: http://stackoverflow.com/comment/85625556
has comment: http://stackoverflow.com/comment/85626233
upvote count: 11
type: AnsweredQuestion
has body: This is a pretty readable chunk of code I think, for i in range(100): continue if i % 2 == 0 But it's not syntactically correct. We can do other nice things in Python like, for i in things: total += 3 if i % 2 == 0 else 1 Or maybe, return a if b &gt; a else c Why can't we do a continue if statement?
score: 8
has comment: http://stackoverflow.com/comment/85625573
has answer: http://stackoverflow.com/a/49311953
downvote count: 3
accepted answer: http://stackoverflow.com/a/49311901
has answer: http://stackoverflow.com/a/49312043
has answer: http://stackoverflow.com/a/49311901
favorite count: 0

http://stackoverflow.com/comment/86451049
type: Comment
comment on: http://stackoverflow.com/a/49642742
type: AnswerComment
score: 0
has text: I am using `sudo apt-get install libpng-dev`.I will add the docker recipe to reproduce the context next monday. The reason to be interested in a custom adaptation of the récipe is that opencv have a ton of different compilation options, and I need to customize a couple of them.

http://stackoverflow.com/a/49333769
type: Answer
score: 0
upvote count: 1
downvote count: 1
has body: To extract the Auto Suggestions from Search Box on Google Home Page you have to induce WebDriverWait with expected_conditions as visibility_of_all_elements_located as follows : 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 driver = webdriver.Chrome(executable_path="C:\\Utility\\BrowserDrivers\\chromedriver.exe") driver.get("http://www.google.com") search_field = driver.find_element_by_name("q") search_field.send_keys("google") searchText_google_suggestion = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//form[@action='/search' and @role='search']//ul[@role='listbox']//li//span"))) for item in searchText_google_suggestion : print(item.text) Console Output : google google translate google maps google drive google pixel 2 google earth google news google scholar google play store google photos Here you can find a relevant discussion on How to automate Google Home Page auto suggestion?
answers question: http://stackoverflow.com/q/49325855

http://stackoverflow.com/comment/85836370
type: Comment
score: 0
has text: max_element's scope is restricted to the function since it is defined inside the function. you cannot access it outside. Python is not bash or Lua.
type: QuestionComment
comment on: http://stackoverflow.com/q/49417191

http://stackoverflow.com/comment/85567259
comment on: http://stackoverflow.com/q/49282238
type: Comment
type: QuestionComment
has text: @ma3oun thanks, but I need the entire matrix
score: 0

http://stackoverflow.com/a/49309626
has comment: http://stackoverflow.com/comment/85621715
score: 0
has body: Your gunicorn start command looks strange: Starting process with command `gunicorn mysite.wsgi --log-file -` The command should specify the module name and variable name separated with a colon, like this: gunicorn mysite.wsgi:application
answers question: http://stackoverflow.com/q/49306996
type: Answer
has comment: http://stackoverflow.com/comment/85695267

http://stackoverflow.com/q/49394155
type: Question
upvote count: 4
has title: RabbitMq Connection to 127.0.0.1:5672 Failed
has comment: http://stackoverflow.com/comment/86059561
has answer: http://stackoverflow.com/a/51352801
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52522350
has body: I'm currently following a rabbitmq tutorial and running into an issue. No matter how close I follow the tutorial I keep getting this error when trying to run my send.py and receive.py: pika.exceptions.ConnectionClosed: Connection to 127.0.0.1:5672 failed: [Errno 61] Connection refused This is the send.py: #!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close() This is the receive.py: #!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume(callback, queue='hello', no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() I can't for the life of me figure out what I'm doing wrong. I've looked at other post on here that ask a similar question but still no dice.
has answer: http://stackoverflow.com/a/76036942
downvote count: 0
favorite count: 0
tagged with: pika
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49433178
tagged with: rabbitmq
answer count: 4
has comment: http://stackoverflow.com/comment/85873911

http://stackoverflow.com/a/49405675
has comment: http://stackoverflow.com/comment/85812683
score: 0
has comment: http://stackoverflow.com/comment/85812519
has comment: http://stackoverflow.com/comment/85812604
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85812743
accepted answer of: http://stackoverflow.com/q/49405442
has body: If you want to split the two strings in the list and bind the result to two variables you can simply do this: mylist = ["a word 1 2 3 4","b word 5 6 7 8"] newlist1 = mylist[0].split() newlist2 = mylist[1].split() This is OK for 2 variables but in general, if you had more strings to split, that quickly becomes unwieldy. For a more general solution you can simply use a list of lists: &gt;&gt;&gt; newlists = [s.split() for s in mylist] &gt;&gt;&gt; newlists [['a', 'word', '1', '2', '3', '4'], ['b', 'word', '5', '6', '7', '8']] Then access each list by index: &gt;&gt;&gt; newlists[0] ['a', 'word', '1', '2', '3', '4'] &gt;&gt;&gt; newlists[1] ['b', 'word', '5', '6', '7', '8'] Or you might use a dictionary: &gt;&gt;&gt; d = {'newlist{}'.format(i) : s.split() for i, s in enumerate(mylist, 1)} &gt;&gt;&gt; d {'newlist1': ['a', 'word', '1', '2', '3', '4'], 'newlist2': ['b', 'word', '5', '6', '7', '8']} Now you can access the list by key: &gt;&gt;&gt; d['newlist1'] ['a', 'word', '1', '2', '3', '4'] &gt;&gt;&gt; d['newlist2'] ['b', 'word', '5', '6', '7', '8']
type: Answer
answers question: http://stackoverflow.com/q/49405442

http://stackoverflow.com/comment/86039810
has text: Yes, it is working, it wasn't that difficult. I still wish Twisted would implement a proper serial endpoint... work on that branch seems stalled. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49382435
type: AnswerComment

http://stackoverflow.com/q/49375927
answer count: 1
tagged with: scikit-learn
upvote count: 10
downvote count: 1
favorite count: 0
type: Question
score: 9
has title: AttributeError: 'GMM' object has no attribute 'covariances_' || AttributeError: 'module' object has no attribute 'GaussianMixture'
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49376863
has body: I have a snippet of code to fit the guassian model for my data. I have imported mixture from sklearn. However even I use mixture.GaussianMixture I get an error:AttributeError: 'module' object has no attribute 'GaussianMixture' and if I use the other way, it gives an error: AttributeError: 'GMM' object has no attribute 'covariances_'. I even tried importing covariance but doean't seem to work. Could anyone please let me know how to fix this error. from sklearn import mixture # Fit a Gaussian mixture with EM using five components gmm = mixture.GaussianMixture(n_components=5, covariance_type='full').fit(X) gmm = GMM(n_components=3, covariance_type='full')
has answer: http://stackoverflow.com/a/49376863

graph
tags question: http://stackoverflow.com/q/49304746
tags question: http://stackoverflow.com/q/49340520
tags question: http://stackoverflow.com/q/49367855
tags question: http://stackoverflow.com/q/49351897
tags question: http://stackoverflow.com/q/49355143
tags question: http://stackoverflow.com/q/49427320
tags question: http://stackoverflow.com/q/49319722
tags question: http://stackoverflow.com/q/49335183
tag name: graph
tags question: http://stackoverflow.com/q/49373003
type: Tag
tags question: http://stackoverflow.com/q/49340077
tags question: http://stackoverflow.com/q/49339575
tags question: http://stackoverflow.com/q/49297349
tags question: http://stackoverflow.com/q/49358396
tags question: http://stackoverflow.com/q/49297316

http://stackoverflow.com/comment/85854307
has text: @Chris_Rands far from optimal in which way? They look strikingly similar to me, and timing isn't an issue.
comment on: http://stackoverflow.com/a/49425861
type: Comment
score: 0
type: AnswerComment

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

http://stackoverflow.com/q/49355577
tagged with: dictionary
has title: Python 3, turning csv into a python dictionary
has answer: http://stackoverflow.com/a/49355765
has body: I am trying to take a csv file (which can be found here on my GitHub repo, https://github.com/playdscription/100daysofpython/blob/master/day_012/master_exercise_boolean.csv and turn it into a dictionary in python3. The idea is to take a google sheet, have multiple people fill it out, then turn it into a csv and have a python script pack that into a dictionary so I can access this information in a variety of ways. I open the csv file, make a reader object out of it, then I loop through each line, and loop through each item in a specific part of the line and if the item has a value in it then I want it to write that value to a dictionary I have labeled joint. However even if there is a value in the item, I cannot get it to even just print that value. What am I doing wrong? import csv exercise_library = {} joint = {} with open('/Users/laptop/github/100daysofpython/day_012/master_exercise_boolean.csv' , 'r') as csv_file: csv_reader = csv.reader(csv_file) #look for joint actions of the NECK for line in csv_reader: for item in line[4:7]: if item == True: joint[line[3]] = [item] #look for joint actions of the scapula. for item in line[8:12]: if item == True: joint[line[7]] = [item] #look for joint actions of the glenero_humeral. for item in line[13:19]: if item == True: print(item) #joint[line[12]] = [item] exercise_library[line[0]] = [joint]
score: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49355856
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85752511
comment on: http://stackoverflow.com/q/49375681
has text: What if there is odd number of rows? Say seven rows. How would like to split it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49279990
tagged with: ironpython
has body: I am trying to use gensim through IronPython, but installing this package seems to be impossible. I tried it with IronPython 2.7.7. with the following commands: ipy -X:Frames -m install ensurepip ipy -X:Frames -m pip install setuptools ipy -X:Frames -m pip install gensim Does anyone know if it is possible to use the gensim-package in IronPython? Otherwise, I have to switch a part of my .NET application over to CPython, where I have gensim working. Thanks in advance!
favorite count: 0
type: Question
tagged with: c#
type: UnansweredQuestion
has title: How to install gensim for IronPython?
tagged with: python
tagged with: gensim
answer count: 0
score: 1
downvote count: 0
tagged with: pip
upvote count: 1

http://stackoverflow.com/a/59541568
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49353243
has body: I got the same error with a more complicated project, after releasing a new version suddenly it failed. luckily in my case, I had docker images for each version, and was able to use pip freeze to see what changed. In both version I used xgboost==0.81 In the version that worked I had scikit-learn==0.21.3 and in the new version it was scikit-learn==0.22 surprisingly enough, that's now what caused the issue. I've tried to uninstall and reinstall xgboost and reverted scikit-learn to the version is was originally on, and still no luck (even after making sure to install one after the other in the right order). what did cause the issue was an update of numpy from 1.17.4 to 1.18.0. reverting it solved it for me (not sure why) this was python 3.6 on ubuntu

http://stackoverflow.com/a/49329937
has body: You can use regex to match the colors: from selenium import webdriver from bs4 import BeautifulSoup as soup import re d = driver.Chrome() d.get("https://www.n2yo.com/passes/?s=39090&amp;a=1") s = soup(d.page_source, 'lxml') data = [i.text for i in s.find_all('tr', {'bgcolor':re.compile('#FFFFFF|#FFFF33|#FFCC00')})] Output: [u'16-Mar 20:34N12\xb020:42W265\xb079\xb020:48SSW199\xb0-Map and details', u'17-Mar 07:51S178\xb007:58W260\xb052\xb008:05NNW341\xb0-Map and details', u'17-Mar 20:00NNE19\xb020:08E102\xb050\xb020:14S180\xb0-Map and details', u'18-Mar 07:17SSE160\xb007:24E83\xb077\xb007:31N349\xb0-Map and details', u'18-Mar 08:58SW217\xb009:04W269\xb013\xb009:09NW323\xb0-Map and details', u'18-Mar 21:06N6\xb021:13WNW295\xb041\xb021:19SW217\xb0-Map and details', u'19-Mar 06:43SE142\xb006:50ENE67\xb038\xb006:57N356\xb0-Map and details', u'19-Mar 08:23SSW196\xb008:30W268\xb027\xb008:36NNW333\xb0-Map and details', u'19-Mar 20:32N12\xb020:39WNW286\xb084\xb020:46SSW198\xb0-Map and details', u'20-Mar 07:48S177\xb007:55WSW254\xb055\xb008:02NNW342\xb0-Map and details', u'20-Mar 19:58NNE20\xb020:05E98\xb047\xb020:12S178\xb0-Map and details', u'21-Mar 07:14SSE159\xb007:22NE58\xb072\xb007:28N349\xb0-Map and details', u'21-Mar 08:55SW216\xb009:01W272\xb014\xb009:07NW325\xb0-Map and details', u'21-Mar 21:03N6\xb021:10WNW288\xb043\xb021:17SW215\xb0-Map and details', u'22-Mar 06:41SE141\xb006:48ENE70\xb036\xb006:54N356\xb0-Map and details', u'22-Mar 08:20S194\xb008:27W265\xb029\xb008:34NNW335\xb0-Map and details', u'22-Mar 20:29N13\xb020:36N348\xb086\xb020:43SSW196\xb0-Map and details', u'23-Mar 07:46S176\xb007:53W265\xb059\xb008:00NNW343\xb0-Map and details', u'23-Mar 19:55NNE20\xb020:02E94\xb045\xb020:09S177\xb0-Map and details', u'24-Mar 07:12SSE157\xb007:19ENE71\xb069\xb007:26N350\xb0-Map and details', u'24-Mar 08:53SW214\xb008:59W270\xb015\xb009:04NW325\xb0-Map and details', u'24-Mar 21:01N7\xb021:08WNW292\xb046\xb021:14SW214\xb0-Map and details', u'25-Mar 06:38SE139\xb006:45E…
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49329719
downvote count: 0

http://stackoverflow.com/q/49387995
tagged with: dictionary
has title: Extract a date from a dict in python
has body: I have a dict like this: SHOPS_AND_ORDERNUM = { 'Shop - Produce - 20180212.xlsx': 1334, 'Shop - Organic - 20180223.xlsx': 8893, 'Shop - Fresh - 20180226.xlsx': 5557, 'Shop - Dairy - 20180227.xlsx': 3870 } I want to extract the dates from the dict above into the form: DD-MM-YYYY I am new to regular expressions, and my attempts keep failing. I have started something like this: for i, j in DATA_FILES_AND_SO.items(): m = re.search(some_logic, i) if m: found = m.group(1) Any help would be much appreciated!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85777345
has answer: http://stackoverflow.com/a/49388137
score: 0
accepted answer: http://stackoverflow.com/a/49388053
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85777358
has answer: http://stackoverflow.com/a/49388610
has answer: http://stackoverflow.com/a/49388053
upvote count: 1
has answer: http://stackoverflow.com/a/49388129
downvote count: 1
favorite count: 0
type: Question
answer count: 5
possible better answer: http://stackoverflow.com/a/49388063
tagged with: python
has answer: http://stackoverflow.com/a/49388063

http://stackoverflow.com/comment/85643186
score: 0
comment on: http://stackoverflow.com/q/49321054
has text: Can you post any code you have so far so we know exactly what you need help with? Do you need to know how to walk through the directories to find the files, or how to find the specific elements, or something else?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49370043
downvote count: 0
has comment: http://stackoverflow.com/comment/85741722
answers question: http://stackoverflow.com/q/49369657
has body: Working example: junk &lt;- "total=7871MB;free=5711MB;used=2159MB;shared=0MB;buffers=304MB;cached=1059MB; free=71MB;total=5751MB;shared=3159MB;used=5MB;buffers=30MB;cached=1059MB; cached=1059MB;total=5751MB;shared=3159MB;used=5MB;buffers=30MB;free=109MB;" names &lt;- unique(strsplit(gsub("[(?\\n=\\d+MB;)]", " ", a, perl=TRUE), "(\\s+)")[[1]]) dataset &lt;- read.table(text=gsub("[^(\\d+)]", " ", a, perl=TRUE), header = FALSE, col.names=names)
has comment: http://stackoverflow.com/comment/85760116
type: Answer
score: 3
upvote count: 3

numpy
tags question: http://stackoverflow.com/q/49430866
tags question: http://stackoverflow.com/q/49303765
tags question: http://stackoverflow.com/q/49330707
tags question: http://stackoverflow.com/q/49288559
tags question: http://stackoverflow.com/q/49384079
tags question: http://stackoverflow.com/q/49436628
tags question: http://stackoverflow.com/q/49288973
tags question: http://stackoverflow.com/q/49397704
tags question: http://stackoverflow.com/q/49328235
tags question: http://stackoverflow.com/q/49304425
tags question: http://stackoverflow.com/q/49430215
tags question: http://stackoverflow.com/q/49413515
tags question: http://stackoverflow.com/q/49372552
tags question: http://stackoverflow.com/q/49383601
tags question: http://stackoverflow.com/q/49380594
tags question: http://stackoverflow.com/q/49288021
tags question: http://stackoverflow.com/q/49403845
tags question: http://stackoverflow.com/q/49410317
tags question: http://stackoverflow.com/q/49374698
tags question: http://stackoverflow.com/q/49408242
tags question: http://stackoverflow.com/q/49435915
tags question: http://stackoverflow.com/q/49393943
tags question: http://stackoverflow.com/q/49327692
tags question: http://stackoverflow.com/q/49425997
tags question: http://stackoverflow.com/q/49386165
tags question: http://stackoverflow.com/q/49309679
tags question: http://stackoverflow.com/q/49428916
tags question: http://stackoverflow.com/q/49386958
tags question: http://stackoverflow.com/q/49323171
tags question: http://stackoverflow.com/q/49290826
tags question: http://stackoverflow.com/q/49312838
tags question: http://stackoverflow.com/q/49316668
tags question: http://stackoverflow.com/q/49427065
tags question: http://stackoverflow.com/q/49374064
tags question: http://stackoverflow.com/q/49365532
tags question: http://stackoverflow.com/q/49306351
tags question: http://stackoverflow.com/q/49419205
tags question: http://stackoverflow.com/q/49371486
tags question: http://stackoverflow.com/q/49343231
tags question: http://stackoverflow.com/q/49290187
tags question: http://stackoverflow.com/q/49287398
tags question: http://stackoverflow.com/q/49368783
tags question: http://stackoverflow.com/q/49382207
tags question: http://stackoverflow.com/q/49303178
tags question: http://stackoverflow.com/q/49394681
tags question: http://stackoverflow.com/q/49296927
tags question: http://stackoverflow.com/q/49289417
tags question: http://stackoverflow.com/q/49438910
tags question: http://stackoverflow.com/q/49313488
tags question: http://stackoverflow.com/q/49371430
tags question: http://stackoverflow.com/q/49290238
tags question: http://stackoverflow.com/q/49372640
tags question: http://stackoverflow.com/q/49331458
tags question: http://stackoverflow.com/q/49349388
tags question: http://stackoverflow.com/q/49394102
tags question: http://stackoverflow.com/q/49350463
tags question: http://stackoverflow.com/q/49407029
tags question: http://stackoverflow.com/q/49324767
tags question: http://stackoverflow.com/q/49332811
tags question: http://stackoverflow.com/q/49342589
tags question: http://stackoverflow.com/q/49382504
tags question: http://stackoverflow.com/q/49308887
tags question: http://stackoverflow.com/q/49350659
tags question: http://stackoverflow.com/q/49394188
tags question: http://stackoverflow.com/q/49437047
tags question: http://stackoverflow.com/q/49392396
tags question: http://stackoverflow.com/q/49297298
tags question: http://stackoverflow.com/q/49392083
tags question: http://stackoverflow.com/q/49380182
tags question: http://stackoverflow.com/q/49392915
tags question: http://stackoverflow.com/q/49312775
tags question: http://stackoverflow.com/q/49384682
tags question: http://stackoverflow.com/q/49368516
tags question: http://stackoverflow.com/q/49346906
tags question: http://stackoverflow.com/q/49367278
tags question: http://stackoverflow.com/q/49378486
tags question: http://stackoverflow.com/q/49372813
tags question: http://stackoverflow.com/q/49288016
tags question: http://stackoverflow.com/q/49358449
tags question: http://stackoverflow.com/q/49340169

http://stackoverflow.com/comment/85647962
comment on: http://stackoverflow.com/q/49309147
has text: Have you tested boto3's s3.copy_object()? Some related solutions here: https://aws.amazon.com/blogs/compute/content-replication-using-aws-lambda-and-amazon-s3/ and https://aws.amazon.com/blogs/compute/synchronizing-amazon-s3-buckets-using-aws-step-functions/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85632006
type: AnswerComment
comment on: http://stackoverflow.com/a/49288052
score: 0
type: Comment
has text: They both return `MacOSX`

http://stackoverflow.com/q/49424274
duplicate of: http://stackoverflow.com/q/34725117
linked to: http://stackoverflow.com/q/10802418
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85849933
has body: I have a question about how to save files after I convert them from psd to jpg using python. Since I want to check every file, I used os.walk function. Here is my code. When I run this, I have this error. FileNotFoundError: [Errno 2] No such file or directory: 'test02.psd' The folder I want to save files in is in the same category as python file. But the psd file is in the subfolder somewhere. How can I get over this? from PIL import Image import os for path, dir, files in os.walk('.'): for file in files: if file.endswith('.psd'): print('The {} is being converted to jpg...'.format(file)) i = Image.open(file) fn, fext = os.path.splitext(file) try: i.save('jpgs/{}.jpg'.format(fn)) # I created a folder named 'jpgs' already. except Exception as e: print(e)
has title: How to convert and save files(os.walk)
tagged with: python
has comment: http://stackoverflow.com/comment/85849786
score: 2
has comment: http://stackoverflow.com/comment/85850402
has comment: http://stackoverflow.com/comment/85849635
upvote count: 2
has comment: http://stackoverflow.com/comment/85849534
linked to: http://stackoverflow.com/q/34725117
has comment: http://stackoverflow.com/comment/85851585
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49424326
has comment: http://stackoverflow.com/comment/85849877
favorite count: 0
tagged with: os.walk
type: Question

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

http://stackoverflow.com/comment/85772619
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49299789
has text: BTW, it would be more concise to do like `with myConnection as cur: …`, because a MySQLdb connection used as a context manager produces a cursor.

http://stackoverflow.com/q/49348321
has answer: http://stackoverflow.com/a/49502674
has title: What is wrong with my code in python?
type: AnsweredQuestion
tagged with: bbc-microbit
score: -1
possible better answer: http://stackoverflow.com/a/49502674
type: Question
accepted answer: http://stackoverflow.com/a/49348349
answer count: 2
has answer: http://stackoverflow.com/a/49348349
downvote count: 2
upvote count: 1
has body: In my code, its supposed to be a magic 8 ball that is rigged. Pressing A should show "Yes!", pressing B should show "No." But every time, it shows "Yes!" without any buttons being pressed. from microbit import * import random frameq = Image("00000:""00000:""00900:""00000:""00000") framew = Image("00000:""09990:""09390:""09990:""00000") framee = Image("99999:""93339:""93339:""93339:""99999") framer = Image("33333:""33333:""33333:""33333:""33333") framet = Image("22222:""22222:""22222:""22222:""22222") framey = Image("11111:""11111:""11111:""11111:""11111") frames = [frameq, framew, framee, framer, framet, framey] answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it" "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] apress = False bpress = False while True: if button_a.is_pressed: bpress = False apress = True elif button_b.is_pressed: apress = False bpress = True display.show("8") if accelerometer.was_gesture("shake") and apress is True: display.clear() display.show(frames, loop=False, delay=250) sleep(1000) display.show("Yes!") apress = False elif accelerometer.was_gesture("shake") and bpress is True: display.clear() display.show(frames, loop=False, delay=250) sleep(1000) display.show("No.") bpress = False elif accelerometer.was_gesture("shake"): display.clear() display.show(frames, loop=False, delay=250) sleep(1000) display.scroll(random.choice(answers)) It shows no error message, it just shows "Yes!" every single time I shake. And by the way, "Yes!" is not in the answers array, only "Yes", and I always see the !.
tagged with: python
favorite count: 0

http://stackoverflow.com/q/49425610
type: UnansweredQuestion
has title: Cannot find required executable ovs-controller : Mininet
has body: sudo python Topology.py N = 6 *** Creating network *** Adding controller *** Adding hosts: a b c d e u *** Adding switches: s1 s2 *** Adding links: (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (a, s1) (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (b, s1) (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (c, s2) (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (d, s2) (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (5.00Mbit 3ms delay 2% loss) *** Error: RTNETLINK answers: No such file or directory (e, s1) Traceback (most recent call last): File "Topology.py", line 45, in &lt;module&gt; perfTest() File "Topology.py", line 33, in perfTest net = Mininet(topo=topo,host=CPULimitedHost,link=TCLink,controller=OVSController) File "/usr/lib/python2.7/dist-packages/mininet/net.py", line 172, in __init__ self.build() File "/usr/lib/python2.7/dist-packages/mininet/net.py", line 442, in build self.buildFromTopo( self.topo ) File "/usr/lib/python2.7/dist-packages/mininet/net.py", line 429, in buildFromTopo self.addLink( **params ) File "/usr/lib/python2.7/dist-packages/mininet/net.py", line 364, in addLink link = cls( node1, node2, **options ) File "/usr/lib/python2.7/dist-packages/mininet/link.py", line 534, in __init__ params2=params ) File "/usr/lib/python2.7/dist-packages/mininet/link.py", line 424, in __init__ node1, node2, deleteIntfs=False ) File "/usr/lib/python2.7/dist-packages/mininet/link.py", line 468, in makeIntfPair deleteIntfs=deleteIntfs ) File "/…
linked to: http://stackoverflow.com/q/17341076
tagged with: python
tagged with: controller
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49485794
type: Question
tagged with: mininet

http://stackoverflow.com/comment/85811148
type: Comment
has text: Thanks Daniel. I checked defer and only in shell. I still get all fields and their values. When I checked the description I see that "Whenever you call only() it replaces the set of fields to load immediately." So defer and only are for immediate load but when you try to read the field that is in defer you can still get the value. What is more defer and only is not working for reverse relations. Am I right? Thanks again.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49403260

http://stackoverflow.com/a/49342638
answers question: http://stackoverflow.com/q/49342589
has body: Trace each part out, this should speak for itself. Comments inlined. In [304]: array = np.array([1, 1, 2, 3, 2, 1, 2, 3]) In [305]: np.unique(array) # unique values in `array` Out[305]: array([1, 2, 3]) In [306]: array == 1 # retrieve a boolean mask where elements are equal to 1 Out[306]: array([ True, True, False, False, False, True, False, False]) In [307]: (array == 1).nonzero()[0] # get the `True` indices for the operation above Out[307]: array([0, 1, 5]) In summary; the code is creating a mapping of &lt;unique_value : all indices of unique_value in array&gt; - In [308]: {i: (array == i).nonzero()[0] for i in np.unique(array)} Out[308]: {1: array([0, 1, 5]), 2: array([2, 4, 6]), 3: array([3, 7])} And here's the slightly more readable version - In [313]: mapping = {} ...: for i in np.unique(array): ...: mapping[i] = np.where(array == i)[0] ...: In [314]: mapping Out[314]: {1: array([0, 1, 5]), 2: array([2, 4, 6]), 3: array([3, 7])}
type: Answer
accepted answer of: http://stackoverflow.com/q/49342589
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49395146
type: Answer
answers question: http://stackoverflow.com/q/49395100
score: 7
type: AcceptedAnswer
downvote count: 0
has body: df.unstack(0).swaplevel(0, 1, 1).sort_index(1)
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49395100

http://stackoverflow.com/comment/85719281
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49359474
has text: Before you can attempt to solve the coding part of your problem, you should decide what kind of [regression analysis](https://en.wikipedia.org/wiki/Regression_analysis) you want to determine a trend. In the real world, many data sets will get better and worse all the time. Or do you want a tri-state output of `always improving`, `always decaying`, `no clear trend`?
type: QuestionComment

http://stackoverflow.com/comment/85811267
type: QuestionComment
score: 0
has text: @Josh Are you sure? I'm getting an error: "Could not find a version that satisfies the requirement <dependency>". Am I missing something? (Added setup.py to question)
comment on: http://stackoverflow.com/q/49402740
type: Comment

http://stackoverflow.com/comment/85646699
type: QuestionComment
score: 0
has text: Please add more details
comment on: http://stackoverflow.com/q/49322015
type: Comment

http://stackoverflow.com/q/49305349
answer count: 1
score: -1
tagged with: utf-8
has comment: http://stackoverflow.com/comment/85620176
favorite count: 0
has title: 'ascii' codec can't decode byte
type: Question
has comment: http://stackoverflow.com/comment/85618727
has comment: http://stackoverflow.com/comment/85618904
upvote count: 0
accepted answer: http://stackoverflow.com/a/49305778
has comment: http://stackoverflow.com/comment/85621511
has body: I getting this error 'ascii' codec can't decode byte 0xc2 in position 69: ordinal not in range(128) on this line of code: documents1 = text_file.read().split("\n\n"). I am opening the file with text_file = open(filepath, "r") Normally I would simply stick .encode('utf-8'), but that just gives 'str' object has no attribute 'encode'
tagged with: python
has answer: http://stackoverflow.com/a/49305778
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85621767

http://stackoverflow.com/q/49300502
has answer: http://stackoverflow.com/a/49302414
tagged with: python
tagged with: nosql
tagged with: mongodb
has comment: http://stackoverflow.com/comment/85602852
score: 0
answer count: 1
tagged with: pymongo
has comment: http://stackoverflow.com/comment/85602809
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85603034
has body: I am quite new in using Mongodb. I have a database exported from a json (the other values at the moment are not important). The query I am trying to make is this one: I want all the mercancia that all the different client have. So in this case, the client Electronica Chispas, will have 2 mercancia with all the info about it. [{"cliente": {"nombre": "Cafes el amanencer"}, "mercancia": {"envio": "Normal", "tipo": "Gaseoso", "fecha": "24/12/2003", "peso": 21, "volumen": 43, "origen": "Cadiz", "destino": "Castellon"}, "vagon": {"id": 1330, "volumen": 202, "peso": 433 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Normal", "tipo": "Liquido", "fecha": "08/02/2005", "peso": 17, "volumen": 24, "origen": "San Sebastian", "destino": "Orense"}, "vagon": {"id": 1290, "volumen": 111, "peso": 464 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Urgente intradia", "tipo": "Contaminante", "fecha": "15/09/2002", "peso": 11, "volumen": 83, "origen": "Valladolid", "destino": "Ciudad Real"}, "vagon": {"id": 1315, "volumen": 115, "peso": 481 }}] I am missing some syntaxis or maybe I am just not doing it right. In python (but you can do it in the db itself). db.prueba1.find({'cliente.cliente': {$mercancias}}) I have syntax error, but there are so many ways to do find() that I am quite lost. I am not looking especifically for the query solved, but the way it could be solved (pseudocode, whatever helps me solve it).
has title: simple Find() query in MongoDB
accepted answer: http://stackoverflow.com/a/49302414

http://stackoverflow.com/comment/85828799
comment on: http://stackoverflow.com/q/49402761
score: 0
type: Comment
type: QuestionComment
has text: `package` needs to be importable. You could extend `sys.path` in the Sphinx config relative to that config module (`__file__` and `os.path` functions are useful here).

http://stackoverflow.com/q/49298976
type: AnsweredQuestion
score: 0
answer count: 1
has body: I'm new to python and I've been trying to parse the output of from an F5 API request and I'm struggling a bit. I would like to extract all the "name" and "destination" values and save those to a file. This should be a name and the corresponding IP address. From the output below, it would be: test-account 10.1.1.1 test-account_443 10.1.1.5 I can extract the individual elements, but I'm struggling to figure out how to iterate over the output file so I can get all of the key values I want. I've cut the output short to make it easier to read. parsed_json = json.loads(data) destination = parsed_json['items'][0]['destination'] name = parsed_json['items'][0]['name'] This only extracts one key value from the whole output file. Many thanks in advance. { "kind": "tm:ltm:virtual:virtualcollectionstate", "items": [ { "kind": "tm:ltm:virtual:virtualstate", "name": "test-account", "partition": "Common", "fullPath": "/Common/test-account", "generation": 1, "addressStatus": "yes", "autoLasthop": "default", "cmpEnabled": "yes", "connectionLimit": 0, "destination": "/Common/10.1.1.1:80", "enabled": true, "gtmScore": 0, "ipProtocol": "tcp", "mask": "255.255.255.255", "mirror": "disabled", "mobileAppTunnel": "disabled", "nat64": "disabled", "pool": "/Common/test-account", "rateLimit": "disabled", "rateLimitDstMask": 0, "rateLimitMode": "object", "rateLimitSrcMask": 0, "serviceDownImmediateAction": "none", "source": "0.0.0.0/0", "sourceAddressTranslation": { "type": "automap" }, "sourcePort": "preserve", "synCookieStatus": "not-activated", "translateAddress": "enabled", "translatePort": "enabled", "vlansDisabled": true, "vsIndex": 2, "rules": [ "/Common/redirect-http-to-https" ], "rulesReference": [ { "link": } ], "policiesReference": { "link": "isSubcollection": true }, "profilesReference": { "link": "isSubcollection": true } }, { "kind": "tm:ltm:virtual:virtualstate", "name": "test-account_443", "partition": "Common", "fullPath": "/Common/test-account_443", "generation": 1, "selfLink"…
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49299184
has answer: http://stackoverflow.com/a/49299184
has title: Parse API output in Python
tagged with: f5
has comment: http://stackoverflow.com/comment/85601616

http://stackoverflow.com/q/49281676
tagged with: python-3.x
has body: I have a 3D tensor with shape (X,Y,Z). Only Z is known in advance, everything else is determined at running time. I have an integer N s.t N divides X. I would like to do an operation similar to tf.reduce_mean on one axis without completely getting rid of the axis I'm taking the mean along. Another way of seeing this is as a tf.reduce_mean operation on subtensors of dimension (X/N, Y, Z) and concatenating the results back. So the final shape of my 3D tensor would be (N,Y,Z) So given N=2 and the following 3D tensor [[[1., 2.], [3., 4.], [5., 6.]], [[7., 8.], [9., 0.], [1., 2.]], [[3., 4.], [5., 6.], [7., 8.]], [[9., 0.], [1., 2.], [3., 4.]] [[5., 6.], [7., 8.], [9., 0.]] [[1., 2.], [3., 4.], [5., 6.]]] the new 3D tensor should be [[[3.66, 4.66], [5.66, 2.66], [4.33, 5.33]], [[5 , 2.66], [3.66 , 4.66], [5.66 , 3.33]]] I've looked around for a bit in both the tensorflow documentation and on this website, but couldn't find anything. Any insights on what the simplest/most efficient way of doing this is?
upvote count: 1
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49281770
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49281770
has title: Tensorflow: reduce_mean of subtensors and concatenating the results
type: Question

http://stackoverflow.com/comment/85630935
type: Comment
type: QuestionComment
score: 6
has text: You need to use ajax
comment on: http://stackoverflow.com/q/49314730

http://stackoverflow.com/comment/85808005
score: 0
type: Comment
has text: What is `INPUT_SIZE` set to?
comment on: http://stackoverflow.com/q/49398457
type: QuestionComment

http://stackoverflow.com/q/49358396
type: Question
tagged with: graph
type: UnansweredQuestion
tagged with: attention-model
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/51348792
tagged with: deep-learning
has title: PyTorch: How to implement attention for graph attention layer
tagged with: pytorch
answer count: 1
has body: I have implemented the attention (Eq. 1) of https://arxiv.org/pdf/1710.10903.pdf but it's clearly not memory efficient and can run only a single model on my GPU (it takes 7-10GB). Currently, I have class MyModule(nn.Module): def __init__(self, in_features, out_features): super(MyModule, self).__init__() self.in_features = in_features self.out_features = out_features self.W = nn.Parameter(nn.init.xavier_uniform(torch.Tensor(in_features, out_features).type(torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor), gain=np.sqrt(2.0)), requires_grad=True) self.a = nn.Parameter(nn.init.xavier_uniform(torch.Tensor(2*out_features, 1).type(torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor), gain=np.sqrt(2.0)), requires_grad=True) def forward(self, input): h = torch.mm(input, self.W) N = h.size()[0] a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.out_features) e = F.elu(torch.matmul(a_input, self.a).squeeze(2)) return e Where my insight to compute all the e_ij terms is In [8]: import torch In [9]: import numpy as np In [10]: h = torch.LongTensor(np.array([[1,1], [2,2], [3,3]])) In [11]: N=3 In [12]: h.repeat(1, N).view(N * N, -1) Out[12]: 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 [torch.LongTensor of size 9x2] In [13]: h.repeat(N, 1) Out[13]: 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3 [torch.LongTensor of size 9x2] And finally concatenate both hs and feed matrix a. Is there a way to do it in a more memory-friendly way ?

http://stackoverflow.com/a/49434557
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49434230
score: 2
has comment: http://stackoverflow.com/comment/85871296
type: Answer
has body: If I understood you correctly, you can get those articles by changing the api query like this: import requests data_range = ['24hours', '7days', '30days', '365days'] news_feed = {} with requests.Session() as s: for rng in data_range: news_feed[rng] = s.get('http://query.nytimes.com/svc/add/v1/sitesearch.json?begin_date={}ago&amp;facet=true'.format(rng)).json() And access the values like this: print(news_feed) #or print(news_feed['30days']) EDIT To query aditional pages, you may try this: import requests data_range = ['7days'] news_feed = {} news_list = [] page = 1 with requests.Session() as s: for rng in data_range: while page &lt; 20: #this is limited to 120 news_list.append(s.get('http://query.nytimes.com/svc/add/v1/sitesearch.json?begin_date={}ago&amp;page={}&amp;facet=true'.format(rng, page)).json()) page += 1 news_feed[rng] = news_list for new in news_feed['7days']: print(new)
has comment: http://stackoverflow.com/comment/85872494
accepted answer of: http://stackoverflow.com/q/49434230
upvote count: 2

http://stackoverflow.com/comment/85804239
type: Comment
type: QuestionComment
has text: @Sraw yes. Is that wrong?
score: 0
comment on: http://stackoverflow.com/q/49401418

http://stackoverflow.com/a/49312359
has comment: http://stackoverflow.com/comment/85658004
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49312298
has body: That can be done with a list comprehension like: Code: data = [[int(x[0]), [y.strip() for y in x[1].split(',')]] for x in (line.split(':') for line in letters)] Test Code: letters = ['1:a, b, c', '2: d, e, f'] data = [[int(x[0]), [y.strip() for y in x[1].split(',')]] for x in (line.split(':') for line in letters)] print(data) Results: [[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]]
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85763201
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49380204
has text: Thanks for your quick response. My code is working fine when using in a small dataframe. It will raise error if count is larger than 5000
score: 0

http://stackoverflow.com/comment/85754520
type: Comment
comment on: http://stackoverflow.com/q/49376022
score: 0
has text: i am going to check if the pixel are skin pixels or not
type: QuestionComment

http://stackoverflow.com/q/49417747
has comment: http://stackoverflow.com/comment/85837258
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85837390
has comment: http://stackoverflow.com/comment/85837585
has comment: http://stackoverflow.com/comment/85837422
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85837287
accepted answer: http://stackoverflow.com/a/49417919
has comment: http://stackoverflow.com/comment/85837602
favorite count: 0
type: Question
has title: Customize how a Python object is processed as a function argument?
has comment: http://stackoverflow.com/comment/85837231
has body: A Python class's __call__ method lets us specify how a class member should be behave as a function. Can we do the "opposite", i.e. specify how a class member should behave as an argument to an arbitrary other function? As a simple example, suppose I have a ListWrapper class that wraps lists, and when I call a function f on a member of this class, I want f to be mapped over the wrapped list. For instance: x = WrappedList([1, 2, 3]) print(x + 1) # should be WrappedList([2, 3, 4]) d = {1: "a", 2: "b", 3:"c"} print(d[x]) # should be WrappedList(["a", "b", "c"]) Calling the hypothetical __call__ analogue I'm looking for __arg__, we could imagine something like this: class WrappedList(object): def __init__(self, to_wrap): self.wrapped = to_wrap def __arg__(self, func): return WrappedList(map(func, self.wrapped)) Now, I know that (1) __arg__ doesn't exist in this form, and (2) it's easy to get the behavior in this simple example without any tricks. But is there a way to approximate the behavior I'm looking for in the general case?
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85837282
has answer: http://stackoverflow.com/a/49417919
has comment: http://stackoverflow.com/comment/85837261

http://stackoverflow.com/a/49329494
upvote count: 1
answers question: http://stackoverflow.com/q/49329214
type: Answer
downvote count: 0
has body: It looks like it may have what you need built-in, but I don't see a prebuilt option &gt;&gt;&gt; import autopep8 &gt;&gt;&gt; autopep8.join_logical_line("""plt.legend( ... handles=[ ... indrnn_plot, ... lstm_plot,], ... loc=0)""".decode('utf-8')) u'plt.legend( handles=[ indrnn_plot, lstm_plot,], loc=0)\n' &gt;&gt;&gt; print(u'plt.legend( handles=[ indrnn_plot, lstm_plot,], loc=0)\n') plt.legend( handles=[ indrnn_plot, lstm_plot,], loc=0) &gt;&gt;&gt; print(len(u'plt.legend( handles=[ indrnn_plot, lstm_plot,], loc=0)\n')) 55 So you need to go through your file by logical line, check if the join is less than or equal to 79 chars and then replace it.
score: 1

http://stackoverflow.com/q/49308530
has body: I have a time series dataframe, the dataframe is quite big and contain some missing values in the 2 columns('Humidity' and 'Pressure'). I would like to impute this missing values in a clever way, for example using the value of the nearest neighbor or the average of the previous and following timestamp.Is there an easy way to do it? I have tried with fancyimpute but the dataset contain around 180000 examples and give a memory error
downvote count: 1
tagged with: imputation
has answer: http://stackoverflow.com/a/49309473
accepted answer: http://stackoverflow.com/a/49309473
tagged with: nan
favorite count: 0
has answer: http://stackoverflow.com/a/49308715
type: Question
possible better answer: http://stackoverflow.com/a/54494569
has comment: http://stackoverflow.com/comment/85619503
has answer: http://stackoverflow.com/a/54494569
has answer: http://stackoverflow.com/a/49308695
score: 26
has comment: http://stackoverflow.com/comment/85619487
tagged with: python
upvote count: 27
answer count: 4
has title: Missing values in Time Series in python
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/a/49337909
has body: I would use python to make a supreme bot. I am doing kinda the same thing just wanting to make an adidas bot. I did some research and most botters use python. If you type hi in to the debug console it will stop running but instead you should open the file and run it in terminal or command line. just write cd /path/of/your/file python yourfilename.py This should make it say hola and you having the possibility of answering hi. please share some more of you program
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49333123
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/49292070
has title: Python can't access subclass methods that aren't extended from base class
type: UnansweredQuestion
score: 0
tagged with: inheritance
tagged with: oop
has comment: http://stackoverflow.com/comment/85587356
has comment: http://stackoverflow.com/comment/85782176
tagged with: subclass
tagged with: python
type: Question
has body: So I have in one module a subclass that is extended from a base class in another module. The subclass extends a couple methods from the base class, but also includes several classes that are not extended Now from a different module, I import the subclass, and for some reason, I only have access to the methods that are extended from the base class. If I try to call one of the instance methods that is declared in the subclass, I get an AttributeError: "subclass" Object has no attribute "non-extended method" Is this some strange python inheritance rule that it is supposed to behave this way? And what am I supposed to do to be able to access the non-extended instance methods if I don't want those methods to be declared in the base class? Thanks.
tagged with: instance
answer count: 0

time-series
tags question: http://stackoverflow.com/q/49367995
tags question: http://stackoverflow.com/q/49387205
tags question: http://stackoverflow.com/q/49301997
tags question: http://stackoverflow.com/q/49329097
tags question: http://stackoverflow.com/q/49439055
tags question: http://stackoverflow.com/q/49387930
tags question: http://stackoverflow.com/q/49299766
type: Tag
tags question: http://stackoverflow.com/q/49304516
tags question: http://stackoverflow.com/q/49306601
tag name: time-series
tags question: http://stackoverflow.com/q/49352279
tags question: http://stackoverflow.com/q/49411776
tags question: http://stackoverflow.com/q/49327905
tags question: http://stackoverflow.com/q/49280856
tags question: http://stackoverflow.com/q/49416980
tags question: http://stackoverflow.com/q/49306922
tags question: http://stackoverflow.com/q/49376811
tags question: http://stackoverflow.com/q/49411948
tags question: http://stackoverflow.com/q/49325236

http://stackoverflow.com/comment/85730188
comment on: http://stackoverflow.com/q/49364859
score: 1
type: Comment
has text: what does `APIModuleException` inherit from? `ValueError`? why not `except APIModuleException` in your main?
type: QuestionComment

http://stackoverflow.com/a/49391297
upvote count: 1
has body: Before answering your question, there is an important thing you need to know about Python strings, which is that they are immutable. As the Data Model doc proposes: The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. So you can't just use the replace method but you have to reassign the new string into your text string. So this part: print(text.replace(EL,str(PasswordSubHT[EL]))) Would be: text = text.replace(LETTER, PasswordSubHT[LETTER], 1) print(text) You don't also have to loop over the string to assign it to a list, but just loop over the string itself and check the condition you want. According to replace method doc. You can specify how many characters are allowed to be replaced, by providing the maxreplace argument. So what you need is something like: CharList = [] text = "xxxxAAaaaSSSxxx" PasswordSubHT = {"a":"@" , "A":"4" , "S":"5"} for LETTER in text: if LETTER in PasswordSubHT.keys(): # Note: Check the new max character argument. text = text.replace(LETTER, PasswordSubHT[LETTER], 1) print(text)
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49390828
type: Answer

http://stackoverflow.com/a/49410931
upvote count: 2
downvote count: 0
has body: pd.Series([i in mystring for i in df.A]) Output: 0 True 1 False dtype: bool
score: 2
answers question: http://stackoverflow.com/q/49410786
type: Answer

http://stackoverflow.com/q/49419367
duplicate of: http://stackoverflow.com/q/5434400
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: iterator
has body: Suppose we have the following class: class Klass: iterable_attr_names = {'x', 'y', 'z'} x = 5 y = 6 z = 7 def __init__(self): pass def foo(*args): # 'foo' is not in iterable_attr_names return Is it possible to define an __iter__ method for the class, instead of only instances of the class? The implementation of the class __iter__ method might look something like the following: class KlassIter: def __init__(self, klass): self._klass = klass self._inner_it = iter(klass.iterable_attr_names) def __next__(self): attr_name = next(self._inner_it) return getattr(self._klass, attr_name) Then we could do this: print(Klass.x) print(Klass.y) print(Klass.z) and this: for attr in Klass: print(attr)
answer count: 0
has comment: http://stackoverflow.com/comment/85840270
type: UnansweredQuestion
upvote count: 3
has title: Is it possible to define an __iter__ method for a class?
downvote count: 0
linked to: http://stackoverflow.com/q/5434400
has comment: http://stackoverflow.com/comment/85840268
score: 3

http://stackoverflow.com/comment/85639903
has text: Maybe try doing `request.POST.get('receivedon')` instead, this will ensure that you don't get a MultiValueDictKeyError error
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49319153
score: 0

http://stackoverflow.com/q/49303543
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85609158
score: 0
has body: I'm looking to retrieve all but one value from a list: ll = ['a','b','c'] nob = [x for x in ll if x !='b'] Is there any simpler, more pythonic way to do this, with sets perhaps?
has comment: http://stackoverflow.com/comment/85609239
has answer: http://stackoverflow.com/a/49304475
possible better answer: http://stackoverflow.com/a/49304475
has comment: http://stackoverflow.com/comment/85609122
has comment: http://stackoverflow.com/comment/85609170
accepted answer: http://stackoverflow.com/a/49303937
has comment: http://stackoverflow.com/comment/85609533
type: Question
has title: Retrieving all but one value
answer count: 2
has answer: http://stackoverflow.com/a/49303937
has comment: http://stackoverflow.com/comment/85609201
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49332241
downvote count: 0
has comment: http://stackoverflow.com/comment/85666591
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85666464
has comment: http://stackoverflow.com/comment/85666538
favorite count: 0
has body: I wrote a py file called simplifier. Usually when you double click the py file, Windows should give you both a console and the program. Just like the picture below. However, I clicked my py file and the console showed up and disappeared in a flash and the program did not show up at all. Usually this means there should be some bugs in my code. So I opened the py file in IDLE and ran it, expecting the shell to give me an error. However, it did not report anything. I don't know how to locate the error. The file used to work well and it just started to behave like that. I tested putting "input('')" only in a py file and it worked as expected. And some of my programs also work well, but the rest doesn't. Could the bug come from my imported modules? I import some module written by myself (ez and eztk). I checked those functions. They are ok. Here is the code of simplifier. from tkinter import * from tkinter import messagebox from eztk import * import ez root=Tk() root['bg']='MintCream' t1=Text(root) def newline(): t=gettxt(t1) new='' for i,ch in enumerate(t): if ch=='\n' and t[i+1:i+3]!='- ': new+=' ' else: new+=ch inst2(new) w0=Label(root,text='Input:↑') w1=Button(root,text="\\n",command=newline) def brackets(): t=gettxt(t1) new='' stop=0 d={'[':']','(':')','{':'}',0:None} for ch in t: if ch in d: stop=ch elif ch==d[stop]: stop=0 elif not stop: new+=ch inst2(new) w2=Button(root,text='([{}])',command=brackets) def linecount(event): count=lambda t:t.count('\n')+(t[-1]!='\n') if t else 0 up=count(gettxt(t1)) down=count(gettxt(t2)) w3['text']=f'LineCount:↑{up}↓{down}' root.bind('&lt;KeyPress&gt;', linecount) w3=Label(root,text='LineCount') def clear(): deltxt(t1) deltxt(t2) w4=Button(root,text='Clear',command=clear) t2=Text(root) ws=[w0,w1,w2,w3,w4] t1.grid(row=0,column=0,columnspan=len(ws)) for i,w in enumerate(ws): w.configure(relief=FLAT,bg='SeaGreen1') w.grid(row=1,column=i,sticky=NS) t2.grid(row=2,column=0,columnspan=len(ws)) def inst2(text): deltxt(t2) instxt(t2,text) …
type: Question
tagged with: python-3.x
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/85666555
has comment: http://stackoverflow.com/comment/85666838
type: UnansweredQuestion
tagged with: python
has title: Windows10 Python Program Disappear
has comment: http://stackoverflow.com/comment/85666683
has comment: http://stackoverflow.com/comment/85666750
has comment: http://stackoverflow.com/comment/85666602

http://stackoverflow.com/q/49344443
score: 0
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/49344496
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/49344496
tagged with: dictionary
has title: I'm looking for help on how to export JSON data from an API call to an CSV
answer count: 1
has body: Example of the dictionary returned from the api call. UserList contains the dictionary below. {1: {'Email': 'JohnDoe@email.com', 'FirstName': 'John', 'Id': {'Value': 1}, 'LastName': 'Doe', 'Location': '1', 'UserName': 'JohnDoe'}, 2: {'Email': 'JaneDoe@email.com', 'FirstName': 'Jane', 'Id': {'Value': 2}, 'LastName': 'Doe', 'Location': '2', 'UserName': 'JaneDoe'}, 3: {'Email': 'FredDoe@email.com', 'FirstName': 'Fred', 'Id': {'Value': 1}, 'LastName': 'Doe', 'Location': '3', 'UserName': 'FredDoe'}} Code I'm using to try to export the data. I need to export the data with the keys (UserName, FirstName, LastName) as the headers. The dictionary is saved in the UserList variable. with open('Test.csv', 'w') as f: fieldnames = ['UserName', 'FirstName', 'LastName'] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for data in UserList: writer.writerow([UserList[data][f] for f in fieldnames]) Below is the error I'm getting... Traceback (most recent call last): File "&lt;input&gt;", line 6, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 155, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'list' object has no attribute 'keys'
type: AnsweredQuestion

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

http://stackoverflow.com/q/49347506
favorite count: 0
tagged with: celery
type: Question
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33849715
tagged with: twisted
has body: I have a Django 2.0, Celery 4 and Scrapy 1.5 setup where I have a Spider inside a django custom command and I need to call this command at regular intervals, I use Celery to call these commands and they involve scraping a web page and saving some results to the database. Here are my files: get_data.py class Command(BaseCommand): help = 'Crawl for new data' def handle(self, *args, **options): settings = Settings() settings.setmodule(crawler_settings) process = CrawlerProcess(settings=settings) args = {some needed args} process.crawl(DataLogSpider, kwargs=args) process.start() celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @task() def collect_data_information(): call_command('get_data') (Django) settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BEAT_SCHEDULE = { 'task-get-logs': { 'task': 'core.tasks.collect_data_information', 'schedule': crontab(minute='*/15') # every 15 minutes }, } I've removed some imports and reduced the code for simplicity. The problem is that when I run my celery task, my spider will only execute the first time, the second time I get ReactorNotRestartable error. I understand that the problem comes from the Twisted reactor being restarted more than once, which is not possible. I've already looked into these questions 1, 2, 3 and many others involving the same error, but none of them considered the concurrency problem when using Django to save to the database. When I tried applying their solution to my problem I receive a django.db.utils.OperationalError: SSL error: decryption failed or bad record mac. I've looked that up as well and it is caused by the multiple processes that open a database connection, which is actually hapenning because of their solution. So my question boils down to:…
upvote count: 3
accepted answer: http://stackoverflow.com/a/49448256
answer count: 1
linked to: http://stackoverflow.com/q/39946632
has answer: http://stackoverflow.com/a/49448256
tagged with: scrapy
has title: Django + Celery + Scrapy twisted reactor(ReactorNotRestartable) and database(SSL error) errors
downvote count: 1
linked to: http://stackoverflow.com/q/41495052

http://stackoverflow.com/q/49400752
type: Question
accepted answer: http://stackoverflow.com/a/49510663
has answer: http://stackoverflow.com/a/49510663
answer count: 1
tagged with: pyqt4
type: AnsweredQuestion
score: 0
has body: I do understand there is way using Threads by emplying Qtimer and yes I do want it to update on a real time basis. I have experienced changing of these object Qlcd and Qlabel upon pushing button how ever i want it to update upon itself. Any help would be appreciated.
tagged with: real-time
has title: How to make PYQT gui update upon real time data acquasition? The objects considered being QLCD and Qlabel?
tagged with: python

http://stackoverflow.com/q/49412942
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49413424
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85827998
tagged with: python-3.x
has title: bazel build Error: Cannot locate python.exe
tagged with: windows
accepted answer: http://stackoverflow.com/a/49413424
tagged with: python
tagged with: bazel
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85828266
has body: I'm trying to build bazel using the following approach in mysys64. I found this at tensorflow-mnist-test cd [bazel-dist-dir] pacman -Syuu gcc git curl zip unzip zlib-devel export BAZEL_WRKDIR=c:/tempdir/shrtpath export BAZEL_SH=c:/tools/msys64/usr/bin/bash.exe export BAZEL_VS=c:/Program\ Files\ \(x86\)/Microsoft\ Visual\ Studio\ 14.0 export BAZEL_PYTHON=c:/Python36/python.exe ./compile.sh ./compile.sh compile output/bazel.exe However mysys2 gives an error when I try to compile. It says it cannot locate my python.exe. This is so strange because the file is in the path I provide. Does anybody what is going on here? I also tried the message giving in the error but nothing work. How can I solve this? Master Tk@DESKTOP-BJH5T82 MSYS /C/Users/Master TK/Downloads/tensorflow_compilation/bazel-0.11.1 $ ./compile.sh ERROR: cannot locate python.exe; check your PATH. You may need to run the following command, or something similar, depending on where you installed Python: export PATH="/c/Python27:$PATH"
answer count: 1
has comment: http://stackoverflow.com/comment/85828550

http://stackoverflow.com/q/49282589
has comment: http://stackoverflow.com/comment/85568283
answer count: 1
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49282779
has title: Unable to sore lines of an http-text file in list python 3.5
tagged with: python
type: Question
tagged with: python-3.x
has body: url="https://www.sec.gov/Archives/edgar/data/3662/0000950170-98-000413.txt" data=urllib.request.urlopen(url) list_line=[str(x) for x in data] for line in list_line: line.replace("b'","") line.replace("\\n","") line.replace("\\t","") print (list_line) It is generating list like this: ["b'-----BEGIN PRIVACY-ENHANCED MESSAGE-----\n'", "b'Proc-Type: 2001,MIC-CLEAR\n'", "b'Originator-Name: webmaster@www.sec.gov\n'", "b'Originator-Key-Asymmetric:\n'", "b' MFgwCgYEVQgBAQICAf8DSgAwRwJAW2sNKK9AVtBzYZmr6aGjlWyK3XmZv3dTINen\n'", "b' TWSM7vrzLADbmYQaionwg5sDW3P6oaM5D3tdezXMm7z1T+B+twIDAQAB\n'", "b'MIC-Info: RSA-MD5,RSA,\n'", "b' EvPdKfnjzBIjWkEk2RgNCk1/52qXomHpN+LDwL/XTT/XBuAzk70AYYrsxlQbyiqr\n'", "b' V5559QRyTgPe9PfVt0db9Q==\n'", "b'\n'", "b'0000950170-98-000413.txt : 19980309\n'", "b'0000950170-98-000413.hdr.sgml : 19980309\n'"] &lt;----sample I want to remove b',\n and \t , string split and replace not working, how to do it?
accepted answer: http://stackoverflow.com/a/49282779

http://stackoverflow.com/q/49419720
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49984019
linked to: http://stackoverflow.com/q/44822999
tagged with: python
has title: TypeError: Value passed to parameter 'input' has DataType float64 not in list of allowed values: float16, bfloat16, float32
downvote count: 1
has comment: http://stackoverflow.com/comment/85846245
score: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85852524
answer count: 1
has body: I have read many questions similar to mine, but all of them are different with mine. for itr in xrange(MAX_ITERATION): train_images, train_annotations = train_dataset_reader.next_batch(batch_size) # train_images=tf.image.convert_image_dtype(train_images,np.float32) # train_annotations=tf.image.convert_image_dtype(train_annotations,np.float32) # print(train_images_.get_shape(),train_annotations_.get_shape()) # train_images=tf.cast(train_images,tf.float32) # train_images = tf.to_float(train_images) # train_annotations = tf.to_float(train_annotations) #train_images, train_annotations = py_func(selftrans, [train_images_, train_annotations_], [tf.float32], grad=None) print(train_images.dtype) # train_annotations=tf.cast(train_annotations,tf.float32) # train_images,train_annotations = sess.run([train_images,train_annotations]) # train_images = train_images.astype('float32') # train_annotations = train_annotations.astype('float32') # print(train_annotations.dtype) feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 1} sess.run(train_op, feed_dict=feed_dict) The question is: After I use my own data (vessel segmentation, which is a Two Classification Problems), the data read by using next_batch is float64, while feed_dict() needs float32. Commonly, codes like tf.cast or tf.tp_float can be used to convert my data to float32. However, after using those converting codes, I found the error changed to TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles. Finally, I tried to use sess.run to off-set its tf.Tensor form. Erorr changed to the original one, which means my data was converted back to float64. Thus, it seems to be an endless loop. "Without converting, float64 will not be accepted. After converting, Tf. Tensor will also not be accepted. To off-set the tf.Tensor form using sess run, data will be converted back to float64 simultaneously" How …
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: image-segmentation
upvote count: 3

http://stackoverflow.com/comment/85716173
type: QuestionComment
comment on: http://stackoverflow.com/q/49357735
has text: You'll have to close and open the file each time you want to get updated results.
score: 0
type: Comment

http://stackoverflow.com/comment/85631881
comment on: http://stackoverflow.com/q/49294222
type: QuestionComment
score: 0
has text: This is one of the most dreaded features of most languages created in the '90s. why would you want to bring it back?
type: Comment

http://stackoverflow.com/a/49409915
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85838235
answers question: http://stackoverflow.com/q/49365376
downvote count: 0
has body: If you got your response with the following query: https://$ACCOUNT.cloudant.com/$DATABASE/_design/$DDOC/_search/$INDEX_NAME?limit=200 You would get the next 200 rows with this query: https://$ACCOUNT.cloudant.com/$DATABASE/_design/$DDOC/_search/$INDEX_NAME?limit=200&amp;bookmark="g1AAAAJveJzLYWBg4MhgTmHQTElKzi9KdUhJMtRLytVNTtYtLdYtzi8tydA1MNRLzskvTUnMK9HLSy3JAWphSmRIkv___39WBpOb_QcGMEhkRjXHnBhzkhSAZJI9ulFMIKO0EE4iyk1JDiCz4gmZZUCUWQkgs-qxmkViUOWxgLQ2ACmgafPxGUdUiEGMWwAxbj_loQYx7wDEvPuUhxzEvAcQ89BCLwsAMoq9cQ" To get all the documents for your query, write a function that recursively queries the database with the bookmark value coming from the previous response each time. Do this until your response has less than 200 documents, which is how you know you're done. Full documentation on querying a Cloudant search index is here: https://console.bluemix.net/docs/services/Cloudant/api/search.html#queries
score: 1

http://stackoverflow.com/q/49309670
type: AnsweredQuestion
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/85622421
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85622965
has comment: http://stackoverflow.com/comment/85623521
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49311033
has comment: http://stackoverflow.com/comment/85622749
has title: Example from NetworkX documentation gets an error (all_pairs_shortest_path)
tagged with: python
has answer: http://stackoverflow.com/a/49310581
possible better answer: http://stackoverflow.com/a/49310581
has body: I tried to copy and paste an example from NetworkX package documentation. This is the example: &gt;&gt;&gt;G = nx.path_graph(5) &gt;&gt;&gt; path = nx.all_pairs_shortest_path(G) &gt;&gt;&gt; print(path[0][4]) [0, 1, 2, 3, 4] Unfortunately, instead of the expected output, I get the following error message: 'generator' object has no attribute '__getitem__'
tagged with: networkx
accepted answer: http://stackoverflow.com/a/49311033

http://stackoverflow.com/comment/85676870
has text: @Bugs_Bunny - But I notice another problem. (I am not finacial guy, so not sure if understand it correct) so you need yearly fluctation. It means need `std` per months in each year? If yes, solution is correct.
score: 1
comment on: http://stackoverflow.com/a/49338065
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49298731
type: Answer
upvote count: 2
has body: Splitting using : and creating a dataframe with each of the split as separate column values. import pandas as pd d = {0: '09:30:38', 1: '13:40:27', 2: '18:05:24', 3: '04:58:08', 4: '09:00:09'} df = pd.DataFrame([v.split(':') for v in d.values()], columns=['hour', 'minute', 'second']) print(df) Result: hour minute second 0 09 30 38 1 13 40 27 2 18 05 24 3 04 58 08 4 09 00 09
downvote count: 0
answers question: http://stackoverflow.com/q/49298488
score: 2
has comment: http://stackoverflow.com/comment/113204865

http://stackoverflow.com/q/49338302
downvote count: 0
has answer: http://stackoverflow.com/a/49454182
favorite count: 0
type: Question
has title: Django - Form across multiple views with progress saving
has answer: http://stackoverflow.com/a/49385129
score: 9
upvote count: 9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88994382
tagged with: django
tagged with: python
has body: I'm working on a Django project and to make the forms experience far smoother I want to spread a ModelForm across a few pages. It would be ideal if users who are logged in can save their progress in the form without actually posting the content (in this case, a JobApplication where users can come back to filling in info without actually sending off the application). Currently I have looked at other answers on SO such as this one; but this only shows me how to utilise caching to store information between the views where the form is present. Models.py (models, forms and views have been simplified for readability): class JobApplication(models.Model): job = models.ForeignKey(JobPost,on_delete=models.SET_NULL,...) user = models.ForeignKey(AUTH_USER_MODEL,...) details = models.CharField(max_length=300) skills = models.CharField(max_length=300) feedback = models.CharField(max_length=300) #... [insert more fields] ... Forms.py: class Application(forms.ModelForm): details = forms.CharField() # To go in page 1 of the form process skills = forms.CharField() # To go in page 2 feedback = forms.CharField() # To go in page 3 class Meta: model = JobApplication fields = ['details','skills','feedback'] Views.py: from . import forms def view1(request): form = forms.Application() if request.method == 'POST': form = forms.Application(data=request.POST) ... some logic here which I am not sure of ... return render(request, 'view1.html', {}) def view2(request): form = forms.Application() if request.method == 'POST': form = forms.Application(data=request.POST) ... return render(request, 'view2.html', {}) def view3(request): form = forms.Application() if request.method == 'POST': form = forms.Application(data=request.POST) ... return render(request, 'view3.html', {}) Note that I'm happy to edit my forms or models to achieve this multi-page, save progress effect that you may see on job sites. Let me know if there's any more code I can add that will be useful, since I'm not too sure what else …
has comment: http://stackoverflow.com/comment/88923306
has comment: http://stackoverflow.com/comment/88994436
has answer: http://stackoverflow.com/a/49508982
answer count: 3
linked to: http://stackoverflow.com/q/14901680
has comment: http://stackoverflow.com/comment/89013028

http://stackoverflow.com/q/49417531
has body: How do I unit test my script for incorrect command line arguments? For example, my_script.py -t should give an error since -t flag is not present, as shown in the code below: parser = OptionParser() parser.add_option("-d", action="callback", callback=get_bios_difference, help="Check difference between two files" ) (options, args) = parser.parse_args() if len(sys.argv) == 1: # if only 1 argument, it's the script name parser.print_help() exit()
tagged with: unit-testing
favorite count: 0
has answer: http://stackoverflow.com/a/49417643
score: 2
tagged with: optionparser
has title: unittest for command line arguments
type: Question
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49418610

http://stackoverflow.com/q/49435865
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49436340
has comment: http://stackoverflow.com/comment/85873707
tagged with: python
has body: I have two different dataframes populated with different name sets. For example: t1 = pd.DataFrame(['Abe, John Doe', 'Smith, Brian', 'Lin, Sam', 'Lin, Greg'], columns=['t1']) t2 = pd.DataFrame(['Abe, John', 'Smith, Brian', 'Lin, Sam', 'Lu, John'], columns=['t2']) I need to find the intersection between the two data sets. My solution was to split by comma, and then groupby last name. Then I'll be able to compare last names, and then see if the first names of t2 are contained within t1. ['Lu, John'] is the only one that should be returned in above example. What I need help on is how to compare values within two different dataframes that are grouped by a common column. Is there a way to intersect the results of a groupby for two different dataframes and then compare the values within each key value pair? I need to extract the names in t2 that are not in t1. I have an idea that it should look something like this: for last in t1: print(t2.get_group(last)) #BUT run a compare between the two different lists here Only problem is if the last name doesn't exist in the second groupby, it throws an error, so I can't even proceed to the next step mentioned by the comment, of comparing the values in the groups (first names).
has comment: http://stackoverflow.com/comment/85874089
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49436340
tagged with: pandas
has comment: http://stackoverflow.com/comment/85873749
has comment: http://stackoverflow.com/comment/85873611
accepted answer: http://stackoverflow.com/a/49452386
has answer: http://stackoverflow.com/a/49452386
has title: How do you compare the values in two different dataframe groupby results?

tkinter
tags question: http://stackoverflow.com/q/49350388
tags question: http://stackoverflow.com/q/49439734
tags question: http://stackoverflow.com/q/49324850
tags question: http://stackoverflow.com/q/49323339
tags question: http://stackoverflow.com/q/49332259
tags question: http://stackoverflow.com/q/49307497
tags question: http://stackoverflow.com/q/49311773
tags question: http://stackoverflow.com/q/49341343
tags question: http://stackoverflow.com/q/49375176
tags question: http://stackoverflow.com/q/49382761
tags question: http://stackoverflow.com/q/49407991
tags question: http://stackoverflow.com/q/49348727
tags question: http://stackoverflow.com/q/49321095
tags question: http://stackoverflow.com/q/49432915
tags question: http://stackoverflow.com/q/49334436
tags question: http://stackoverflow.com/q/49331686
tags question: http://stackoverflow.com/q/49302176
tags question: http://stackoverflow.com/q/49397720
tags question: http://stackoverflow.com/q/49410785
tags question: http://stackoverflow.com/q/49344575
tags question: http://stackoverflow.com/q/49315276
tags question: http://stackoverflow.com/q/49279580
tags question: http://stackoverflow.com/q/49360545
tags question: http://stackoverflow.com/q/49314702
tags question: http://stackoverflow.com/q/49382628
tags question: http://stackoverflow.com/q/49371500
tags question: http://stackoverflow.com/q/49340971
tags question: http://stackoverflow.com/q/49327456
tags question: http://stackoverflow.com/q/49359550
tags question: http://stackoverflow.com/q/49431740
tags question: http://stackoverflow.com/q/49284124
tag name: tkinter
tags question: http://stackoverflow.com/q/49369364
tags question: http://stackoverflow.com/q/49396207
tags question: http://stackoverflow.com/q/49297302
tags question: http://stackoverflow.com/q/49294578
tags question: http://stackoverflow.com/q/49352249
tags question: http://stackoverflow.com/q/49344762
tags question: http://stackoverflow.com/q/49409827
tags question: http://stackoverflow.com/q/49300636
tags question: http://stackoverflow.com/q/49301489
tags question: http://stackoverflow.com/q/49313841
tags question: http://stackoverflow.com/q/49342383
tags question: http://stackoverflow.com/q/49427936
tags question: http://stackoverflow.com/q/49292397
tags question: http://stackoverflow.com/q/49313874
tags question: http://stackoverflow.com/q/49335297
tags question: http://stackoverflow.com/q/49371147
tags question: http://stackoverflow.com/q/49422041
tags question: http://stackoverflow.com/q/49287073
tags question: http://stackoverflow.com/q/49304262
tags question: http://stackoverflow.com/q/49374585
tags question: http://stackoverflow.com/q/49297194
tags question: http://stackoverflow.com/q/49334408
tags question: http://stackoverflow.com/q/49420379
tags question: http://stackoverflow.com/q/49290523
tags question: http://stackoverflow.com/q/49338888
tags question: http://stackoverflow.com/q/49347300
tags question: http://stackoverflow.com/q/49412451
tags question: http://stackoverflow.com/q/49308962
tags question: http://stackoverflow.com/q/49332241
tags question: http://stackoverflow.com/q/49370592
tags question: http://stackoverflow.com/q/49281416
tags question: http://stackoverflow.com/q/49299145
tags question: http://stackoverflow.com/q/49364713
tags question: http://stackoverflow.com/q/49411359
tags question: http://stackoverflow.com/q/49417737
tags question: http://stackoverflow.com/q/49370745
tags question: http://stackoverflow.com/q/49433315
tags question: http://stackoverflow.com/q/49364677
tags question: http://stackoverflow.com/q/49290330
tags question: http://stackoverflow.com/q/49313223
tags question: http://stackoverflow.com/q/49288164
tags question: http://stackoverflow.com/q/49416122
tags question: http://stackoverflow.com/q/49323582
tags question: http://stackoverflow.com/q/49353671
tags question: http://stackoverflow.com/q/49285466
tags question: http://stackoverflow.com/q/49286100
tags question: http://stackoverflow.com/q/49388200
type: Tag

http://stackoverflow.com/a/49421409
has comment: http://stackoverflow.com/comment/85844127
score: -1
has comment: http://stackoverflow.com/comment/85843830
type: Answer
answers question: http://stackoverflow.com/q/49421228
has comment: http://stackoverflow.com/comment/85844182
has body: You can check the intersection of each sublist with rest of the elements of list, if all of the intersections are empty then the element is not repeated &gt;&gt;&gt; d = [[1,2,3], [4,5], [1,2], [6,7]] &gt;&gt;&gt; [a for a in d if all(len(set(a) &amp; set(b)) == 0 for b in d if b!=a)] &gt;&gt;&gt; [[4, 5], [6, 7]]
has comment: http://stackoverflow.com/comment/85843741
downvote count: 1
upvote count: 0

http://stackoverflow.com/q/49364196
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49364246
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49364395
tagged with: python
has answer: http://stackoverflow.com/a/49364453
has body: I have a nested tuple in the form: nested_tup = [('15MAR18 103000', '15MAR18 103758'), ('15MAR18 120518', '15MAR18 121308')] etc... The 1st element in each tuple is the start date and the 2nd element in each tuple is the end date. I want to find the difference in time between the 2 dates and then append the answer as a 3rd element in each tuple... So far I have the following: for start, end in nested_tup: after = datetime.strptime(end, '%d%b%y %H%M%S') before = datetime.strptime(start, '%d%b%y %H%M%S') duration = after - before I need this duration value to be appended as the 3rd element in each tuple.. I don't know how though.. Any help appreciated.
tagged with: python-2.7
score: 0
answer count: 3
tagged with: datetime
has comment: http://stackoverflow.com/comment/85728851
has title: Adding values to end of a nested tuple

http://stackoverflow.com/comment/85742022
has text: Thanks by explanation. I was thinking the `on_message` was used by any feedback from the `server`. So, our publish operations do not have answers from server, right? How do we know if the operations were succeeded? Yet, how can I see the values sent to specific topics?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49329172

http://stackoverflow.com/comment/85581749
type: Comment
type: QuestionComment
score: 0
has text: Of course you can do this in Python. The easiest way, just as in most other languages, is to pick a web services framework (probably a lightweight one like Flask, rather than something like Django, but you can use whatever you like). But it's only slightly more complicated to use a raw HTTP server like the one in the stdlib and code up a hook to run a function for a given endpoint.
comment on: http://stackoverflow.com/q/49289262

http://stackoverflow.com/q/49305858
duplicate of: http://stackoverflow.com/q/48267633
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85614416
tagged with: selenium
has body: i use python 3.6.4 and install selenium with pip command pip install -U selenium when i use a simple code like this from selenium import webdriver browser = webdriver.Firefox() browser.get('http://seleniumhq.org/') i get error: from selenium.firefox.webdriver import WebDriver ImportError: No module named 'selenium.firefox' i download chromedriver.exe and add this path to system environment bot not working how can i fix this problem?
has comment: http://stackoverflow.com/comment/85614012
has comment: http://stackoverflow.com/comment/85615767
linked to: http://stackoverflow.com/q/45584241
type: Question
has comment: http://stackoverflow.com/comment/85614440
linked to: http://stackoverflow.com/q/48267633
duplicate of: http://stackoverflow.com/q/45584241
has comment: http://stackoverflow.com/comment/85631499
has comment: http://stackoverflow.com/comment/85614369
tagged with: python
has title: python not recognize webdriver firefox&chrome
tagged with: webdriver

http://stackoverflow.com/comment/85634630
has text: i can only change code in place where #write your code here comment is
comment on: http://stackoverflow.com/a/49308630
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49419797
upvote count: 1
tagged with: unique
favorite count: 0
has answer: http://stackoverflow.com/a/49419844
type: Question
has body: I need to match a string with specific letters but none of the letters should be duplicated. For example, [AEIOU] should not match 'AAEIOU' or 'AAEEIOU'. It should only match 'AEIOU' and the order of the letters should not matter. I tried using the exact quantifier with {} but did not work.
possible better answer: http://stackoverflow.com/a/49419839
has title: Python regex to match multiple unique values
tagged with: python
accepted answer: http://stackoverflow.com/a/49419844
tagged with: regex
type: AnsweredQuestion
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/85841052
has answer: http://stackoverflow.com/a/49419924
downvote count: 0
has answer: http://stackoverflow.com/a/49419839
has comment: http://stackoverflow.com/comment/85841060

http://stackoverflow.com/comment/85685018
comment on: http://stackoverflow.com/q/49338837
type: Comment
score: 0
type: QuestionComment
has text: Not 100% sure but is it possible that the `image` and `label` that you pass as inputs to `generate_input_fn` are tensors? If this is the case, then they will not be from the same graph as the rest and will cause the error.

http://stackoverflow.com/q/49353078
has comment: http://stackoverflow.com/comment/85706903
has comment: http://stackoverflow.com/comment/85706997
has body: I have a spark dataframe and I want to process each sentence(lower, remove punctuation) of each line. To be more specific: |text | +--------------------------------+ | This is a text.I want to split! +--------------------------------- And I want to get this dataframe: |text | +--------------------------------- | [this is text ][i want to split] +---------------------------------
type: Question
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/85706554
type: UnansweredQuestion
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85706718
tagged with: python
linked to: http://stackoverflow.com/q/39235704
score: 0
has title: Stemming each sentence, of each row of Spark dataframe
tagged with: apache-spark
answer count: 0
duplicate of: http://stackoverflow.com/q/39235704
has comment: http://stackoverflow.com/comment/85706618
has comment: http://stackoverflow.com/comment/85706971
has comment: http://stackoverflow.com/comment/85706750

http://stackoverflow.com/comment/85668420
has text: They wouldn't be calculated with any of the existing columns. It be the max/min/average `duration` across all instances of consecutive geohash.
comment on: http://stackoverflow.com/q/49333312
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85785415
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49391589
type: Comment
has text: see amended ans- using a nested for loop. You may choose to write to the file but I think it is better (for several reasons) to write at the end- otherwise it'll slow up the program a lot

http://stackoverflow.com/q/49363505
answer count: 0
score: 1
has title: Check if value obtained from equation slightly wrong because of double precision limitation?
favorite count: 0
tagged with: precision
type: Question
type: UnansweredQuestion
has body: I calculate an algorithm which operates some big matrices together. The result of 25 iterations is 43094433924714.60 42305389712997.10 42051869142057.30 41857066081162.10 41709555393330.50 41567289549908.10 41445508409456.40 41351519393007.90 41285939671446.50 41246739458582.20 41227637000953.50 41221374361160.30 41222070832734.30 41225683762693.20 41229940202366.40 41234197403025.10 41238259341968.60 41242214489820.80 41246250974730.60 41250072955515.30 41253409784178.00 41256148996999.60 41258526183343.50 41260749335391.20 41262757761836.80 I found it is weird as I expect them to be monotonically decreased. I try to find the reason and realize these numbers are 14 exponents with 2 mantissa which is more than double-precision format. How can I check if this weird trend comes from just wrong calculation in python? The equation and simplified data example is down below: from __future__ import division import numpy as np from scipy.sparse import rand eps = 1e-6 matrix = rand(5000, 1300, density=0.25, format="csr")*1e7 V = matrix.todense() + (np.random.rand(5000,1300) + 1.0) W = np.zeros((5000, 100), int) + eps np.fill_diagonal(W, 1, wrap=True) W = np.dot(W,np.diag(1/sum(W))) H = np.random.rand(W.shape[1],V.shape[1]) + 1.0 ONES = np.ones(shape=(V.shape[0],V.shape[1])) cost = [] for it in range(25): Wt = W.conj().T H = np.multiply((H / np.dot(Wt,ONES)),(np.dot(Wt,(V/(np.dot(W,H)+eps))))) cost.append(np.sum(np.multiply(V,np.log(V/(np.dot(W,H)+eps))) - V + np.dot(W,H)) + np.sum(H)) print cost Is it possible to use decimal() to proof (for very accurate calculation) just at the end? I think it should have some better ways.
downvote count: 0
upvote count: 1
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/comment/85685706
has text: Off course you can put additional informations into your question. However, take care to only post the interesting part of your code (not all your code if it is long).
score: 0
comment on: http://stackoverflow.com/q/49333206
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49306430
type: Question
has answer: http://stackoverflow.com/a/49308400
has comment: http://stackoverflow.com/comment/85617804
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85615167
tagged with: python
has body: I've opened the csv file (600mb) by df=pd.read_csv(file) It is quite big so I've reduced memory usage from : It works in Jupter Notebook and shows: I've changed types : float64 ---&gt; float32, object ----&gt; category, int ------&gt; uint16, uint8, like this(e.g for object): converted_obj = pd.DataFrame() for col in df_obj.columns: num_unique_values = len(df_obj[col].unique()) num_total_values = len(df_obj[col]) if num_unique_values / num_total_values &lt; 0.5: converted_obj.loc[:,col] = df_obj[col].astype('category') else: converted_obj.loc[:,col] = df_obj[col] optimized_df[converted_obj.columns] = converted_obj optimized_df.info() Now, I want to export reduced DataFrame to csv, but after I am doing it, the file sized increased to over 800mb(before - 600mb). When I am reading the new file to Jupyter Notebook the dtypes are the same as before reduction and the same thing with memory usage (1,6 GB+). What am I doing wrong ? How to extract the reduced csv ? Thanks in advance.
score: 0
tagged with: pandas
tagged with: types
answer count: 1
has title: Cannot export csv with to_csv after reducing memory usage
tagged with: data-science

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

http://stackoverflow.com/a/49325066
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85777751
answers question: http://stackoverflow.com/q/49323696
score: 2
type: Answer
has body: As you syntax looks right now, it will run on a variable-by-variable basis. You are submitting/running the RENAME VARIABLES command as many times as the number of variables in your list. On one hand, this is in-efficient, as it takes longer to run than what I am suggesting below. On the other (and more important) hand, doing it variable by variable, does not guard against duplicate variables. I am guessing that you already have in your datafile a variable named dg_mnpfs, and you are attempting to create a new one by renaming v23_1_dg_mnpfs. Just check your datafile, after your python code breaks. A more efficient way of writing you code would be to create lists with the old names, and new names, and submit the syntax with only one command. begin program. import spss,spssaux vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) my_new_list=[] for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") my_new_list.append(mynewvar) my_syntax="ren var (" + " ".join(mylist) + "=" + " ".join(my_new_list) +")." spss.Submit(my_syntax) end program. And one more thing: the strip function removes the text from both ends of the variables. If you only want to remove the prefix, consider using lstrip. Details can be found here, in the official documentation.
has comment: http://stackoverflow.com/comment/85766762
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49323696

http://stackoverflow.com/q/49392845
has answer: http://stackoverflow.com/a/59900858
has comment: http://stackoverflow.com/comment/85787318
favorite count: 0
has comment: http://stackoverflow.com/comment/103779047
has body: Why does it say that it can not find my class? Why should I create another class with the same name in order to make make it not complain? from typing import Dict class WeekDay: def __init__(self, day_number, day_name): self.day_name = day_name self.day_number = day_number @staticmethod def get_week_days() -> Dict[str, WeekDay]: # WeekDay unresolved reference error weekdays = { "monday": WeekDay(1, "Monday"), "tuesday": WeekDay(2, "Tuesday"), "wednesday": WeekDay(3, "Wednesday"), "thursday": WeekDay(4, "Thursday"), "friday": WeekDay(5, "Friday"), "saturday": WeekDay(6, "Saturday"), "sunday": WeekDay(7, "Sunday") } return weekdays
upvote count: 30
type: Question
has title: Python parameter annotations unresolved reference
tagged with: python-typing
has answer: http://stackoverflow.com/a/49392996
linked to: http://stackoverflow.com/q/33533148
score: 30
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49393116
possible better answer: http://stackoverflow.com/a/59900858
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/49393116
tagged with: python

http://stackoverflow.com/comment/85627767
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49313012
has text: I see a recursive function call and a list comprehension, but no backtracking. Backtracking involved a tree to search and there's non.
type: QuestionComment

http://stackoverflow.com/a/78731434
score: -1
answers question: http://stackoverflow.com/q/49284893
upvote count: 0
downvote count: 1
has body: I solved this by adding this line matplotlib.use('module://backend_interagg'). None of the other backend options worked for me.
type: Answer

http://stackoverflow.com/a/49426386
accepted answer of: http://stackoverflow.com/q/49426315
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49426315
type: AcceptedAnswer
has body: You can use an aggregation and order by that. from django.db.models import Count Article.objects.annotate(site_count=Count('site')).order_by('site_count')
type: Answer

http://stackoverflow.com/comment/85761197
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49378849
score: 1
has text: https://stackoverflow.com/questions/11232230/logging-to-two-files-with-different-settings

http://stackoverflow.com/a/49360136
type: Answer
answers question: http://stackoverflow.com/q/49359474
score: 0
has comment: http://stackoverflow.com/comment/85735019
has body: You can simply check , Will this work ? def checker(list_): check={} temp = [] for m, n in enumerate(list_): try: if list_[m] &lt; list_[m + 1]: temp.append('Increasing') else: temp.append('Decreasing') except IndexError: pass check[temp.count('Increasing')] = 1 check[temp.count('Decreasing')] = 0 return check[max(check)] test_Case 1: print(checker([5.0, 6.0, 9.0, 4.0, 10.0])) output: 1 test_Case 2 print(checker([6.0, 4.0, 5.0, 4.0, 3.0])) output: 0
has comment: http://stackoverflow.com/comment/85731113
has comment: http://stackoverflow.com/comment/85728659

http://stackoverflow.com/comment/85740037
score: 1
comment on: http://stackoverflow.com/q/49369163
type: Comment
type: QuestionComment
has text: Defining specific subclasses of `DataException` seems more Pythonic than effectively just wrapping instances around `mapper.get`. Cf. the various [subclasses of `OSError`](https://docs.python.org/3/library/exceptions.html#os-exceptions) in Python 3, which previously were different *instances* of `OSError` distinguished by their `errno` attributes.

http://stackoverflow.com/comment/85584014
score: 0
type: AnswerComment
has text: Wow that's incredible. It's a little too complicated for me to understand, though. What does the temp.extend do? The code works exactly like I need it to.
comment on: http://stackoverflow.com/a/49290453
type: Comment

http://stackoverflow.com/comment/85632261
comment on: http://stackoverflow.com/q/49314500
type: QuestionComment
has text: sorry, I meant: have a look at the format of "frame" in both applications and find the differences. You probably can't expect that VideoStream and cv2.VideoCapture deliver images with the same properties/format.
score: 1
type: Comment

http://stackoverflow.com/comment/85690555
type: QuestionComment
comment on: http://stackoverflow.com/q/49344715
type: Comment
score: 0
has text: @AaweshManShrestha Probability is a form of weight, so yes.

http://stackoverflow.com/a/49397821
answers question: http://stackoverflow.com/q/49397704
has body: This should work and be quite efficient: a = np.array([1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0]) a0 = a==0 np.where(a0[:-3] &amp; a0[1:-2] &amp; a0[2:-1] &amp; a0[3:]) (array([6, 12], dtype=int64),) # indices of first of 4 consecutive 0's
type: Answer
score: 0

http://stackoverflow.com/comment/85850402
comment on: http://stackoverflow.com/q/49424274
type: QuestionComment
score: 0
has text: @Jean-FrançoisFabre Is [this](https://stackoverflow.com/questions/34725117/python-existing-file-not-found-ioerror-errno-2-with-openpyxl) good enough?
type: Comment

http://stackoverflow.com/comment/85580753
has text: Also, I think you could probably just iterate through the cursor without using `.fetchall()`. After that I have no familiarity with `Clob` to say whether you could get around using `json.loads()` on each row.
score: 0
comment on: http://stackoverflow.com/q/49288724
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49377086
has comment: http://stackoverflow.com/comment/85755242
type: Answer
has body: If you want to handle it, each one should easily consider the drawing independently, and that is what I proposed in my previous answer. In the following example we use a layout to locate it and use the ids to access the values. from kivy.app import App from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout root = Builder.load_string(""" &lt;WaterFill@Widget&gt;: level: 0 color: 0, 0, 1 canvas: StencilPush Ellipse: pos: root.pos size: root.size StencilUse Color: rgb: root.color Rectangle: pos: root.pos size: (root.width, root.level*root.height) StencilUnUse StencilPop &lt;FloatLayout&gt;: WaterFill: id: left level: 0.4 pos_hint: {'x' : 0.10, 'y': 0.4} size_hint: 0.4, 0.4 WaterFill: id: right pos_hint: {'x' : 0.55, 'y': 0.4} size_hint: 0.4, 0.4 Button: id: button text: 'text' size_hint: .25, .25 on_press: root.press_me() """) class Principal(FloatLayout): def press_me(self): current_level = self.ids["right"].level self.ids["right"].level = 0.0 if current_level &gt;= 1.0 else current_level + 1.0/9 class TestApp(App): def build(self): return Principal() if __name__ == "__main__": TestApp().run() Note: I recommend reading about the kivy language, how the design of the .kv is linked with the .py
accepted answer of: http://stackoverflow.com/q/49357315
has comment: http://stackoverflow.com/comment/85797705
has comment: http://stackoverflow.com/comment/85755187
has comment: http://stackoverflow.com/comment/85797613
has comment: http://stackoverflow.com/comment/85797824
has comment: http://stackoverflow.com/comment/85755141
has comment: http://stackoverflow.com/comment/85798672
has comment: http://stackoverflow.com/comment/85797439
has comment: http://stackoverflow.com/comment/85755290
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85755048
has comment: http://stackoverflow.com/comment/85780953
has comment: http://stackoverflow.com/comment/85755117
has comment: http://stackoverflow.com/comment/85797917
answers question: http://stackoverflow.com/q/49357315
score: 0
has comment: http://stackoverflow.com/comment/85797484
has comment: http://stackoverflow.com/comment/85755085
has comment: http://stackoverflow.com/comment/85797924

http://stackoverflow.com/comment/85630703
has text: It sounds like your button might be submitting the form after running `create_table()`. So it runs `create_table()` then a split second later the post of the form causes your browser to get a response and the whole page is re-rendered. That would explain why you see the data flash for a split second before disappearing again
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49314528

http://stackoverflow.com/q/49417323
type: UnansweredQuestion
tagged with: python
has body: Lately, I installed Anaconda on a Windows 8 machine in order to install pytorch. I have a i7 intel processor with 4 cores, using python 3.6. Whenever I try to set mkl.set_num_threads to 4 or generally more than 3, the mkl.get_max_threads is capped at 2. I already tried reinstalling everything, using the MKL_NUM_THREADS env variable, Installing numpy by myself using this ,and many other suggestions with no luck. Needless to say, using low number of cores leads to very slow performance. Hope you guys can help :)
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/85841991
answer count: 1
has title: MKL threads capped using anaconda
downvote count: 1
has comment: http://stackoverflow.com/comment/85842904
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49424409

http://stackoverflow.com/comment/85860577
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49408445
has text: age = 65 >>> retirement = 65 - 1 >>> if retirement < 1: print ("okay") else: Syntax Error
type: Comment

http://stackoverflow.com/a/49306346
answers question: http://stackoverflow.com/q/49306155
has comment: http://stackoverflow.com/comment/85615072
upvote count: 2
downvote count: 0
type: Answer
has body: The colors within Fore are not AnsiFore objects, as you said in your question. They're just strings, so they also don't have an AnsiFore property. &gt;&gt;&gt; dir(Fore) ['BLACK', 'BLUE', 'CYAN', 'GREEN', 'LIGHTBLACK_EX', 'LIGHTBLUE_EX', 'LIGHTCYAN_EX', 'LIGHTGREEN_EX', 'LIGHTMAGENTA_EX', 'LIGHTRED_EX', 'LIGHTWHITE_EX', 'LIGHTYELLOW_EX', 'MAGENTA', 'RED', 'RESET', 'WHITE', 'YELLOW', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] The best you can probably do here is: &gt;&gt;&gt; colors = [i for i in dir(Fore) if not i.startswith('_')] &gt;&gt;&gt; colors ['BLACK', 'BLUE', 'CYAN', 'GREEN', 'LIGHTBLACK_EX', 'LIGHTBLUE_EX', 'LIGHTCYAN_EX', 'LIGHTGREEN_EX', 'LIGHTMAGENTA_EX', 'LIGHTRED_EX', 'LIGHTWHITE_EX', 'LIGHTYELLOW_EX', 'MAGENTA', 'RED', 'RESET', 'WHITE', 'YELLOW'] If you want, have a look at the module source. The colors are strings created by: A number (Black = 30) Taking the str representation of this int, prepending it with '\033[', and appending m to it: I.e.: &gt;&gt;&gt; BLACK = 10 &gt;&gt;&gt; CSI = '\033[' ... &gt;&gt;&gt; def code_to_chars(code): ... return CSI + str(code) + 'm' ... &gt;&gt;&gt; code_to_chars(BLACK) '\x1b[10m'
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49306155
has comment: http://stackoverflow.com/comment/85615017
has comment: http://stackoverflow.com/comment/85615045

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

http://stackoverflow.com/comment/85846052
has text: i have already fitted the model and pickled it to a .sav file . i am then loading it to predict in the above code
type: AnswerComment
comment on: http://stackoverflow.com/a/49422704
score: 0
type: Comment

http://stackoverflow.com/comment/85825906
comment on: http://stackoverflow.com/q/49411990
score: 0
type: Comment
type: QuestionComment
has text: @JoranBeasley this is python.

http://stackoverflow.com/a/56419413
has body: if (len( face_recognition.face_encodings( image_to_be_matched))&gt; 0): print("face found in image!") '''continue''' else: print('Face Not found') '''Do Something Else or repeat capture''' #I think this Will help You!
answers question: http://stackoverflow.com/q/49401581
type: Answer
score: 0

http://stackoverflow.com/comment/85678847
comment on: http://stackoverflow.com/q/49339067
score: 0
type: Comment
has text: "You generally don't" is still the case. Almost all of the tools for this just bundle the Python interpreter, your original script, and that script's library dependencies *into* one big, slow-to-start executable.
type: QuestionComment

http://stackoverflow.com/q/49323426
duplicate of: http://stackoverflow.com/q/1871524
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49323768
tagged with: dictionary
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49324225
has body: I am currently trying to turn this list of dictionaries [ {'John Guy': [28, '03171992', 'Student']}, {'Bobby Jones': [22, '02181982', 'Student']}, {'Claire Eubanks': [18, '06291998', 'Student']}, ] into a csv file but with a header that includes Name, Age, Date of Birth, and Occupation. Does anyone have any ideas? I can't seem to make it work with the csv writer. Thank you.
downvote count: 2
has title: Turning a list full of dictionaries into a csv file in Python
upvote count: 1
linked to: http://stackoverflow.com/q/1871524
favorite count: 0
has answer: http://stackoverflow.com/a/49323769
has comment: http://stackoverflow.com/comment/85648172
tagged with: list
answer count: 3

http://stackoverflow.com/comment/85704930
comment on: http://stackoverflow.com/a/49352374
has text: You are a saviour. Thanks a bunch. Its printing in a new line though , Can I print in the same line ?
type: Comment
score: 0
type: AnswerComment

label
tags question: http://stackoverflow.com/q/49423347
tag name: label
tags question: http://stackoverflow.com/q/49432583
type: Tag
tags question: http://stackoverflow.com/q/49297316

http://stackoverflow.com/q/49414841
has answer: http://stackoverflow.com/a/74068697
has answer: http://stackoverflow.com/a/78889503
has answer: http://stackoverflow.com/a/67249271
has answer: http://stackoverflow.com/a/56327194
tagged with: python-3.5
has answer: http://stackoverflow.com/a/71605829
has body: I'm trying to execute a Python script, but I am getting the following error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I'm using python 3.5.2 on a Linux Mint 18.1 Serena OS Can someone tell me why this happens, and how can I solve?
linked to: http://stackoverflow.com/q/64841082
downvote count: 0
has answer: http://stackoverflow.com/a/72864743
has title: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
has answer: http://stackoverflow.com/a/64355193
answer count: 24
accepted answer: http://stackoverflow.com/a/49414907
has answer: http://stackoverflow.com/a/53394314
has answer: http://stackoverflow.com/a/78849366
favorite count: 0
has answer: http://stackoverflow.com/a/53961885
type: Question
has answer: http://stackoverflow.com/a/71779376
has answer: http://stackoverflow.com/a/69740900
has answer: http://stackoverflow.com/a/49414907
linked to: http://stackoverflow.com/q/54273050
has answer: http://stackoverflow.com/a/59506367
linked to: http://stackoverflow.com/q/70483839
has answer: http://stackoverflow.com/a/77146406
has answer: http://stackoverflow.com/a/65831131
tagged with: segmentation-fault
tagged with: python
has answer: http://stackoverflow.com/a/71857831
has answer: http://stackoverflow.com/a/71856384
has answer: http://stackoverflow.com/a/75623448
has answer: http://stackoverflow.com/a/77146820
score: 89
tagged with: linux-mint
has answer: http://stackoverflow.com/a/69196192
has answer: http://stackoverflow.com/a/64824887
upvote count: 89
has answer: http://stackoverflow.com/a/78207198
possible better answer: http://stackoverflow.com/a/56327194
has answer: http://stackoverflow.com/a/59498385
type: AnsweredQuestion

http://stackoverflow.com/comment/85857719
type: Comment
comment on: http://stackoverflow.com/a/49414489
type: AnswerComment
score: 0
has text: Thanks for your help

pip
tags question: http://stackoverflow.com/q/49352751
tags question: http://stackoverflow.com/q/49286763
tags question: http://stackoverflow.com/q/49396554
tags question: http://stackoverflow.com/q/49338652
tags question: http://stackoverflow.com/q/49402740
tags question: http://stackoverflow.com/q/49312879
tags question: http://stackoverflow.com/q/49437764
tags question: http://stackoverflow.com/q/49398198
tags question: http://stackoverflow.com/q/49324241
tags question: http://stackoverflow.com/q/49317226
tags question: http://stackoverflow.com/q/49297830
tags question: http://stackoverflow.com/q/49372219
tags question: http://stackoverflow.com/q/49333343
tags question: http://stackoverflow.com/q/49387439
tags question: http://stackoverflow.com/q/49279990
tags question: http://stackoverflow.com/q/49287441
tags question: http://stackoverflow.com/q/49438948
type: Tag
tags question: http://stackoverflow.com/q/49358231
tags question: http://stackoverflow.com/q/49293962
tags question: http://stackoverflow.com/q/49334751
tags question: http://stackoverflow.com/q/49309270
tags question: http://stackoverflow.com/q/49420107
tags question: http://stackoverflow.com/q/49312229
tags question: http://stackoverflow.com/q/49340998
tags question: http://stackoverflow.com/q/49371873
tags question: http://stackoverflow.com/q/49349682
tags question: http://stackoverflow.com/q/49345360
tags question: http://stackoverflow.com/q/49327929
tags question: http://stackoverflow.com/q/49308803
tags question: http://stackoverflow.com/q/49388901
tags question: http://stackoverflow.com/q/49311983
tags question: http://stackoverflow.com/q/49359799
tags question: http://stackoverflow.com/q/49329079
tag name: pip
tags question: http://stackoverflow.com/q/49433896
tags question: http://stackoverflow.com/q/49392801
tags question: http://stackoverflow.com/q/49335903
tags question: http://stackoverflow.com/q/49311839
tags question: http://stackoverflow.com/q/49323587
tags question: http://stackoverflow.com/q/49358578
tags question: http://stackoverflow.com/q/49391807
tags question: http://stackoverflow.com/q/49283203
tags question: http://stackoverflow.com/q/49285843
tags question: http://stackoverflow.com/q/49427239
tags question: http://stackoverflow.com/q/49359744
tags question: http://stackoverflow.com/q/49342660
tags question: http://stackoverflow.com/q/49359646
tags question: http://stackoverflow.com/q/49309779
tags question: http://stackoverflow.com/q/49384882
tags question: http://stackoverflow.com/q/49326554
tags question: http://stackoverflow.com/q/49370016
tags question: http://stackoverflow.com/q/49348999
tags question: http://stackoverflow.com/q/49291015

http://stackoverflow.com/q/49388887
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49389127
has answer: http://stackoverflow.com/a/49389127
has title: how to use split when the string is seperated by more than one character in python
tagged with: python
score: -1
has body: I am currently using python and i have a question: if we have a string that is separated by multiple characters for example: l = ['0 , hellp,\t2,\t BB , -\n', ' 1 ,\t \t knock \t , BB,N,- ] and I want show it in this way: 0,hellp,2,BB,- 1,knock,BB,N,- how would the coding be if i wanted to use split? i have already tried this code: l = ['0 , hellp,\t2,\t BB , -\n', ' 1 ,\t \t knock \t , BB,N,- ] replacements=('\t',' ' ,'\n') for r in replacements : l = l.replace(r,' ') words =l.split() print(words) but it didnt work out like how i want
answer count: 3
has answer: http://stackoverflow.com/a/49389216
downvote count: 2
accepted answer: http://stackoverflow.com/a/49388964
upvote count: 1
has answer: http://stackoverflow.com/a/49388964

http://stackoverflow.com/comment/85824983
has text: Thanks a lot for your script ! It does work for that example indeed, but I just found out it won't in some cases, like if ID1 and ID2 have 3 times the same value, and ID3 has one that differs 3 times. The problem will be that an offset will be created on each and every LAG()OVER(). In this example, on the 3rd row, the final groupID will not copy the last groupId :/
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49404973
type: Comment

http://stackoverflow.com/comment/85640574
type: QuestionComment
comment on: http://stackoverflow.com/q/49319836
has text: Read their documentation. It's free up to i think 500 translations a day and in non-profit situations. Prices: https://cloud.google.com/translate/pricing, doc: https://cloud.google.com/translate/docs/
score: 0
type: Comment

http://stackoverflow.com/q/49427382
tagged with: python
has body: I have dataframe like this: import pandas as pd df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'ent':['A','B']}) | |a |b |ent |---|---|----|---- |0 |1 |3 |A |1 |2 |4 |B I want to have this dataframe in form like this: |ent |A |B ------------- |a |1 |2 |b |3 |4 I can apply df.T or df.transpose but I don't get exactly what I want (header): | |0 |1 ------------- |a |1 |2 |b |3 |4 |ent |A |B I'm looking for pandastic solution (renaming columns and dropping ent row after transpose for me is inelegant).
has answer: http://stackoverflow.com/a/49427669
has answer: http://stackoverflow.com/a/49427429
answer count: 2
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49427669
accepted answer: http://stackoverflow.com/a/49427429
has title: Dataframe transpose - how to get columns name right?
tagged with: dataframe

http://stackoverflow.com/q/49436308
has body: I am trying to integrate pytest-jira plugin to my python script. I am referring to this link. It is not feasible to hard code username/password in clear text form in ~/jira.cfg. Is there any way I can override them from outside? Basically I am looking for ways to skip hard coding of password in jira.cfg. username = USERNAME (or blank for no authentication password = PASSWORD (or blank for no authentication) Can someone suggest a way to do this?
has answer: http://stackoverflow.com/a/49438750
favorite count: 0
tagged with: jira
tagged with: python-jira
has comment: http://stackoverflow.com/comment/85875677
upvote count: 2
answer count: 1
downvote count: 0
type: Question
score: 2
type: AnsweredQuestion
has title: How to avoid hard coded username/password in jira.cfg for pytest_jira plugin
tagged with: pytest
accepted answer: http://stackoverflow.com/a/49438750
tagged with: python

http://stackoverflow.com/a/49380322
score: 2
downvote count: 0
type: Answer
has body: Depending on what are going to do with the object I'd suggest looking into the Cloud Storage notifications: Object Change Notification — can notify the app when an object is updated or added to a bucket. Cloud Pub/Sub Notifications for Cloud Storage — sends a message to the Pub/Sub service. You can process the message with a handler written in my of supported languages or simply use Cloud Functions to create a lightweight server-less handler. Just follow the links, there are some examples attached.
answers question: http://stackoverflow.com/q/49367662
upvote count: 2

http://stackoverflow.com/comment/85626401
comment on: http://stackoverflow.com/q/49311943
score: 0
type: QuestionComment
has text: 50 million rows is a lot of data. If you need the results of this query often, perhaps you can cache it somewhere.
type: Comment

http://stackoverflow.com/q/49326584
favorite count: 0
type: Question
tagged with: caffe
tagged with: python
has title: How to Add Scale Parameter
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85689768
accepted answer: http://stackoverflow.com/a/49345180
has body: I have the following caffe Layer I want to add: layer { name: "s" type: "Scale" bottom: "o" top: "o" param { lr_mult: 0 decay_mult: 0 } param { lr_mult: 1 decay_mult: 0 } scale_param { filler { value: 1 } bias_term: true bias_filler { value: 0 } } } I need to create this with Python. How do I do this? caffeNet.tops[gScaleName] = L.Scale(caffeNet.tops[gConvName], param=[dict(lr_mult=0, decay_mult=0), dict(lr_mult=1, decay_mult=0)], scale_param=[dict(bias_term=True), dict(bias_filler=dict(value=0)), dict(filler=dict(value=0))] ) I try this and it gives an error saying ScaleParameter has no attribute add. How do I add it?
has answer: http://stackoverflow.com/a/49345180
answer count: 1
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49331602
score: 0
has body: I want to be able to check if a JSON array has a piece of data that meets criteria. I am learning Python and JSONs are somewhat new to me. This is what I have so far... The idea is that as long as the 'contact_count' &lt; 0 or == to 0 in this case that it wound recursively run that function until its false def instantMessage(): data = json.loads(jSon) while data[1]['contact_count'] == 0: instantMessage() jSon = {u'contact_list': [], u'contact_count': 0} I appreciate your help ahead of time!
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has comment: http://stackoverflow.com/comment/85665392
has title: Checking bits of data from JSON in Python
type: Question
has comment: http://stackoverflow.com/comment/85665267
has comment: http://stackoverflow.com/comment/85665591
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85665337
has answer: http://stackoverflow.com/a/49489536
tagged with: python

http://stackoverflow.com/comment/85812441
type: Comment
has text: Great. No Problem. :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49405416

http://stackoverflow.com/q/49433077
accepted answer: http://stackoverflow.com/a/49518604
tagged with: python
has answer: http://stackoverflow.com/a/49518604
possible better answer: http://stackoverflow.com/a/57245576
tagged with: numerical-integration
has answer: http://stackoverflow.com/a/57245576
has body: I am trying to integrate over a multivariate distribution in python. To test it, I built this toy example with a bivariate normal distribution. I use nquad() in order to extend it to more than two variables later on. Here is the code: import numpy as np from scipy import integrate from scipy.stats import multivariate_normal def integrand(x0, x1, mean, cov): return multivariate_normal.pdf([x0, x1], mean=mean, cov=cov) mean = np.array([100, 100]) cov = np.array([[20, 0], [0, 20]]) res, err = integrate.nquad(integrand, [[-np.inf, np.inf], [-np.inf, np.inf]], args=(mean, cov)) print(res) The result I get is 9.559199162933625e-10. Obviously, this is incorrect. It should be (close to) 1. What is the problem here?
type: AnsweredQuestion
answer count: 2
upvote count: 3
has title: Integration of Multivariate Normal Distribution in Python
downvote count: 0
favorite count: 0
type: Question
score: 3

closures
tags question: http://stackoverflow.com/q/49328171
tag name: closures
type: Tag

http://stackoverflow.com/comment/85860914
type: QuestionComment
has text: And what happens to the values that are further away from the mean than one std?
score: 1
comment on: http://stackoverflow.com/q/49429734
type: Comment

http://stackoverflow.com/comment/85697301
comment on: http://stackoverflow.com/a/49347062
has text: You may use groups, if you don't want to store any _addiitional information_ as part of the user's profile. If there is no difference between a student and a teacher (except what they can do in the system) then by all means you can use groups and the out-of-the-box user model without modifications.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49290698
has body: multiprocessing asks the OS to launch one or more new processes, running the same version of Python and the same version of your script. It can also set up pipes or other ways of sharing data directly between them. It usually works like magic; when you peek under the hood, sometimes it looks like sausage being made, but you can usually understand the sausage grinders. The multiprocessing docs do a great job explaining things further (they're long, but then there's a lot to explain). And if you need even more under-the-hood knowledge, the docs link to the source, which is pretty readable Python code. If you have a specific question after reading, come back to SO and ask a specific question. Meanwhile, you can get some of the benefits of multiprocessing without multiple cores. The main benefit—the reason the module was designed—is parallelism for speed. And obviously, without 4 cores, you aren't going to cut your time down to 25%. But sometimes, you actually can get a bit of speedup even with a single core, especially if that core has "hyperthreading" or similar technologies. I've seen times come down to 80%, or even 60%. More commonly, they'll go up to 108% instead (because you did get a small benefit from hyperthreading, but the overhead cost was higher than the gain). But try it with your code and see. Meanwhile, you get all of the side benefits: Concurrency: You can run multiple tasks at once without them blocking each other. Of course threads, asyncio, and other techniques can do this too. Isolation: You can run multiple tasks at once without the risk of one of them changing data that another one wasn't expecting to change. Crash protection: If a child task segfaults, only that task is affected. (Well, you still have to be careful of any side-effects—if it crashed in the middle of writing a file that another tasks expects to be in a consistent shape, you're still in trouble.) You can also use the multiprocessing module without multiple processes. Sometimes you ju…
type: Answer
answers question: http://stackoverflow.com/q/49290202
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/49347379
tagged with: beautifulsoup
type: Question
has title: how to use bs4 to get to a link nested within a matched div element
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49347468
has answer: http://stackoverflow.com/a/49347468
tagged with: python
type: AnsweredQuestion
score: 0
has body: Is there any way to get a the link out of an a element that's nested within a div element when all I can match is the div element? Something similar to the get_text() method but for links. Here is what i have matched: כל שעה שווה לכם קצת יותר this is my bs4 call: >>> headlines = davarsoup.select('.headline')
answer count: 1

http://stackoverflow.com/comment/85697110
comment on: http://stackoverflow.com/a/49347949
type: AnswerComment
score: 1
type: Comment
has text: I solved the problem in Python using Beautifulsoup and pandas. All is needed is to call dfs = pd.read_html(driver.page_source), once one navigates to the right website.

http://stackoverflow.com/comment/85778511
type: QuestionComment
comment on: http://stackoverflow.com/q/49388276
score: 0
has text: @Gareth Latty: Than this is would be the answer already. If you are sure about this, make it an answer and i will accept.
type: Comment

http://stackoverflow.com/q/49354665
type: Question
tagged with: stemming
linked to: http://stackoverflow.com/q/10369479
type: UnansweredQuestion
upvote count: 7
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/52603166
has answer: http://stackoverflow.com/a/49397599
has comment: http://stackoverflow.com/comment/85712598
favorite count: 0
duplicate of: http://stackoverflow.com/q/17317418
answer count: 3
tagged with: nltk
has body: I'm writing a text classification system in Python. This is what I'm doing to canonicalize each token: lem, stem = WordNetLemmatizer(), PorterStemmer() for doc in corpus: for word in doc: lemma = stem.stem(lem.lemmatize(word)) The reason I don't want to just lemmatize is because I noticed that WordNetLemmatizer wasn't handling some common inflections. In the case of adverbs, for example, lem.lemmatize('walking') returns walking. Is it wise to perform both stemming and lemmatization? Or is it redundant? Do researchers typically do one or the other, and not both?
score: 7
has answer: http://stackoverflow.com/a/49360329
has title: Should I perform both lemmatization and stemming?
tagged with: python
linked to: http://stackoverflow.com/q/17317418
tagged with: nlp

http://stackoverflow.com/comment/85776082
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49378740
has text: The result of two gzipped files concatenated is also a valied gzipped file, or in other words `zcat file1.gz file2.gz` and `cat file1.gz file2.gz | gzip -dc` give the same output. But if you now the offset to the beginning of file2.gz, it's possible to extract the content of file2.gz separately. This procedure is recommended in the [WARC standard](http://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/#record-at-time-compression).

http://stackoverflow.com/q/49314270
favorite count: 0
accepted answer: http://stackoverflow.com/a/49340194
type: Question
type: AnsweredQuestion
tagged with: dbf
has answer: http://stackoverflow.com/a/49340194
possible better answer: http://stackoverflow.com/a/55688380
score: 3
has answer: http://stackoverflow.com/a/55688380
tagged with: python
has title: can't write dbf file
has body: stuck with create dbf file in python3 with dbf lib. im tried this - import dbf Tbl = dbf.Table( 'sample.dbf', 'ID N(6,0); FCODE C(10)') Tbl.open('read-write') Tbl.append() with Tbl.last_record as rec: rec.ID = 5 rec.FCODE = 'GA24850000' and have next error: Traceback (most recent call last): File "c:\Users\operator\Desktop\2.py", line 3, in &lt;module&gt; Tbl.open('read-write') File "C:\Users\operator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\dbf\__init__.py", line 5778, in open raise DbfError("mode for open must be 'read-write' or 'read-only', not %r" % mode) dbf.DbfError: mode for open must be 'read-write' or 'read-only', not 'read-write' if im remove 'read-write' - next: Traceback (most recent call last): File "c:\Users\operator\Desktop\2.py", line 4, in &lt;module&gt; Tbl.append() File "C:\Users\operator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\dbf\__init__.py", line 5492, in append raise DbfError('%s not in read/write mode, unable to append records' % meta.filename) dbf.DbfError: sample.dbf not in read/write mode, unable to append records thats im doing wrong? if im not try append, im just get .dbf with right columns, so dbf library works.
answer count: 2
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49338758
favorite count: 0
accepted answer: http://stackoverflow.com/a/49338840
tagged with: editline
type: Question
has answer: http://stackoverflow.com/a/49338840
has title: Why the editText doesn't show the user input in Python class?
has body: I have a Python class that display a window that includes 2 text filed and 2 buttons. Where the user enter a string in the first edit text and on click on the (open button) the second edit text will display the user input. The problem is that on the click on the button there is nothing displayed in the text filed. Code: ''' 1- import the libraries from the converted file 2- import the converted file ''' from PyQt5 import QtCore, QtGui, QtWidgets import pathmsgbox import os import pathlib class path_window(pathmsgbox.Ui_PathMSGbox): def __init__(self,windowObject ): self.windowObject = windowObject self.setupUi(windowObject) self.windowObject.show() self.getText() ''' get the userInput from the EditLine ''' def getText(self): inputUser = self.pathEditLine.text() outPutUser = self.outputPathName.setText(inputUser) print(outPutUser) def puchBtn(self): openButton = self.PathOpenBtn.clicked.connect(self.getText) ''' function that exit from the system after clicking "cancel" ''' def exit(): sys.exit() ''' define the methods to run only if this is the main module deing run the name take __main__ string only if its the main running script and not imported nor being a child process ''' if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) PathMSGbox = QtWidgets.QWidget() pathUi = path_window(PathMSGbox) pathUi.pathCancelBtn.clicked.connect(exit) sys.exit(app.exec_())
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
tagged with: button
tagged with: pyqt5
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/85708565
score: 0
type: AnswerComment
type: Comment
has text: @StephenRauch, agreed. I added a comment to reflect this fact.
comment on: http://stackoverflow.com/a/49354090

http://stackoverflow.com/q/49414667
has comment: http://stackoverflow.com/comment/85834726
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/49436165
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85836951
has answer: http://stackoverflow.com/a/49415517
answer count: 2
possible better answer: http://stackoverflow.com/a/49415517
has comment: http://stackoverflow.com/comment/85834495
has comment: http://stackoverflow.com/comment/85862601
has title: Fast way to convert SQLAlchemy objects to Python dicts
has body: I have this query that returns a list of student objects: query = db.session.query(Student).filter(Student.is_deleted == false()) query = query.options(joinedload('project')) query = query.options(joinedload('image')) query = query.options(joinedload('student_locator_map')) query = query.options(subqueryload('attached_addresses')) query = query.options(subqueryload('student_meta')) query = query.order_by(Student.student_last_name, Student.student_first_name, Student.student_middle_name, Student.student_grade, Student.student_id) query = query.filter(filter_column == field_value) students = query.all() The query itself does not take much time. The problem is converting all these objects (can be 5000+) to Python dicts. It takes over a minute with this many objects.Currently, the code loops thru the objects and converts using to_dict(). I have also tried _dict__ which was much faster but this does not convert all relational objects it seems. How can I convert all these Student objects and related objects quickly?
has comment: http://stackoverflow.com/comment/85833372
tagged with: python
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/49436165
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85832388

http://stackoverflow.com/q/49336657
has comment: http://stackoverflow.com/comment/85675682
has answer: http://stackoverflow.com/a/49339536
answer count: 4
has answer: http://stackoverflow.com/a/49337773
type: AnsweredQuestion
upvote count: 0
has title: Merge column from different CSV into a single file
has answer: http://stackoverflow.com/a/49337749
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49337781
possible better answer: http://stackoverflow.com/a/49337773
has body: Basically I have 2 csv file as below: File 1: File 2: Current output: Num Num2 Num 1 1 1 2 2 2 3 3 3 4 4 4 Num2 1 2 3 4 I want to merge them into a single csv file as below: Expected File 3: Num Num2 1 1 2 2 3 3 4 4 However when I merge the file, it starts at the bottom of File 1 data. How to make them start at the column 2 row 1, instead of starting at the below. inputs = ["asd.csv", "b.csv"] # etc # First determine the field names from the top line of each input file # Comment 1 below fieldnames = [] for filename in inputs: with open(filename, "r", newline="") as f_in: reader = csv.reader(f_in) headers = next(reader) for h in headers: if h not in fieldnames: fieldnames.append(h) # Then copy the data with open("out.csv", "w", newline="") as f_out: # Comment 2 below writer = csv.DictWriter(f_out, fieldnames=fieldnames) for filename in inputs: with open(filename, "r", newline="") as f_in: reader = csv.DictReader(f_in) # Uses the field names in this file for line in reader: # Comment 3 below writer.writerow(line)
type: Question
accepted answer: http://stackoverflow.com/a/49337749
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: merge
score: -1

http://stackoverflow.com/a/49393822
has comment: http://stackoverflow.com/comment/85790163
score: 5
has comment: http://stackoverflow.com/comment/85790715
upvote count: 5
answers question: http://stackoverflow.com/q/49393705
downvote count: 0
type: Answer
has body: Python does not magically fill the value of n into the string. For this you either need to use format: r"\b[a-zA-z]{{{}}}\b".format(n) or, if you are running Python >= 3.6, use the new f-strings (which can be combined with the r prefix denoting a raw string): fr"\b[a-zA-z]{{{n}}}\b" In both cases you need the outer two {{}} to create a literal {} and the inner is a format placeholder. If you want to avoid having to escape the literal {}, you can use the older %-formatting to achieve the same thing. For this n needs to always be an integer (which it is here): r"\b[a-zA-z]{%i}\b" % n

http://stackoverflow.com/q/49427395
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85858354
accepted answer: http://stackoverflow.com/a/49429186
has answer: http://stackoverflow.com/a/49429186
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85856247
tagged with: python
score: -1
type: Question
has body: I need to mark certain regions on my mosaic. I have plotted horizontal lines, but would like to be able to set a tick value of the value next to them. something like '0.1, 0.2, etc' I have added an example of the picture below. fig = plt.figure(figsize=(2,20)) plt.imshow(cube1_img_rot) plt.imshow(cube2_img_rot, extent=[-19,1928,-24537, -22591]) plt.imshow(cube3_img_rot, extent=[-19,1928,-9352, -7476]) for i in range(len(mu_pix)): plt.axhline(mu_pix[i]) plt.savefig('foo.pdf', bbox_inches='tight', dpi=1000)
upvote count: 0
has comment: http://stackoverflow.com/comment/85855807
answer count: 1
has title: plt.imshow() custom ticks at set Y values [Python]
tagged with: imshow

terminal
tags question: http://stackoverflow.com/q/49362774
tags question: http://stackoverflow.com/q/49320231
tags question: http://stackoverflow.com/q/49317226
tags question: http://stackoverflow.com/q/49437026
tags question: http://stackoverflow.com/q/49432242
tags question: http://stackoverflow.com/q/49299392
type: Tag
tags question: http://stackoverflow.com/q/49430925
tags question: http://stackoverflow.com/q/49393300
tag name: terminal
tags question: http://stackoverflow.com/q/49301514
tags question: http://stackoverflow.com/q/49403824

http://stackoverflow.com/a/49352409
accepted answer of: http://stackoverflow.com/q/49350136
type: Answer
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/105882728
answers question: http://stackoverflow.com/q/49350136
has comment: http://stackoverflow.com/comment/85713217
has comment: http://stackoverflow.com/comment/113728132
has body: In that case you should try out newly released requests_html library which has the capability to handle dynamically generated items. This is how your script should look like if you comply with what I have just said: import requests_html session = requests_html.HTMLSession() r = session.get('https://chartink.com/screener/test-121377') r.html.render(sleep=5) items = r.html.find("table#DataTables_Table_0",first=True) for item in items.find("tr"): data = [td.text for td in item.find("th,td")] print(data) Output: ['Sr.', 'Stock Name', 'Symbol', 'Links', '% Chg', 'Price', 'Volume'] ['1', 'Axis Bank Limited', 'AXISBANK', 'P&amp;F | F.A', '-1.33%', '522.6', '12,146,623'] ['2', 'Reliance Industries Limited', 'RELIANCE', 'P&amp;F | F.A', '-1.29%', '900.05', '14,087,564'] ['3', 'Tata Steel Limited', 'TATASTEEL', 'P&amp;F | F.A', '-1.89%', '600.2', '11,739,582']
upvote count: 5
has comment: http://stackoverflow.com/comment/113728722
score: 5
has comment: http://stackoverflow.com/comment/113737062

http://stackoverflow.com/q/49366412
upvote count: 1
tagged with: python
has body: I am following a simple tutorial to load Reddit comment data from pushshift.io into a dask bag. I am getting the strange error: "Resolving "AttributeError: module 'dask.bag' has no attribute 'from_filenames'", despite the fact that this is standard procedure as described here: http://dask.pydata.org/en/doc-test-build/bag.html import dask import dask.bag as db data = db.from_filenames("reddit_1_28_2018.txt", chunkbytes=100000).map(json.loads) AttributeError Traceback (most recent call last) &lt;ipython-input-17-bcbd31affbfb&gt; in &lt;module&gt;() 2 import dask.bag as db 3 ----&gt; 4 data = db.from_filenames("reddit_1_28_2018.txt", chunkbytes=100000).map(json.loads) AttributeError: module 'dask.bag' has no attribute 'from_filenames'
type: AnsweredQuestion
has title: Resolving "AttributeError: module 'dask.bag' has no attribute 'from_filenames'"
has answer: http://stackoverflow.com/a/51001305
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: Question
tagged with: dask
accepted answer: http://stackoverflow.com/a/51001305

http://stackoverflow.com/comment/85984562
score: 0
type: Comment
type: AnswerComment
has text: By modularity I mean that you can easily change parts of your code (optimizer, constraints, loss, regularization etc.)
comment on: http://stackoverflow.com/a/49406777

http://stackoverflow.com/q/49409150
has body: Please see the simplified example: A = [(721,'a'),(765,'a'),(421,'a'),(422,'a'),(106,'b'),(784,'a'),(201,'a'),(206,'b'),(207,'b')] I want group adjacent tuples with attribute 'a', every two pair wise and leave tuples with 'b' alone. So the desired tuple would looks like: A = [[(721,'a'),(765,'a')], [(421,'a'),(422,'a')], [(106,'b')], [(784,'a'),(201,'a')], [(206,'b')], [(207,'b')]] What I can do is to build two separated lists contains tuples with a and b. Then pair tuples in a, and add back. But it seems not very efficient. Any faster and simple solutions?
has answer: http://stackoverflow.com/a/49410184
has comment: http://stackoverflow.com/comment/85820829
type: Question
has title: Python group by adjacent items in a list with same attributes
accepted answer: http://stackoverflow.com/a/49410091
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/49409386
possible better answer: http://stackoverflow.com/a/49409386
has comment: http://stackoverflow.com/comment/85820753
favorite count: 0
has answer: http://stackoverflow.com/a/49410091
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85820801
tagged with: list
answer count: 3
upvote count: 5

http://stackoverflow.com/q/49430262
downvote count: 1
has answer: http://stackoverflow.com/a/49430507
accepted answer: http://stackoverflow.com/a/49430603
has answer: http://stackoverflow.com/a/49430478
has comment: http://stackoverflow.com/comment/85862463
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/49430413
has comment: http://stackoverflow.com/comment/85862244
has answer: http://stackoverflow.com/a/49430398
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/49430603
tagged with: regex
has body: I have a text file with entries like this: Interface01 : adress 192.168.0.1 next-interface: interface02: adress 10.123.123.214 next-interface: interface01 : adress 172.123.456.123 I'd like to parse it and get only the IP address corresponding to Interface01 I tried may things with python re.finall but couldn't get anything matching i = open(f, r, encoding='UTF-8') txt = i.read() interface = re.findall(r'Interface01 :\s*(.adress*)n',txt,re.DOTALL) but nothing works. The expected result is 192.168.0.1.
has comment: http://stackoverflow.com/comment/85862881
has answer: http://stackoverflow.com/a/49430623
type: Question
score: 2
has answer: http://stackoverflow.com/a/49430413
has comment: http://stackoverflow.com/comment/85862297
has comment: http://stackoverflow.com/comment/85862678
has title: Python re.findall with multiple patterns

http://stackoverflow.com/comment/120782232
comment on: http://stackoverflow.com/q/49348999
has text: Hi @thatotherguy, I have the same problem like salonitiwari's question and I read your comment that worst case I can compile dlib from source.. since I am new in this field, would you like to give me information about how to compile dlib from source ?
type: Comment
score: 0
type: QuestionComment

keras
tags question: http://stackoverflow.com/q/49438154
tags question: http://stackoverflow.com/q/49419265
tags question: http://stackoverflow.com/q/49282269
tags question: http://stackoverflow.com/q/49360786
tags question: http://stackoverflow.com/q/49346253
tags question: http://stackoverflow.com/q/49419860
tags question: http://stackoverflow.com/q/49399847
tags question: http://stackoverflow.com/q/49344429
tags question: http://stackoverflow.com/q/49404993
tags question: http://stackoverflow.com/q/49305971
tags question: http://stackoverflow.com/q/49337897
tags question: http://stackoverflow.com/q/49369176
tags question: http://stackoverflow.com/q/49422473
tags question: http://stackoverflow.com/q/49409448
tags question: http://stackoverflow.com/q/49365979
tags question: http://stackoverflow.com/q/49421088
tags question: http://stackoverflow.com/q/49374511
tags question: http://stackoverflow.com/q/49342925
tags question: http://stackoverflow.com/q/49388477
tags question: http://stackoverflow.com/q/49381736
tags question: http://stackoverflow.com/q/49287407
tags question: http://stackoverflow.com/q/49311863
tags question: http://stackoverflow.com/q/49406272
tags question: http://stackoverflow.com/q/49349522
tags question: http://stackoverflow.com/q/49281035
tags question: http://stackoverflow.com/q/49334642
tags question: http://stackoverflow.com/q/49432451
tags question: http://stackoverflow.com/q/49345671
tags question: http://stackoverflow.com/q/49351616
tags question: http://stackoverflow.com/q/49312989
tags question: http://stackoverflow.com/q/49332244
tags question: http://stackoverflow.com/q/49421843
tags question: http://stackoverflow.com/q/49366046
tags question: http://stackoverflow.com/q/49404205
tags question: http://stackoverflow.com/q/49340856
tags question: http://stackoverflow.com/q/49392972
tags question: http://stackoverflow.com/q/49350942
tags question: http://stackoverflow.com/q/49285317
tags question: http://stackoverflow.com/q/49350531
tags question: http://stackoverflow.com/q/49435335
tags question: http://stackoverflow.com/q/49302743
tags question: http://stackoverflow.com/q/49346257
tags question: http://stackoverflow.com/q/49419645
tags question: http://stackoverflow.com/q/49338923
tags question: http://stackoverflow.com/q/49296099
tags question: http://stackoverflow.com/q/49354178
tags question: http://stackoverflow.com/q/49298506
tags question: http://stackoverflow.com/q/49286496
tags question: http://stackoverflow.com/q/49359489
tags question: http://stackoverflow.com/q/49398457
tags question: http://stackoverflow.com/q/49330274
tags question: http://stackoverflow.com/q/49350480
tags question: http://stackoverflow.com/q/49407713
tags question: http://stackoverflow.com/q/49436628
tags question: http://stackoverflow.com/q/49288973
tags question: http://stackoverflow.com/q/49363552
tags question: http://stackoverflow.com/q/49391386
tags question: http://stackoverflow.com/q/49362931
tags question: http://stackoverflow.com/q/49384628
tags question: http://stackoverflow.com/q/49305461
tags question: http://stackoverflow.com/q/49295311
tags question: http://stackoverflow.com/q/49377809
tags question: http://stackoverflow.com/q/49339355
tag name: keras
tags question: http://stackoverflow.com/q/49349918
tags question: http://stackoverflow.com/q/49354239
tags question: http://stackoverflow.com/q/49425632
tags question: http://stackoverflow.com/q/49417181
tags question: http://stackoverflow.com/q/49349388
tags question: http://stackoverflow.com/q/49291664
tags question: http://stackoverflow.com/q/49426359
tags question: http://stackoverflow.com/q/49417546
tags question: http://stackoverflow.com/q/49363410
tags question: http://stackoverflow.com/q/49425056
tags question: http://stackoverflow.com/q/49437136
tags question: http://stackoverflow.com/q/49313650
type: Tag
tags question: http://stackoverflow.com/q/49375356
tags question: http://stackoverflow.com/q/49370940
tags question: http://stackoverflow.com/q/49301203

http://stackoverflow.com/comment/85626733
score: 0
type: Comment
has text: The script `/usr/local/bin/pip3` seems to be broken — it tries to use `/usr/local/lib/python2.7/` library. Use `python2.7 -m pip` or `python3.4…` to run `pip` with the proper version of Python.
type: QuestionComment
comment on: http://stackoverflow.com/q/49311839

http://stackoverflow.com/comment/85839242
score: 0
has text: fixed, was just a copy+paste issue for stack overflow, problem persists.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49418799

http://stackoverflow.com/a/49512936
upvote count: 1
answers question: http://stackoverflow.com/q/49438070
type: Answer
accepted answer of: http://stackoverflow.com/q/49438070
score: 1
type: AcceptedAnswer
has body: You can use an Output widget to display your HTML. This worked for me: import ipywidgets as widgets from IPython.display import display, HTML import threading out = widgets.Output() def foo(): with out: display(HTML(' foobarbaz ')) threading.Thread(target=foo).start() out
downvote count: 0

http://stackoverflow.com/a/49375587
type: AcceptedAnswer
score: 9
upvote count: 9
has body: Even if you manage to get this working, I don’t think it will do what you want. As soon as you have multiple processes pulling from the same random state in parallel, it’s no longer deterministic which order they each get to the state, meaning your runs won’t actually be repeatable. There are probably ways around that, but it seems like a nontrivial problem. Meanwhile, there is a solution that should solve both the problem you want and the nondeterminism problem: Before spawning a child process, ask the RNG for a random number, and pass it to the child. The child can then seed with that number. Each child will then have a different random sequence from other children, but the same random sequence that the same child got if you rerun the entire app with a fixed seed. If your main process does any other RNG work that could depend non-deterministically on the execution of the children, you'll need to pre-generate the seeds for all of your child processes, in order, before pulling any other random numbers. As senderle pointed out in a comment: If you don't need multiple distinct runs, but just one fixed run, you don't even really need to pull a seed from your seeded RNG; just use a counter starting at 1 and increment it for each new process, and use that as a seed. I don't know if that's acceptable, but if it is, it's hard to get simpler than that. As Amir pointed out in a comment: a better way is to draw a random integer every time you spawn a new process and pass that random integer to the new process to set the numpy's random seed with that integer. This integer can indeed come from np.random.randint().
answers question: http://stackoverflow.com/q/49372619
has comment: http://stackoverflow.com/comment/85768785
has comment: http://stackoverflow.com/comment/85777555
type: Answer
has comment: http://stackoverflow.com/comment/85758442
has comment: http://stackoverflow.com/comment/85777153
accepted answer of: http://stackoverflow.com/q/49372619
has comment: http://stackoverflow.com/comment/85758970
downvote count: 0
has comment: http://stackoverflow.com/comment/85758716
has comment: http://stackoverflow.com/comment/85758736

http://stackoverflow.com/comment/85673526
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49334150
has text: you need to show the code and the error
score: 0

http://stackoverflow.com/q/49376371
has answer: http://stackoverflow.com/a/49376460
upvote count: 9
type: UnansweredQuestion
has body: I'm brand new to coding and I've been trying to absorb as much as possible. I don't understand a lot of the technical explanations you guys post, so please try to keep it in simple English. I get the mechanics of how a decorator function works, but my issue is following the code logic - specifically why we have to add *args and ** kwargs. Is it correct to state that whatever we pass in to the decorator function that takes in a function which has arguments, will always pass the same arguments into the wrapper function because it's nested within the decorator? That's what I'm missing here. I don't understand how the arguments from the original function get passed in.
tagged with: python
has title: python decorators *args and ** kwargs
answer count: 1
tagged with: decorator
downvote count: 1
has comment: http://stackoverflow.com/comment/85753689
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/85753685

http://stackoverflow.com/comment/85689997
score: 2
has text: Please add the code to the question and describe the context a bit.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49344916

http://stackoverflow.com/a/71692384
answers question: http://stackoverflow.com/q/49427574
downvote count: 0
score: 1
upvote count: 1
has body: I am also looking for the same solution as you, however, I can make your code shorter and more efficient: import pandas as pd file = pd.read_excel("Classeur1.xlsx", header = 10) file.head() This way you can read can skip all the rows from 0 ==> 9 and start reading from the 10th row.
type: Answer

http://stackoverflow.com/q/49322509
answer count: 1
has title: Colaboratory importing .py files error
has comment: http://stackoverflow.com/comment/85646961
type: Question
has answer: http://stackoverflow.com/a/49332355
has comment: http://stackoverflow.com/comment/85646430
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85646305
tagged with: python
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/85647520
has body: I mounted Google drive in Colaboratory and set path to the drive/. It seems that the path is set correctly, however when I run my code, the files can't be read. I am quite sure that proc_data_lib.py is a pythonfile instead of zip file and the first few lines of that python file is in the second picture Error Images File:proc_data_lib.py ERROR INFO: File "drive/ECMLDeepAudio-Master/lib/proc_data_lib.py", line 1 PK�����rpL^�2'���'������mimetypeapplication/vnd.oasis.opendocument.textPK�����rpL/�4z���������Thumbnails/thumbnail.png�PNG ^ SyntaxError: invalid syntax
score: 0

http://stackoverflow.com/a/49435413
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85872913
answers question: http://stackoverflow.com/q/49435215
has body: You could just iterate through the list and pop() and concatenate non-matching values to the previous item. i = 0 while i &lt; len(lst): if not (lst[i].startswith('i') or list[i].startswith('r')): lst[i - 1] += lst.pop(i) else: i += 1
has comment: http://stackoverflow.com/comment/85873040

http://stackoverflow.com/a/49340058
score: 5
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49339079
has comment: http://stackoverflow.com/comment/133307293
upvote count: 5
has body: I have constructed a minimal example which is for a curve similar to yours. If you had posted actual data instead of a picture, this would have gone a bit faster. The two key things to understand about robust fitting with least_squares is that you have to use a different value for the loss parameter than linear and that f_scale is used as a scaling parameter for the loss function. Basically, from the docs, least_squares tries to minimize F(x) = 0.5 * sum(rho(f_i(x)**2) and setting the loss loss parameter changes rho in the above formula. For loss='linear' rho is just the identity function. When loss='soft_l1', rho(z) = 2 * ((1 + z)**0.5 - 1). f_scale is used to scale the loss function such that rho_(f**2) = C**2 * rho(f**2 / C**2). So it doesn't have the same kind of meaning as you are asking for above, it's more like a way of penalising larger errors less. In this particular case it doesn't appear to make much difference though. import numpy import matplotlib.pyplot as plt import scipy.optimize tmax = 6000 N = 100 K = 6000 T = 200 smootht = numpy.linspace(0, tmax, 1000) tm = numpy.linspace(0, tmax, N) def f(t, K, T): return K * (1 - numpy.exp(-t/T)) v = f(smootht, K, T) vm = f(tm, K, T) + numpy.random.randn(N)*400 def error(pars): K, T = pars vp = f(tm, K, T) return vm - vp f_scales = [0.01, 1, 100] plt.scatter(tm, vm) for f_scale in f_scales: r = scipy.optimize.least_squares(error, [10, 10], loss='soft_l1', f_scale=f_scale) vp = f(smootht, *r.x) plt.plot(smootht, vp, label=f_scale) plt.legend() The resulting plot looks like this: My suggestion is to start by just experimenting with the different loss functions before playing with f_scale.
accepted answer of: http://stackoverflow.com/q/49339079
type: Answer
has comment: http://stackoverflow.com/comment/85706247

http://stackoverflow.com/a/49369037
answers question: http://stackoverflow.com/q/49368882
type: Answer
has body: You either have to set the inplace parameter of the replace function to true or assign the returned df to the df variable
score: -1
has comment: http://stackoverflow.com/comment/85738999
upvote count: 0
has comment: http://stackoverflow.com/comment/85739494
downvote count: 1

http://stackoverflow.com/comment/85584133
score: 1
has text: `temp` is just a variable name.. You can write any legal name there. Just replace your name instead of `temp` everywhere it'll still work. The variable name is just a symbolic name for the value contained at a specific address in your memory. The name is arbitrary.
type: Comment
comment on: http://stackoverflow.com/a/49290453
type: AnswerComment

http://stackoverflow.com/q/49309012
has title: Regex: How to not match word A if word B is somewhere before A
tagged with: python
has answer: http://stackoverflow.com/a/49309075
tagged with: regex
accepted answer: http://stackoverflow.com/a/49309075
type: Question
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/49309534
possible better answer: http://stackoverflow.com/a/49309534
answer count: 2
downvote count: 0
has body: I'm using python regex engine and trying to achieve something like for string foo,fou,bar,baz. I want to match baz if and only if fou is not before it. I've tried negative look behind (&lt;?!fou)baz but it doesn't work as it only work for immediate following.
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/85580380
has text: Does each row of your .txt file have the same number of values?
type: Comment
comment on: http://stackoverflow.com/q/49288559
type: QuestionComment
score: 0

http://stackoverflow.com/q/49360545
answer count: 1
linked to: http://stackoverflow.com/q/17225920
has title: How to detect if an item exist in treeview
linked to: http://stackoverflow.com/q/46176129
tagged with: python
has comment: http://stackoverflow.com/comment/85722405
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49361242
score: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49361242
tagged with: tkinter
has body: I have few lines of code here to detect if an item already exist in tkinter treeview before selected item can be inserted in the tree2 .If the item already exist it should print "item exist" if not the item should be inserted. from tkinter import ttk import tkinter as tk blow = [("january", "2013"),("february", "2014"),("march", "2015"),("april", "2016"),("may", "2017")] def append_select(): cur_id = tree.focus() for child in tree2.selection(): #for child in tree2.get_children(): if cur_id in child: print("item exist") elif cur_id: tree2.insert("", tk.END, values=tree.item(cur_id)['values']) root = tk.Tk() root.geometry("500x500") tree = ttk.Treeview(columns=("columns1", "columns"), show="headings", selectmode="browse") tree.heading("#1", text="Month") tree.heading("#2", text="Year") for n in blow: tree.insert("", tk.END, values=(n)) tree.pack() b1 = tk.Button(text="append", command=append_select) b1.pack() tree2 = ttk.Treeview(columns=("Month", "Year"), show="headings") tree2.heading("#1", text="month") tree2.heading("#2", text="year") tree2.pack() root.mainloop()
tagged with: treeview
downvote count: 0

http://stackoverflow.com/q/49292783
has comment: http://stackoverflow.com/comment/85588172
has body: I get a Keyerror when doing a for loop on a set of int values. Here is the code: # groupes : dict[str:set[int]] groupes = {'cinephiles':{802,125,147,153}, \ 'travaux manuels':{125,802,153}, \ 'cuisine':{153,147,802}, \ 'sport':{153,538,802}} # This first function helps me for the second one def proximite_groupes(group, hobby_1, hobby_2): """ dict[str:set[int]] * str * str -&gt; float """ # intersection_set : set[int] intersection_set = set() # union_set : set[int] union_set = set() # cle : int for cle in group[hobby_1]: if cle in group[hobby_2]: intersection_set.add(cle) for cle in group[hobby_1]: if cle not in union_set: union_set.add(cle) for cle in group[hobby_2]: if cle not in union_set: union_set.add(cle) return len(intersection_set) / len(union_set) def fusion_groupes(group): """ dict[str:set[int]] -&gt; dict[str:set[int]] """ # similarite_max : int similarite_max = 0.0 # str_1 : str # str_2 : str # str_1_final : str str_1_final = '' str_2_final = '' # str_1_final : str # str_final : str str_final = ' ' # final_dict : dict[str:set[int]] final_dict = group # intersection_set : set[int] intersection_set = set() for str_1 in group: for str_2 in group: if str_1 != str_2: if proximite_groupes(group, str_1, str_2) &gt; similarite_max: similarite_max = proximite_groupes(group, str_1, str_2) str_final = str_1 + '_' + str_2 str_1_final = str_1 str_2_final = str_2 del final_dict[str_1_final] del final_dict[str_2_final] # Creation ensemble union for cle in group[str_1_final]: if cle in group[str_2_final]: intersection_set.add(cle) final_dict[str_final] = intersection_set return final_dict The purpose of the function is a little bit hard to difficult, but my problem here is: File "&lt;input&gt;", line 1, in &lt;module&gt; File "&lt;input&gt;", line 261, in fusion_groupes (note that the line would not be the same for you because my program has more lines) KeyError: 'cuisine' (but one time it's 'cuisine', the other time its 'cinephiles', or 'sport', ...
answer count: 1
has title: for loop with set: key
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49293047
accepted answer: http://stackoverflow.com/a/49293047
has comment: http://stackoverflow.com/comment/85588643
tagged with: set
tagged with: python
has comment: http://stackoverflow.com/comment/85588229
type: Question
has comment: http://stackoverflow.com/comment/85588796
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85588405

http://stackoverflow.com/q/49413857
answer count: 1
tagged with: python
has body: How can I obtain the LCFRS grammar using treetools? I used the following terminal command treetools grammar wsj_0001.prd output leftright --dest-format rcg --markov v:1 h:2 where wsj_0001.prd is a tree and the output file I get is empty. https://pypi.python.org/pypi/treetools/0.1.0 - I used the last command form the ones listed. Thanks.
score: 0
has answer: http://stackoverflow.com/a/49764835
tagged with: linguistics
tagged with: nlp
type: Question
has title: Treetools package - computational linguistics
type: UnansweredQuestion
tagged with: package

matplotlib
tags question: http://stackoverflow.com/q/49330829
tags question: http://stackoverflow.com/q/49309706
tags question: http://stackoverflow.com/q/49357973
tags question: http://stackoverflow.com/q/49290266
tags question: http://stackoverflow.com/q/49286313
tags question: http://stackoverflow.com/q/49342812
tags question: http://stackoverflow.com/q/49395718
tags question: http://stackoverflow.com/q/49394394
tags question: http://stackoverflow.com/q/49334579
tags question: http://stackoverflow.com/q/49295139
tags question: http://stackoverflow.com/q/49428588
tags question: http://stackoverflow.com/q/49295779
tags question: http://stackoverflow.com/q/49343087
tags question: http://stackoverflow.com/q/49322980
tags question: http://stackoverflow.com/q/49369083
tags question: http://stackoverflow.com/q/49371365
tags question: http://stackoverflow.com/q/49294705
tags question: http://stackoverflow.com/q/49287690
tags question: http://stackoverflow.com/q/49425805
tags question: http://stackoverflow.com/q/49397920
tags question: http://stackoverflow.com/q/49301983
tags question: http://stackoverflow.com/q/49423770
tags question: http://stackoverflow.com/q/49297206
tags question: http://stackoverflow.com/q/49392606
tags question: http://stackoverflow.com/q/49302095
tags question: http://stackoverflow.com/q/49411783
tags question: http://stackoverflow.com/q/49416776
tags question: http://stackoverflow.com/q/49283546
tags question: http://stackoverflow.com/q/49351275
tags question: http://stackoverflow.com/q/49390901
tags question: http://stackoverflow.com/q/49326496
tags question: http://stackoverflow.com/q/49387217
tags question: http://stackoverflow.com/q/49334810
tags question: http://stackoverflow.com/q/49294519
tags question: http://stackoverflow.com/q/49387261
tags question: http://stackoverflow.com/q/49399748
tags question: http://stackoverflow.com/q/49358826
tags question: http://stackoverflow.com/q/49342018
tags question: http://stackoverflow.com/q/49326860
tags question: http://stackoverflow.com/q/49439510
tags question: http://stackoverflow.com/q/49303263
tags question: http://stackoverflow.com/q/49376052
tags question: http://stackoverflow.com/q/49434952
tags question: http://stackoverflow.com/q/49377203
tags question: http://stackoverflow.com/q/49414329
tags question: http://stackoverflow.com/q/49392426
tags question: http://stackoverflow.com/q/49311863
tags question: http://stackoverflow.com/q/49310392
tags question: http://stackoverflow.com/q/49327905
tags question: http://stackoverflow.com/q/49414186
tags question: http://stackoverflow.com/q/49360266
tags question: http://stackoverflow.com/q/49416646
tags question: http://stackoverflow.com/q/49367013
tags question: http://stackoverflow.com/q/49289179
tags question: http://stackoverflow.com/q/49396526
tags question: http://stackoverflow.com/q/49416975
tags question: http://stackoverflow.com/q/49381245
tag name: matplotlib
tags question: http://stackoverflow.com/q/49381274
tags question: http://stackoverflow.com/q/49391563
tags question: http://stackoverflow.com/q/49323348
tags question: http://stackoverflow.com/q/49338329
tags question: http://stackoverflow.com/q/49355810
tags question: http://stackoverflow.com/q/49343679
tags question: http://stackoverflow.com/q/49286741
tags question: http://stackoverflow.com/q/49419351
tags question: http://stackoverflow.com/q/49379332
tags question: http://stackoverflow.com/q/49302911
tags question: http://stackoverflow.com/q/49423347
tags question: http://stackoverflow.com/q/49293067
tags question: http://stackoverflow.com/q/49306922
tags question: http://stackoverflow.com/q/49340520
tags question: http://stackoverflow.com/q/49353661
tags question: http://stackoverflow.com/q/49282955
tags question: http://stackoverflow.com/q/49395927
tags question: http://stackoverflow.com/q/49418248
tags question: http://stackoverflow.com/q/49428050
tags question: http://stackoverflow.com/q/49290456
tags question: http://stackoverflow.com/q/49283862
tags question: http://stackoverflow.com/q/49282133

http://stackoverflow.com/a/49394114
score: 0
has comment: http://stackoverflow.com/comment/85792204
has body: Here is my suggestion that I find readable, easy to understand and quite short: import random inputSet = set([45, 235, 3, 77, 55, 80, 154]) ran = [50,100] # Get list of elements inside the range a = [x for x in inputSet if x in range(ran[0],ran[1])] # Print a random element print(random.choice(a)) # randomly 55, 77 or 80 Note that I have not used the name input for the defined set because it is a reserved built-in symbol.
type: Answer
answers question: http://stackoverflow.com/q/49393805

http://stackoverflow.com/q/49289709
has title: Element Exception
tagged with: python
has answer: http://stackoverflow.com/a/49290294
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/49293667
tagged with: selenium-chromedriver
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/49291722
has body: I am trying to execute this code and it shows 'NoSuchElementException' this error. So can anyone help me for this ? Code: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver= webdriver.Chrome() page=driver.get("http://www.awgp.org") banner_tell=driver.find_element_by_Link_text('Tell Me More') banner_tell.click()
tagged with: selenium
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/85598516
score: 0
comment on: http://stackoverflow.com/q/49298245
type: QuestionComment
has text: Possible duplicate of [Selenium use Chromium instead of google-chrome](https://stackoverflow.com/questions/24999318/selenium-use-chromium-instead-of-google-chrome)
type: Comment

http://stackoverflow.com/a/49390974
has comment: http://stackoverflow.com/comment/85783756
downvote count: 0
upvote count: 1
has body: Check this and let me know: text = "xxxxAAaaaSSSxxx" PasswordSubHT = {"a":"@" , "A":"4" , "S":"5"} for letter in text: if letter in PasswordSubHT.keys(): text = text.replace(letter, str(PasswordSubHT[letter])) print(text) Note: replace(x, y) will replace all the x in the text. If you want to replace just one char at the time add the count argument = 1: text = text.replace(letter, str(PasswordSubHT[letter]), 1)
has comment: http://stackoverflow.com/comment/85783786
score: 1
has comment: http://stackoverflow.com/comment/85783959
type: Answer
has comment: http://stackoverflow.com/comment/85783570
answers question: http://stackoverflow.com/q/49390828
has comment: http://stackoverflow.com/comment/85783711

http://stackoverflow.com/comment/85810715
type: Comment
has text: there must be some other options as well. This is what I used, so, I told you.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49404569

http://stackoverflow.com/a/49419235
type: Answer
has comment: http://stackoverflow.com/comment/85840039
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49419131
answers question: http://stackoverflow.com/q/49419131
type: AcceptedAnswer
has body: To see just ten rows: import pandas as pd pd.set_option('display.max_rows',10) This will fix your PD to show only first 10 rows always, no matter if you print dataframe to see more. If you want to vary from time to time the use df.head(10)
score: 4
has comment: http://stackoverflow.com/comment/85840021
downvote count: 0

http://stackoverflow.com/a/49289480
has body: You can use itertools.product for this; effectively this is combinations with replacement. You can construct a list comprehension which filters for sum equal to 1. from itertools import product res = np.array([i for i in product(np.linspace(0, 1, 6), repeat=3) if sum(i) == 1]) # array([[ 0. , 0. , 1. ], # [ 0. , 0.2, 0.8], # [ 0. , 0.4, 0.6], # [ 0. , 0.6, 0.4], # [ 0. , 0.8, 0.2], # [ 0. , 1. , 0. ], # [ 0.2, 0. , 0.8], # [ 0.2, 0.2, 0.6], # [ 0.2, 0.4, 0.4], # [ 0.2, 0.6, 0.2], # [ 0.2, 0.8, 0. ], # [ 0.4, 0. , 0.6], # [ 0.4, 0.2, 0.4], # [ 0.4, 0.4, 0.2], # [ 0.4, 0.6, 0. ], # [ 0.6, 0. , 0.4], # [ 0.6, 0.2, 0.2], # [ 0.6, 0.4, 0. ], # [ 0.8, 0. , 0.2], # [ 0.8, 0.2, 0. ], # [ 1. , 0. , 0. ]])
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/49289417
type: Answer
answers question: http://stackoverflow.com/q/49289417

http://stackoverflow.com/q/49430954
tagged with: multithreading
tagged with: multiprocessing
type: Question
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/85863922
has title: How to get actual core number from multiprocessing pool worker?
has comment: http://stackoverflow.com/comment/85864483
tagged with: threadpool
has comment: http://stackoverflow.com/comment/85863833
tagged with: python
has comment: http://stackoverflow.com/comment/85863780
has comment: http://stackoverflow.com/comment/85870031
score: 0
has body: I have created a multi threaded program using multiprocessing pool. I have a 10 core machine and I want to log the core number (from 1 to 10) for each task. But when I run the program it does the operation in parallel, however the thread numbers I am getting is starting from 3 and goes to 12. Sometimes more than 12. I expect to see the numbers from 1 to 10. How could i achieve that? This is how pool is defined : with Pool(initializer=_initializer, initargs=(config, cfg)) as p: logger.info('Getting conversion queue') cursor.execute(const.SQL_S_FILES,{}) file_ids = cursor.fetchall() if file_ids: logger.info('Queueing %d files', len(file_ids)) p.starmap(process, file_ids, chunksize=1) else: logger.info('Empty queue, rechecking in %ds', SLEEP) And this is I am getting the worker number: worker_number= multiprocessing.current_process().name.split("-",1)[1]
linked to: http://stackoverflow.com/q/14004036
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49435215
has comment: http://stackoverflow.com/comment/85872318
upvote count: 2
score: 1
has title: Iterating through strings in list and concatenating to string before it if string meets conditions
has comment: http://stackoverflow.com/comment/85872410
has comment: http://stackoverflow.com/comment/85872600
downvote count: 1
has comment: http://stackoverflow.com/comment/85872477
answer count: 1
has comment: http://stackoverflow.com/comment/85872386
has comment: http://stackoverflow.com/comment/85873564
has comment: http://stackoverflow.com/comment/85872414
has body: I have a list composed of many strings that have been split at '\n'. However, in the raw text file itself, there are a few newlines inserted in the middle of an entry, which makes things confusing. I want to iterate through the list and ask if the first character is equal to 'r' or 'i'. If not, I want to concatenate that string with the one before it. This is an excerpt of what my current list looks like: [‘rs386834028,46662406,1,No summary provided.,http://www.snpedia.com/index.php/Rs386834028(CA;CA)', 'rs121909207,94480221,1,"common in clinvar', '",http://www.snpedia.com/index.php/Rs121909207(C;C)'] The first element in the list is what I want all elements of the list to look like. I want the second and the third to be concatenated together to look as such: [‘rs386834028,46662406,1,No summary provided.,http://www.snpedia.com/index.php/Rs386834028(CA;CA)', 'rs121909207,94480221,1,"common in clinvar,http://www.snpedia.com/index.php/Rs121909207(C;C)'] This is what my code looks like right now: import io def readSNP(filename1): f = io.open(filename1, mode='r', encoding='utf8') fileAsOneString = f.read() splitList = fileAsOneString.split('\n') for string in splitList: for i in range(len(string)): if (i[0] =! 'r' or i[0] =! 'i'): And that's where I get stuck. Any help/suggestions would be appreciated!
has comment: http://stackoverflow.com/comment/85873465
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49435413
has comment: http://stackoverflow.com/comment/85872523

http://stackoverflow.com/comment/85583719
comment on: http://stackoverflow.com/q/49290103
score: 2
has text: `filetest.txt` is probably not an executable file.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49324898
answer count: 1
has title: Combining dataframes so that column entries in left side equal column entries in right side and if not return null
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49324936
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
tagged with: join
upvote count: 1
has body: so I have two data frames to start with in pandas. One data frame has more columns than the other In the larger one, some of those columns contain identical rows as those in the smaller frame. I want to combine the two data frames so that the rows in both frames that are equal result in one row, and the rows that are NOT equal lead to a null. Here is a picture of what I mean: Setup df1 = pd.DataFrame( [[1, 3, 'alpha'], [2, 4, 'beta']], columns=['a', 'b', 'features']) df2 = pd.DataFrame([[5, 6], [1, 3]], columns=['u', 'v']) How could this be done in pandas? How about in SQL?
downvote count: 1

http://stackoverflow.com/q/49413139
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49413208
answer count: 1
tagged with: arrays
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have a pickled file that contain a hash with key -> list like this h = { 'two': [1,2], 'three': [3,4,5]} I want to convert the arrays into an array of array, making the arrays of the same length (just filling up with zeros for the shorter arrays) So the example above I would like to have a result like this &gt;&gt;&gt; np.asarray([[1,2,0],[3,4,5]]) array([[1, 2, 0], [3, 4, 5]]) (I don't care about the keys in the hash, and I also don't care about the order of the arrays). The first step would be to find the longest array, which I think this code will do for me m = max(map(len, h.values())) But how do I create the arrays after that? I thought numpy.copyto() would be possible; copying the original array into a new array filled with zeros and the new length, but it demands arrays of the same shapes.
has answer: http://stackoverflow.com/a/49413208
score: 1
has title: how do I make arrays to be of the same length
tagged with: python
tagged with: numpy

text
tags question: http://stackoverflow.com/q/49292334
tags question: http://stackoverflow.com/q/49368882
tags question: http://stackoverflow.com/q/49411664
tags question: http://stackoverflow.com/q/49316102
tags question: http://stackoverflow.com/q/49368302
tags question: http://stackoverflow.com/q/49333206
tags question: http://stackoverflow.com/q/49291355
tags question: http://stackoverflow.com/q/49343043
type: Tag
tags question: http://stackoverflow.com/q/49412685
tags question: http://stackoverflow.com/q/49349872
tags question: http://stackoverflow.com/q/49323865
tags question: http://stackoverflow.com/q/49314702
tag name: text
tags question: http://stackoverflow.com/q/49432799
tags question: http://stackoverflow.com/q/49424846
tags question: http://stackoverflow.com/q/49330720

http://stackoverflow.com/comment/85573404
comment on: http://stackoverflow.com/q/49285076
score: 0
type: Comment
has text: There are several ways to do it, depending on the objective. You say users should be able to have multiple projects; should projects also have multiple users? If so, you can add a `ManyToManyField` on `Project`. If not, it should be a `ForeignKey`. If it's a `ManyToManyField`, it can be on either `Project` or `Profile`, but I think semantically it makes more sense on `Project`, linking it to the `User`, and not to the `Profile`.
type: QuestionComment

http://stackoverflow.com/a/49411868
accepted answer of: http://stackoverflow.com/q/49409322
has comment: http://stackoverflow.com/comment/85830429
has comment: http://stackoverflow.com/comment/85828163
has comment: http://stackoverflow.com/comment/85826431
has body: After you ran Pyinstaller for the first time, it should have created a main.spec file. You can edit the main.spec file to add any additional resources that your app requires (in addition to what Pyinstaller detects). Then you can run Pyinstaller with the simple command: pyinstaller main.spec Note that most of the options to Pyinstaller have no effect when you provide a spec file argument (all that info should be in the spec file). For more information see Pyinstaller docs.
score: 1
has comment: http://stackoverflow.com/comment/85830266
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49409322
has comment: http://stackoverflow.com/comment/85830611
downvote count: 0
has comment: http://stackoverflow.com/comment/85828040
type: Answer

http://stackoverflow.com/comment/87701949
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49302187
has text: With autoflush enabled, you can still flush each row (or column) so you get a nice compromise between speed and visual feedback. See this [example of doing just that](https://stackoverflow.com/a/43969992/5771269)

http://stackoverflow.com/a/49350600
type: Answer
has body: The problem is your allow clause. It's regex so you must escape special symbols like '?'. This works fine (backslash before ?): Rule(LinkExtractor(allow=['https://finviz.com/screener.ashx\?v=111&amp;r=[0-9]{2}']), callback='parse_screener', follow=True)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49350210
score: 2
answers question: http://stackoverflow.com/q/49350210

http://stackoverflow.com/comment/85626853
score: 0
has text: Seams like you need to look up how to open and read a file in Python, this is well documented: https://docs.python.org/3/library/filesys.html
comment on: http://stackoverflow.com/q/49312476
type: Comment
type: QuestionComment

beautifulsoup
tags question: http://stackoverflow.com/q/49368348
tags question: http://stackoverflow.com/q/49358679
tags question: http://stackoverflow.com/q/49348204
tags question: http://stackoverflow.com/q/49381338
tags question: http://stackoverflow.com/q/49419577
tags question: http://stackoverflow.com/q/49286760
tags question: http://stackoverflow.com/q/49301649
tags question: http://stackoverflow.com/q/49338793
type: Tag
tags question: http://stackoverflow.com/q/49367115
tags question: http://stackoverflow.com/q/49375620
tags question: http://stackoverflow.com/q/49332852
tags question: http://stackoverflow.com/q/49337956
tags question: http://stackoverflow.com/q/49351322
tags question: http://stackoverflow.com/q/49396249
tags question: http://stackoverflow.com/q/49426387
tags question: http://stackoverflow.com/q/49378038
tags question: http://stackoverflow.com/q/49288932
tags question: http://stackoverflow.com/q/49290704
tags question: http://stackoverflow.com/q/49338402
tags question: http://stackoverflow.com/q/49371947
tags question: http://stackoverflow.com/q/49374323
tags question: http://stackoverflow.com/q/49294642
tags question: http://stackoverflow.com/q/49388091
tags question: http://stackoverflow.com/q/49285184
tags question: http://stackoverflow.com/q/49402888
tags question: http://stackoverflow.com/q/49389636
tags question: http://stackoverflow.com/q/49347379
tags question: http://stackoverflow.com/q/49350136
tags question: http://stackoverflow.com/q/49359684
tags question: http://stackoverflow.com/q/49322145
tags question: http://stackoverflow.com/q/49407711
tags question: http://stackoverflow.com/q/49297836
tags question: http://stackoverflow.com/q/49395395
tags question: http://stackoverflow.com/q/49427372
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49375881
tags question: http://stackoverflow.com/q/49336477
tags question: http://stackoverflow.com/q/49352735
tags question: http://stackoverflow.com/q/49356195
tags question: http://stackoverflow.com/q/49407797
tags question: http://stackoverflow.com/q/49396106
tags question: http://stackoverflow.com/q/49392258
tags question: http://stackoverflow.com/q/49283439
tags question: http://stackoverflow.com/q/49312665
tags question: http://stackoverflow.com/q/49366051
tags question: http://stackoverflow.com/q/49395702
tags question: http://stackoverflow.com/q/49434230
tags question: http://stackoverflow.com/q/49424015
tags question: http://stackoverflow.com/q/49318015
tags question: http://stackoverflow.com/q/49280311
tags question: http://stackoverflow.com/q/49348263
tags question: http://stackoverflow.com/q/49428951
tags question: http://stackoverflow.com/q/49344251
tags question: http://stackoverflow.com/q/49413362
tags question: http://stackoverflow.com/q/49380186
tags question: http://stackoverflow.com/q/49305436
tags question: http://stackoverflow.com/q/49343236
tags question: http://stackoverflow.com/q/49342892
tags question: http://stackoverflow.com/q/49378655
tags question: http://stackoverflow.com/q/49287325
tags question: http://stackoverflow.com/q/49389812
tags question: http://stackoverflow.com/q/49416965
tags question: http://stackoverflow.com/q/49353954
tags question: http://stackoverflow.com/q/49310355
tags question: http://stackoverflow.com/q/49304356

http://stackoverflow.com/comment/85843474
comment on: http://stackoverflow.com/a/49421199
score: 0
type: AnswerComment
has text: To join the tuples with `,`
type: Comment

http://stackoverflow.com/comment/85787364
score: 0
comment on: http://stackoverflow.com/q/49392840
type: QuestionComment
has text: Also, watch out for using slices/chained assignment
type: Comment

http://stackoverflow.com/q/49365992
type: AnsweredQuestion
has title: Python openpyxl read until empty cell
has answer: http://stackoverflow.com/a/49368567
possible better answer: http://stackoverflow.com/a/49368567
has answer: http://stackoverflow.com/a/49366265
tagged with: python
has body: I'm trying to read one column out of my Excel-file until it hits an empty cell, then it needs to stop reading. My code so far: import openpyxl import os def main(): filepath = os.getcwd() + "\test.xlsx" wb = openpyxl.load_workbook(filename=filepath, read_only=True) ws = wb['Tab2'] for i in range(2, 1000): cellValue = ws.cell(row=i, column=1).Value if cellValue != None: print(str(i) + " - " + str(cellValue)) else: break; if __name__ == "__main__": main() By running this i get the following error when it hits an empty cell. Does anybody know how i can prevent this from happening. Traceback (most recent call last): File "testFile.py" in &lt;module&gt; main() cellValue = sheet.cell(row=i, column=1).value File "C:\Python34\lib\openpyxl\worksheet\worksheet.py", line 353, in cell cell = self._get_cell(row, column) File "C:\Python34\lib\openpyxl\worksheet\read_only.py", line 171, in _get_cell cell = tuple(self.get_squared_range(column, row, column, row))[0] IndexError: tuple index out of range
favorite count: 0
type: Question
upvote count: 2
score: 2
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/49366265
tagged with: openpyxl
downvote count: 0
tagged with: excel

http://stackoverflow.com/q/49341471
has comment: http://stackoverflow.com/comment/85683304
answer count: 1
tagged with: tensorflow
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85683135
type: UnansweredQuestion
has body: i have this table and the main problem is ID ,W_Weight are not the same length as Class column Note: Every Number of ID is associated with a Class, For example ( the ID 0 have Class 1.0 and ID 4 have Class 5.0 ) ID W_Weight Class 0 0 0.255265 1.0 1 0 0.273844 1.0 2 0 0.351219 1.0 3 0 0.262033 1.0 4 0 0.351219 5.0 5 0 0.258109 1.0 6 0 0.296328 5.0 7 0 0.351219 1.0 8 0 0.301208 1.0 9 0 0.273844 1.0 10 0 0.317767 1.0 11 1 0.299451 1.0 12 1 0.327183 5.0 13 1 0.391577 1.0 14 1 0.272526 1.0 15 1 0.412015 1.0 16 1 0.412015 1.0 17 1 0.287148 1.0 18 1 0.168667 5.0 19 1 0.257689 1.0 20 1 0.242609 1.0 21 2 0.190351 5.0 22 2 0.204205 5.0 23 2 0.254588 5.0 24 2 0.261904 1.0 25 2 0.195398 5.0 26 2 0.248913 5.0 27 2 0.161089 1.0 28 2 0.240355 5.0 29 2 0.261904 1.0 ... ... ... ... 410722 32742 0.190023 NaN 410723 32742 0.190023 NaN 410724 32742 0.184970 NaN 410725 32742 0.166998 NaN 410726 32742 0.196789 NaN 410727 32742 0.171033 NaN 410728 32742 0.207060 NaN 410729 32742 0.171033 NaN 410730 32742 0.179186 NaN 410731 32742 0.207060 NaN 410732 32742 0.182852 NaN 410733 32742 0.146492 NaN 410734 32742 0.141293 NaN 410735 32742 0.193123 NaN 410736 32742 0.207060 NaN 410737 32742 0.092576 NaN 410738 32742 0.207060 NaN 410739 32742 0.160762 NaN 410740 32742 0.165249 NaN 410741 32742 0.207060 NaN 410742 32742 0.184970 NaN 410743 32742 0.147506 NaN 410744 32742 0.207060 NaN 410745 32742 0.190023 NaN 410746 32742 0.116286 NaN 410747 32742 0.070032 NaN 410748 32742 0.207060 NaN 410749 32742 0.166998 NaN 410750 32742 0.147506 NaN 410751 32742 0.207060 NaN The desired table should look like this Note: the first line with index 0 is just an example, i want to do this for all the data in W_Weight column ID W_Weight Class 0 0 {0.25,0.27,0.35,0.26,0.35,0.25,0.29,0.35,0.30,0.27,0.31} 1.0 11 1 0.299451 1.0 12 1 0.327183 5.0 13 1 0.391577 1.0 14 1 0.272526 1.0 15 1 0.412015 1.0 16 1 0.412015 1.0 17 1 0.287148 1.0 18 1 0.168667 5.0 19 1 0.257689 1.0 20 1 0.242609 1.0 21 2 0.190351 5.0 22 2 0.204205 5…
has comment: http://stackoverflow.com/comment/85683011
has comment: http://stackoverflow.com/comment/85683111
tagged with: python
has title: Pandas DataFrame: Collect Column Values to one Row
has comment: http://stackoverflow.com/comment/85683212
score: 0
has answer: http://stackoverflow.com/a/49341564
tagged with: pandas

http://stackoverflow.com/comment/85757745
type: Comment
has text: I think your problem is in the way you invoke this two functions rather than in the dataset. You should update your question with the code you use to obtain that result.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49376334

http://stackoverflow.com/q/49296268
has answer: http://stackoverflow.com/a/49296319
score: 1
has title: opencv for windows XP
downvote count: 1
tagged with: windows-xp
has body: I'm working with opencv in my last study's project. I have python 2.7 x86 and opencv 3.4 already installed. I developed my python project in windows 8 64 bit and I converted my application from .py to .exe through Pyinstaller and it's working fine . But when I move my application to the industrial machine which is windows xp pack 3 32bit and i try to import cv2 I get the following error : ImportError: DLL load failed: The specified module could not be found. Note that I have tried to install Microsoft visual c++ 2015 and didn't solve the problem and I try everything said about this problem on stackoverflow and didn't work with me . Can anyone help me here ?
has comment: http://stackoverflow.com/comment/85795621
favorite count: 0
type: Question
upvote count: 2
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59700899
tagged with: python
tagged with: opencv

http://stackoverflow.com/a/49342675
has body: Alright I figured out a solution! Maybe not the best way, but it works for me! I changed html from: Company Name Add New Company ---------------------------- Select Company {% if custs %} {% for cust in custs %} {{ cust.lname }} {% endfor %} {% endif %} Phone Number to: Company Name Add New Company ---------------------------- Select Company {% if custs %} {% for cust in custs %} {{ cust.lname }} <-------HERE----- {% endfor %} {% endif %} Phone Number I added a 'value' tag to the option, so as the template loads the {{ cust.lname }} into the dropdown, it also loads the {{ cust.pn }} for that particular selection. Then I changed my Jquery from: $('#comp_name').on('change', function() { var cust_pn; for cust in custs { if ($(this).val() == cust.customer_name) { $('#pn').val() = cust.customer_phone_number; } } }); To: $('#comp_name').on('change', function() { $('#pn').val($(this).val()); }); Works perfectly!
answers question: http://stackoverflow.com/q/49340821
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49340821

http://stackoverflow.com/comment/85752739
type: Comment
type: QuestionComment
has text: The line`imgs.show(img)` I change to `imgs.append(img)`,but the answer of `X_train` also is 0.
score: 0
comment on: http://stackoverflow.com/q/49346257

http://stackoverflow.com/q/49435647
has answer: http://stackoverflow.com/a/49435683
tagged with: ldap
tagged with: django-models
tagged with: python
tagged with: django-forms
type: Question
has body: I am trying to show LDAP-attributes of a user by using the django-ldapdb library. First of all I made a new model: models.py class LdapUser(ldapdb.models.Model): base_dn = u"CN=XXX,CN=Users,DC=domain,DC=com" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] # inetOrgPerson phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) I want to display these in my webapp with forms. class LdapUserForm(ldapdb.models.Model): class Meta: model = LdapUser fields = ( 'phone', 'mobile_phone' ) I did all my migrations and but when I run my code it gives me the following error. raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) TypeError: 'class Meta' got invalid attribute(s): fields,model I looked it up but could not find anything helpful. So I hope someone on stacko has a solution for me. Thanks in advance
has title: TypeError: 'class Meta' got invalid attribute(s): fields,model
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: django

http://stackoverflow.com/comment/85789401
type: AnswerComment
comment on: http://stackoverflow.com/a/49311351
has text: @Mike You have received two good answers here. Please consider accepting one of them as a formal answer to your question by clicking the checkmark below the answer score. Now that you've gained more than 15 rep points, you also have the opportunity to upvote one or both of them.
score: 0
type: Comment

http://stackoverflow.com/a/49437703
has body: Omitting a value in a slice is equivalent to using None, so I may suggest this function signature: def slice_(arr, start=None, stop=None, step=None): return arr[start:stop:step] Recommend not to use the name slice for your function, because it shadows the built-in class. Note: You don't need to define your own function for this functionality. A more Pythonic way of slicing an object with dynamic input would be with using getitem directly: arr[slice(a,b,step)]
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/49437653
type: Answer
score: 2

http://stackoverflow.com/comment/85643373
has text: @jpp The columns are definitely there. Check the post again - I've just updated it showing the columns :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49321065

http://stackoverflow.com/comment/95086887
type: AnswerComment
has text: @Light_B The scale is chosen based on the levels. The colors on the scale are chosen by `vmin/vmax` or `norm` (I think if both are given, norm should take precedence).
score: 1
comment on: http://stackoverflow.com/a/49283519
type: Comment

http://stackoverflow.com/comment/85584524
score: 0
comment on: http://stackoverflow.com/q/49290704
type: Comment
type: QuestionComment
has text: Sounds like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). If you are going through the trouble to manually click a button in your browser to update the HTML, why don't you instead manually update the HTML in a text editor?

http://stackoverflow.com/q/49358586
tagged with: jupyter
type: Question
upvote count: 2
score: 2
has title: Jupyter Bokeh: Non-existent column name in glyph renderer
accepted answer: http://stackoverflow.com/a/49457437
answer count: 1
downvote count: 0
has body: I have a GlyphRenderer whose data_source.data is {'index': [0, 1, 2, 3, 4, 5, 6, 7], 'color': ['#3288bd', '#66c2a5', '#abdda4', '#e6f598', '#fee08b', '#fdae61', '#f46d43', '#d53e4f']} The renderer's glyph is Oval(height=0.1, width=0.2, fill_color="color") When rendering, I see E-1001 (BAD_COLUMN_NAME): Glyph refers to nonexistent column name: color [renderer: GlyphRenderer(id='1d1031f5-6ee3-4744-a0f7-22309798e313', ...)] I'm clearly missing something, but this is pretty much lifted from published examples. I verified in a debugger that data_source.column_names is just ['index']; what I don't understand is why the 'color' column doesn't appear in the data source's column_names, or why Bokeh produces this warning (the graph appears to be correctly rendered). The complete source is available at https://pastebin.com/HXAEEujP
has answer: http://stackoverflow.com/a/49457437
favorite count: 0
type: AnsweredQuestion
tagged with: python
tagged with: bokeh

http://stackoverflow.com/q/49335903
tagged with: python
has answer: http://stackoverflow.com/a/49356101
score: 0
has body: I get an error when I execute python2 -m pip freeze this command. The error message is as below: /usr/bin/python: cannot import name HashMissing; 'pip' is a package and cannot be directly executed I had used apt-get remove --purge python python-pip fo removing the python2. Then, I do these path checking for knowing pip and python command path. john@mymachine:~$ whereis python python: /usr/bin/python /usr/bin/python3.4m /usr/bin/python3.4 /usr/bin/python2.7 /usr/bin/python2.7-config /usr/lib/python3.4 /usr/lib/python2.7 /etc/python3.4 /etc/python2.7 /usr/local/lib/python3.4 /usr/local/lib/python2.7 /usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz john@mymachine:~$ which -a pip /usr/local/bin/pip jonh@mymachine:~$ whereis pip pip: /usr/local/bin/pip /usr/local/bin/pip3.5 /usr/local/bin/pip2.7 /usr/local/bin/pip3.4 john@mymachine:~$ which -a python /usr/bin/python Wish some help.
has title: python2 -m pip freeze showing an error
has comment: http://stackoverflow.com/comment/85673555
answer count: 1
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/85673638
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85673473
has comment: http://stackoverflow.com/comment/85673442

http://stackoverflow.com/comment/85778098
comment on: http://stackoverflow.com/q/49388091
type: QuestionComment
has text: It appears that this is one of those sites whose pages are built within the browser using javascript. You should consider using a product such as Selenium for scraping it.
score: 0
type: Comment

http://stackoverflow.com/a/49393627
answers question: http://stackoverflow.com/q/49301489
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49301489
has body: after some time I managed to use select without it blocking my TKinter code, for now i configured some random button(b5) to send a message (which should be blocking) def rms_window(waiter): """MAIN WAITER'S WINDOW""" window = waiter.get_window() # Main window called from the waiter class. activate_window(window, 600, 482) # 600x482 bg_icon = ImageTk.PhotoImage(Image.open('bg_icon.png')) # Image background picture. bg_label = Label(window, height=482, width=600, image=bg_icon) # Create an image label for the window background. bg_label.place(x=0, y=0) order_list = Listbox(window, height=10, width=30, bg='white', fg='brown') # Order list ListBox. sort_gui(window, order_list) # sort scrollbar, labels and order list inside the waiter's window. menu_icon = ImageTk.PhotoImage(Image.open('menu_icon.png')) # Image of the menu button. b1 = Button(window, image=menu_icon) # Append button to the main window and apply picture. set_gui(b1, 'Menu', 'cyan', 'cyan') b1.configure(command=lambda i=waiter.get_socket(): open_menu(waiter, order_list)) # on click - open menu window. b1.grid(row=0, column=0) t1 = Text(window, width=25, height=1, bg='brown') # Simple text box used to read bill number in the bill button t1.grid(row=14, column=0) b2 = Button(window) # Bill button - reads text from variable t1 and sends the bill of the number given. set_gui(b2, 'Bill', 'pale goldenrod', 'chocolate') b2.configure(command=lambda i=waiter.get_socket(): send_bill('BILL ' + t1.get(1.0, END), i)) b2.grid(row=15, column=0) # Sends the bill to the server once you type an order number inside the textbox. b3 = Button(window) set_gui(b3, 'SEND ORDER', 'brown', 'chocolate') b3.configure(command=lambda i=waiter: i.send_order(order_list)) # On click send the whole order list to the server. b3.grid(row=10, column=0) # Send the order listed in the list box widget. chat_icon = ImageTk.PhotoImage(Image.open("chat_icon.png")) b4 = Button(window, image=chat_icon) # Apply chat icon image to waiters chatting butto…

http://stackoverflow.com/q/49317898
has comment: http://stackoverflow.com/comment/85637263
tagged with: python
tagged with: dictionary
has title: Why aren't I getting the correct Len of the number of elements in a key?
downvote count: 1
has body: def wordPattern(pattern, str): """ :type pattern: str :type str: str :rtype: bool """ list_pattern = list() list_str = list() for letter in pattern: list_pattern.append(letter) for word in str.split(): list_str.append(word) new_dict = {} c = 0 for letter in list_pattern: if letter not in new_dict: new_dict[letter] = '' if list_str[c] not in new_dict[letter]: new_dict[letter] = list_str[c] c = c + 1 for key in new_dict: if len(new_dict[key]) != 1: print (len(new_dict[key])) print (new_dict[key]) print ('false') print ('true') print(new_dict) wordPattern("abba","dog cat cat dog") Question I'm trying to solve is : Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Examples: pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false. Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. The outcome: 3 dog false 3 cat false true {'a': 'dog', 'b': 'cat'} I can't understand why I'm getting 3 as Len(list_name[key_name]) while it's visibly 1? Kindly note that I understand there's probably better ways etc but I'm starting to learn and I want to understand my mistake.
has comment: http://stackoverflow.com/comment/85637415
has comment: http://stackoverflow.com/comment/85636981
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/49318176
has comment: http://stackoverflow.com/comment/85637022
has comment: http://stackoverflow.com/comment/85637157
answer count: 1
score: -1
has answer: http://stackoverflow.com/a/49318176
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85637584
upvote count: 0

http://stackoverflow.com/a/49379282
score: 1
accepted answer of: http://stackoverflow.com/q/49378948
has comment: http://stackoverflow.com/comment/85759446
answers question: http://stackoverflow.com/q/49378948
has comment: http://stackoverflow.com/comment/85759513
has comment: http://stackoverflow.com/comment/85760976
type: Answer
has body: If you have numpy installed try this: import numpy as np #Create a list for Y y = [140,150,160,135,170,180] #Convert to numpy array Y = np.asarray(y).reshape(6,1) #Create a list for X x = [[1,10,1],[1,15,1],[1,20,1],[1,12,1],[1,16,1],[1,20,1]] #Convert to numpy array X = np.asarray(x).reshape(6,3) #Multiply using np.matmul for matrix multiplication beta = np.matmul(np.matmul(np.matmul(X.T,X),X.T),Y) Otherwise, prior to running the above lines of code on the python interpreter, install numpy using your Python package manager. The equivalent command for pip is: sudo pip install numpy
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85813000
type: Comment
comment on: http://stackoverflow.com/a/49405706
score: 0
type: AnswerComment
has text: I am trying to have some continuous plotting until the user closes the application ideally. Not sure of the best way to do this

http://stackoverflow.com/q/49283774
tagged with: nltk
has answer: http://stackoverflow.com/a/66302697
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49285084
answer count: 3
accepted answer: http://stackoverflow.com/a/49296135
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/49296135
downvote count: 0
has body: i'm learning a lot about Natural Language Processing with nltk, can do a lot of things, but I'm not being able to find the way to read Texts from the package. I have tried things like this: from nltk.book import * text6 #Brings the title of the text open(text6).read() #or nltk.book.text6.read() But it doesn't seem to work, because it has no fileid. No one seems to have asked this question before, so I assume the answer should be easy. Do you know what's the way to read those texts or how to convert them into a string? Thanks in advance
has title: How to read nltk.text.Text files from nltk.book in Python?
possible better answer: http://stackoverflow.com/a/49285084
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85593963

plotly
tags question: http://stackoverflow.com/q/49405265
tag name: plotly
tags question: http://stackoverflow.com/q/49402400
type: Tag
tags question: http://stackoverflow.com/q/49371248
tags question: http://stackoverflow.com/q/49351985
tags question: http://stackoverflow.com/q/49413895
tags question: http://stackoverflow.com/q/49400465
tags question: http://stackoverflow.com/q/49396696
tags question: http://stackoverflow.com/q/49419718
tags question: http://stackoverflow.com/q/49437764

http://stackoverflow.com/comment/85746647
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49372550
type: Comment
has text: Can you try using an absolute file path rather than just a filename? e.g. point to a specific directory somewhere - such as /home/me/dogs.txt or c:/dogs.txt if on Windows.

http://stackoverflow.com/comment/85669205
has text: @BIKI Sorry, there were a couple of base cases I hadn't considered properly. See my update.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49333365

http://stackoverflow.com/a/57396208
answers question: http://stackoverflow.com/q/49381367
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
has body: Here is an approach to solve your problem: from django.contrib.auth.models import Group # inherit from Group instead of copy the code... class Group(Group): new_field = = models.CharField( verbose_name=('new-field'), max_length=31, ) class Meta: indexes = [ models.Index(fields=['last_name', 'first_name'], name='mixed_idx'), ] Read more about the indexs option. (alias index_together).
accepted answer of: http://stackoverflow.com/q/49381367

tensorflow
tags question: http://stackoverflow.com/q/49429666
tags question: http://stackoverflow.com/q/49416498
tags question: http://stackoverflow.com/q/49334113
tags question: http://stackoverflow.com/q/49373003
type: Tag
tags question: http://stackoverflow.com/q/49300182
tags question: http://stackoverflow.com/q/49281676
tags question: http://stackoverflow.com/q/49338837
tags question: http://stackoverflow.com/q/49341471
tags question: http://stackoverflow.com/q/49349702
tags question: http://stackoverflow.com/q/49378754
tags question: http://stackoverflow.com/q/49345671
tags question: http://stackoverflow.com/q/49351616
tags question: http://stackoverflow.com/q/49312989
tags question: http://stackoverflow.com/q/49391252
tags question: http://stackoverflow.com/q/49302240
tags question: http://stackoverflow.com/q/49339062
tags question: http://stackoverflow.com/q/49383723
tags question: http://stackoverflow.com/q/49408422
tags question: http://stackoverflow.com/q/49301203
tags question: http://stackoverflow.com/q/49430178
tags question: http://stackoverflow.com/q/49345786
tags question: http://stackoverflow.com/q/49333001
tags question: http://stackoverflow.com/q/49373068
tags question: http://stackoverflow.com/q/49394652
tags question: http://stackoverflow.com/q/49434083
tags question: http://stackoverflow.com/q/49293015
tags question: http://stackoverflow.com/q/49382615
tags question: http://stackoverflow.com/q/49376603
tags question: http://stackoverflow.com/q/49285317
tags question: http://stackoverflow.com/q/49412717
tags question: http://stackoverflow.com/q/49332994
tags question: http://stackoverflow.com/q/49435335
tags question: http://stackoverflow.com/q/49401213
tags question: http://stackoverflow.com/q/49371671
tags question: http://stackoverflow.com/q/49354294
tags question: http://stackoverflow.com/q/49302743
tags question: http://stackoverflow.com/q/49393566
tags question: http://stackoverflow.com/q/49314186
tags question: http://stackoverflow.com/q/49405965
tags question: http://stackoverflow.com/q/49430785
tags question: http://stackoverflow.com/q/49288083
tags question: http://stackoverflow.com/q/49338923
tags question: http://stackoverflow.com/q/49402739
tags question: http://stackoverflow.com/q/49343748
tags question: http://stackoverflow.com/q/49368318
tags question: http://stackoverflow.com/q/49419504
tags question: http://stackoverflow.com/q/49285911
tags question: http://stackoverflow.com/q/49439665
tags question: http://stackoverflow.com/q/49306601
tags question: http://stackoverflow.com/q/49409488
tags question: http://stackoverflow.com/q/49370642
tags question: http://stackoverflow.com/q/49398457
tags question: http://stackoverflow.com/q/49360786
tags question: http://stackoverflow.com/q/49317371
tags question: http://stackoverflow.com/q/49294326
tags question: http://stackoverflow.com/q/49294769
tags question: http://stackoverflow.com/q/49329178
tags question: http://stackoverflow.com/q/49425238
tags question: http://stackoverflow.com/q/49346793
tags question: http://stackoverflow.com/q/49305362
tags question: http://stackoverflow.com/q/49406728
tags question: http://stackoverflow.com/q/49312139
tags question: http://stackoverflow.com/q/49401260
tags question: http://stackoverflow.com/q/49365837
tags question: http://stackoverflow.com/q/49395900
tags question: http://stackoverflow.com/q/49418846
tags question: http://stackoverflow.com/q/49429160
tags question: http://stackoverflow.com/q/49346253
tags question: http://stackoverflow.com/q/49288973
tags question: http://stackoverflow.com/q/49432873
tags question: http://stackoverflow.com/q/49385722
tags question: http://stackoverflow.com/q/49433165
tags question: http://stackoverflow.com/q/49282546
tags question: http://stackoverflow.com/q/49305971
tags question: http://stackoverflow.com/q/49397209
tags question: http://stackoverflow.com/q/49293183
tags question: http://stackoverflow.com/q/49325985
tags question: http://stackoverflow.com/q/49290097
tags question: http://stackoverflow.com/q/49342820

http://stackoverflow.com/q/49399140
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49440399
has comment: http://stackoverflow.com/comment/86006351
has comment: http://stackoverflow.com/comment/86064427
downvote count: 0
favorite count: 0
tagged with: aws-lambda
has body: I am trying to execute a python function on AWS Lambda. In my function I am trying to import the mysql.connector module. But an error is throwing up : errorMessage": "No module named 'mysql.connector'" I had written my python code initially in my EC2 Instance. I installed mysql-connector there in my python file directory using pip. pip install mysql-connector -t /path/to/file/dir I uploaded the zip file of the only the file and not any folder containing the file.
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/49399201
type: Question
tagged with: python-2.7
has title: Module Import Error when executing a Lambda python function
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/55596031

http://stackoverflow.com/comment/85761649
type: Comment
has text: That's what used to be called an emoticon.
score: 1
comment on: http://stackoverflow.com/q/49380308
type: QuestionComment

http://stackoverflow.com/comment/85620786
type: AnswerComment
has text: I'm attempting this right now and getting an error. TypeError: 'float' object cannot be interpreted as an integer. I'm trying to figure out what's being considered a float here so I can convert it.
score: 0
comment on: http://stackoverflow.com/a/49308839
type: Comment

http://stackoverflow.com/q/49320007
has answer: http://stackoverflow.com/a/53653747
downvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55594547
tagged with: python
upvote count: 22
tagged with: tqdm
answer count: 4
tagged with: list
has body: I would like to know how long it takes to process a certain list. for a in tqdm(list1): if a in list2: #do something but this doesnt work. If I use for a in tqdm(range(list1)) i wont be able to retrieve the list values. Do you know how do do it?
has answer: http://stackoverflow.com/a/61223343
score: 17
tagged with: loops
has title: How to use tqdm to iterate over a list
has answer: http://stackoverflow.com/a/65234184
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85709624
has text: modified my code. you are passing tuple, but the solver needs individual arguments.
comment on: http://stackoverflow.com/a/49309844
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49362616
tagged with: pytorch
upvote count: 3
score: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49368851
has answer: http://stackoverflow.com/a/49368851
tagged with: neural-network
has body: I'm a bit confused at how CNNs and channels work. Specifically, how come these two implementations are not equal? Isn't the # of output channels just applying however many # of filters? self.conv1 = nn.Conv2d(1, 10, kernel_size=(3, self.embeds_size)) self.conv2 = nn.ModuleList([nn.Conv2d(1, 1, kernel_size=(3, self.embeds_size)) for f in range(10)]) ... conv1s = self.conv1(x) conv2s = [conv(x) for conv in self.conv2] conv2s = torch.stack(conv2s, 1).squeeze(2) print(torch.equal(conv1s, conv2s))
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has title: Understanding PyTorch CNN Channels
tagged with: deep-learning

http://stackoverflow.com/comment/85581565
type: Comment
type: QuestionComment
has text: It restarts the python shell but not the code itself.
comment on: http://stackoverflow.com/q/49289137
score: 0

http://stackoverflow.com/a/49417919
score: 4
has comment: http://stackoverflow.com/comment/85837789
accepted answer of: http://stackoverflow.com/q/49417747
type: Answer
has body: You can't do this in general.* You can do something equivalent for most of the builtin operators (like your + example), and a handful of builtin functions (like abs). They're implemented by calling special methods on the operands, as described in the reference docs. Of course that means writing a whole bunch of special methods for each of your types—but it wouldn't be too hard to write a base class (or decorator or metaclass, if that doesn't fit your design) that implements all those special methods in one place, by calling the subclass's __arg__ and then doing the default thing: class ArgyBase: def __add__(self, other): return self.__arg__() + other def __radd__(self, other): return other + self.__arg__() # ... and so on And if you want to extend that to a whole suite of functions that you create yourself, you can give them all similar special-method protocols similar to the builtin ones, and expand your base class to cover them. Or you can just short-circuit that and use the __arg__ protocol directly in those functions. To avoid lots of repetition, I'd use a decorator for that. def argify(func): def _arg(arg): try: return arg.__arg__() except AttributeError: return arg @functools.wraps(func) def wrapper(*args, **kwargs): args = map(_arg, args) kwargs = {kw: _arg(arg) for arg in args} return func(*args, **kwargs) return wrapper @argify def spam(a, b): return a + 2 * b And if you really want to, you can go around wrapping other people's functions: sin = argify(math.sin) … or even monkeypatching their modules: requests.get = argify(requests.get) … or monkeypatching a whole module dynamically a la early versions of gevent, but I'm not going to even show that, because at this point we're getting into don't-do-this-for-multiple-reasons territory. You mentioned in a comment that you'd like to do this to a bunch of someone else's functions without having to specify them in advance, if possible. Does that mean every function that ever gets constructed in any module you imp…
answers question: http://stackoverflow.com/q/49417747
upvote count: 4
has comment: http://stackoverflow.com/comment/85837903
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49405143
downvote count: 0
has comment: http://stackoverflow.com/comment/85811205
has comment: http://stackoverflow.com/comment/85811192
answers question: http://stackoverflow.com/q/49405101
has comment: http://stackoverflow.com/comment/85811944
type: Answer
has comment: http://stackoverflow.com/comment/85813155
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85813199
has body: You can use: df1 = df.astype(str).groupby('col1').agg(','.join).reset_index() print (df1) col1 col2 col3 col4 0 a. p,r u,w 0,2 1 b. q,t v,y 1,4 2 d. s x 3 If need also indices: df1 = df.astype(str).groupby('col1').agg(','.join).reset_index() df1.index = df.drop_duplicates('col1').index print (df1) col1 col2 col3 col4 row1. a. p,r u,w 0,2 row2. b. q,t v,y 1,4 row4. d. s x 3 Explanation: First cast all columns to strings by astype Then groupby and aggregate join by agg If need also indices by first values on col1 add drop_duplicates
accepted answer of: http://stackoverflow.com/q/49405101
type: AcceptedAnswer

http://stackoverflow.com/comment/85750411
comment on: http://stackoverflow.com/a/49373645
type: AnswerComment
has text: thanks! it is elegant and simple! I wouldn't think about this way.
score: 1
type: Comment

http://stackoverflow.com/a/49379585
score: 9
upvote count: 9
type: Answer
has body: After install use pip or apt, you need to restarting the runtime using “Runtime / Restart runtime…”
has comment: http://stackoverflow.com/comment/85801672
answers question: http://stackoverflow.com/q/49377436
has comment: http://stackoverflow.com/comment/85798751
downvote count: 0

http://stackoverflow.com/a/49440062
has comment: http://stackoverflow.com/comment/85884506
accepted answer of: http://stackoverflow.com/q/49439816
has comment: http://stackoverflow.com/comment/85919260
upvote count: 1
answers question: http://stackoverflow.com/q/49439816
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85891299
has body: def safe_list_get(l, i): if l and i &lt; len(l): return l[i] return {} weather_1D_ago = safe_list_get(data['city']['weather'].get('daily', []),0).get('actual', {}).get('fmt', {}) weather_2D_ago = safe_list_get(data['city']['weather'].get('daily', []),1).get('actual', {}).get('fmt', {})
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85882742

http://stackoverflow.com/comment/85744857
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49371430
has text: `where` gives a tuple, one element per dimension of the condition. Your case is 1d, so the result is a 1 element tuple.
score: 0

http://stackoverflow.com/comment/85622533
comment on: http://stackoverflow.com/a/49310215
type: AnswerComment
has text: Try changing `mystring = 'hr'`. It does not need to begin with for using `in` function.
score: 0
type: Comment

http://stackoverflow.com/comment/85771925
comment on: http://stackoverflow.com/q/49385544
type: Comment
type: QuestionComment
score: 2
has text: You don't seem to be calling your function. Your first step needs to be some very basic debugging -- put in some print statements to verify the function is being called, that variables have the values you expect, that loops are looping, etc.

http://stackoverflow.com/q/49399122
score: 2
has answer: http://stackoverflow.com/a/49400518
downvote count: 0
tagged with: amazon-ec2
has body: I have an ec2 instance"abc1"(ubuntu) and I create image from abc1. Then,I launch a new instance "abc2" from abc1 image. I want abc2 to run the script when it will be launched. So,I write the text in userdata: #!/bin/bash cd ~/env/xxx/bin/ source activate python3.6 ~/env/xxx/source/test.py I manually use these commands,it's valid.However,it doesn't work when using userdata automatically. Does anyone know how to adjust my settings? Thanks a lot.
tagged with: python
tagged with: amazon-web-services
tagged with: ubuntu
tagged with: user-data
type: AnsweredQuestion
has title: How could I run python script on aws EC2 instance(ubuntu)?
answer count: 1
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49400518

http://stackoverflow.com/q/49290059
tagged with: multidimensional-array
type: Question
accepted answer: http://stackoverflow.com/a/49321971
answer count: 2
has body: Given a ndarray of size (n, 3) with n around 1000, how to multiply together all elements for each row, fast? The (inelegant) second solution below runs in about 0.3 millisecond, can it be improved? # dummy data n = 999 a = np.random.uniform(low=0, high=10, size=n).reshape(n/3,3) # two solutions def prod1(array): return [np.prod(row) for row in array] def prod2(array): return [row[0]*row[1]*row[2] for row in array] # benchmark start = time.time() prod1(a) print time.time() - start # 0.0015 start = time.time() prod2(a) print time.time() - start # 0.0003
tagged with: python
has answer: http://stackoverflow.com/a/49321971
possible better answer: http://stackoverflow.com/a/49290086
has answer: http://stackoverflow.com/a/49290086
type: AnsweredQuestion
has title: Efficiently multiply elements of each row together
upvote count: 3
score: 3
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: numpy
tagged with: performance

http://stackoverflow.com/a/49314530
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49313604
type: AcceptedAnswer
downvote count: 0
score: 6
has body: The error message indicates that you're trying to encode to the Windows-1252 character encoding. That encoding doesn't have a representation of the less than or equal symbol. &gt;&gt;&gt; "\u2264".encode("cp1252") &gt;&gt;&gt; Traceback... [as above] The answer is to use UTF-8, an unrestricted encoding, instead of Windows-1252, a very restricted encoding. Your question doesn't include much context, but the line html_file.write(html_text) makes me think you're using Python's file protocol. The documentation for open() shows how to set the encoding, e.g. html_file = open("file.html", mode="w", encoding="utf8") Note that "the default encoding is platform dependent (whatever locale.getpreferredencoding() returns)", which is why you're getting Windows-1252 on Windows 7.
answers question: http://stackoverflow.com/q/49313604
type: Answer

http://stackoverflow.com/comment/85810575
comment on: http://stackoverflow.com/a/49404637
type: AnswerComment
has text: Yes, this was better. I think however my solution can be faster for large sets as it only reassigns a slice using loc, don't you think?
score: 0
type: Comment

http://stackoverflow.com/comment/85760057
has text: Show please the content of `package/__init__.py`, or is it empty?
score: 0
comment on: http://stackoverflow.com/q/49379399
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49305440
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49305293
accepted answer of: http://stackoverflow.com/q/49305293
type: Answer
has comment: http://stackoverflow.com/comment/85613507
has body: One problem with "expression tree" magic like SQLAlchemy uses is that not all operators can be overloaded to capture the expression. For example, you want it &lt;= 1 to be captured by it so it can be turned into a WHERE it &lt;= 1 expression in SQL? Pretty easy: class Magic: def __le__(self, other): return MagicExpression(operator.le, self, other) You build up a tree of those MagicExpression objects, and the code to turn that tree into a SQL query is pretty simple. But what if you also want to capture it in other_query and turn that into a SQL IN or BETWEEN expression? That doesn't work. For one thing, the __contains__ gets called on the other thing, not your magic thing. And, worse, whatever __contains__ returns gets converted to bool by the interpreter. So, if you try this: class Magic: def __contains__(self, other): return MagicExpression(operator.contains, other, self) … and then try it in it2, you're going to get True (or whatever MagicExpression.__bool__ returns), which isn't something you can convert into a SQL IN or BETWEEN later. And what if you try to and two conditions together? Well, you can't even overload the and operator. If the left MagicExpression is falsey, you'll just get that; otherwise, you'll get the right one. Also, of course, there's the simple problem that sometimes you want a static test that doesn't even use any of the magic things, at least for debugging purposes. "OK, something is wrong in my test on that column… what if I just test against 0 and see what the query returns?" But you can't turn count &gt; 0 into a MagicExpression if count and 0 are both plain Python integers. Some people think these limitations are acceptable. Maybe you can design things to use &amp; and | in place of and and or, and make people write the "uglier" version instead of in, and so on. So a lot of queries end up simple, but some end up a hybrid of simple and ugly—still better than all of them being ugly, right? The problem is that it can be a bit of a bug magn…
score: 2
has comment: http://stackoverflow.com/comment/85613685
upvote count: 2

http://stackoverflow.com/q/49337984
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49338024
favorite count: 0
has answer: http://stackoverflow.com/a/49338024
has body: I have an array: classes = ["banana","mango","apple"] I am trying to print this array in a specific format where in each element has to be numbered in a particular sequence. The desired output is as follows: classes = [{"banana" : 1, "mango" : 2, "apple" : 3}] I tried using a for loop as follows: classes = ["banana","mango","apple"] counter = 0 dat = [] for x in classes: counter=counter+1 d = x,":", counter dat.append(d) print(dat) While this prints [('banana', ':', 1), ('mango', ':', 2), ('apple', ':', 3)] this is far from what I require. Can someone help?
type: Question
duplicate of: http://stackoverflow.com/q/209840
has title: Mapping array to sequential numbers via dictionary
tagged with: arrays
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85676306
tagged with: list
tagged with: for-loop
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/209840
has comment: http://stackoverflow.com/comment/85676427
upvote count: 1
has comment: http://stackoverflow.com/comment/85676282

http://stackoverflow.com/a/49290110
answers question: http://stackoverflow.com/q/49289969
upvote count: 1
has body: just fix your regex for space: \s\d+\s or for any word boundary: \b\d+\b
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/49289969
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49324400
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49323183
answers question: http://stackoverflow.com/q/49323183
type: Answer
has body: To sum up. To save state consider using Redis Listen to system signals to trigger graceful shutdown like so: import signal ... def handler_stop_signals(*args, **kwargs): """ Handle system signals only SIGTERM expected to trigger this""" Log.log(__name__).info('Gracefully shutting down') my_process.shutdown() if __name__ == 'main': signal.signal(signal.SIGTERM, handler_stop_signals) No need for different process,cli, api. Register a listener and this callback will kick in once the signal is issued. For more info go here Then when you want to deploy new version with jenkins, just do your service stop or kill , then deploy and start.
has comment: http://stackoverflow.com/comment/85769609
score: 1
upvote count: 1

http://stackoverflow.com/q/49428381
tagged with: python
has answer: http://stackoverflow.com/a/54229256
upvote count: 13
type: AnsweredQuestion
tagged with: python-2.7
has body: I have installed Jupiter notebook and I only have python 2 as a default kernel. I want to change it from python 2 to python 3. How could I do that?
has answer: http://stackoverflow.com/a/72198070
has answer: http://stackoverflow.com/a/69450577
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49429021
answer count: 5
accepted answer: http://stackoverflow.com/a/49430918
possible better answer: http://stackoverflow.com/a/54229256
downvote count: 0
has title: How to change jupyter kernel from Python 2 to python 3?
has answer: http://stackoverflow.com/a/49430918
score: 13

http://stackoverflow.com/comment/85693899
has text: @RoryDaulton In this case here `format` is just as bad as `%`. Instead of risking SQL injection by manually formatting values into queries, you should let the DB engine handle that.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49347070

http://stackoverflow.com/comment/85661090
type: AnswerComment
comment on: http://stackoverflow.com/a/49328914
has text: @rpg711.....I have another method which is very similar to the one I showed here but need to pass different dataset into the argument given above. Your comment on overriding 'struck' me. I was indeed overriding self.SnapShot with SnpShot on the second method on which python was angry at. Thanks for pointing that out, fixed it. The first method you showed will work now
type: Comment
score: 0

http://stackoverflow.com/comment/85612625
has text: Possible duplicate of [How to concatenate two lists in Python?](https://stackoverflow.com/questions/1720421/how-to-concatenate-two-lists-in-python)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49304002
type: Comment

http://stackoverflow.com/comment/85606255
comment on: http://stackoverflow.com/q/49302187
has text: We need more info me thinks. Are you setting pixels one by one? Generally in computer graphics you would build a buffer array of pixels and then send that to render. You could be inefficiently calling screen updates by setting pixels one by one. Maybe build a buffer array of pixels and update?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85679346
has text: What platform? My research yields that on OSX or Windows the color may not be configurable.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49338888
score: 1

http://stackoverflow.com/a/49383063
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85767218
has body: The function name is witch(), not hexed(). So: Change this: elif main == "crypto": hexed() #THIS IS WHERE I AM CALLING ANOTHER FILE To this: elif main == "crypto": witch() #THIS IS WHERE I AM CALLING ANOTHER FILE
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49382792
answers question: http://stackoverflow.com/q/49382792
score: 1

http://stackoverflow.com/a/49328914
has comment: http://stackoverflow.com/comment/85660410
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49328730
has comment: http://stackoverflow.com/comment/85661090
has comment: http://stackoverflow.com/comment/85660367
answers question: http://stackoverflow.com/q/49328730
score: 1
has comment: http://stackoverflow.com/comment/85660286
type: Answer
has body: Well, there are two/three ways to fix this: The quick and not so smart way(you probably don't want to call a member function of an object of IDList) from pnl.exp.Engine import IDList idl = IDList(var_bus_dt, part_rltnshp, cmpnt_chrg, iday_cmpnt_chrg, [8,11,12]) part_idList = idl.get_partIDlist() The way you're expecting this to behave, as a static method: class IDList(object): @staticmethod def get_partIDlist(dsnDate, dsnExpel, dsnEOD, dsnIDay, SnapShot): prev_dt = dsnDate[dsnDate.bus_dt == prcs_dt]['prev_dt'].iloc[0] prev_partID =dsnExpel[dsnExpel['prcs_dt'] == prev_dt][dsnExpel.corp_cd == 3][dsnExpel.rltnshp_cd == 'PRIME_BROKERED']'map_id', 'part_id' part_id =dsnEOD[dsnEOD.bus_dt == prcs_dt][dsnEOD.run_cn == run_cn][dsnEOD.part_stat_cd == 'C'][dsnEOD.lvl_cd == 'A']'map_id', 'part_id' IDaypart_id = pd.DataFrame(columns=['map_id', 'part_id', 'wndw_hr_nb']) for snp in SnapShot: part_id_IDay = dsnIDay[dsnIDay.bus_dt == prcs_dt][dsnIDay.run_cn == run_cn][dsnIDay.part_stat_cd == 'C'][dsnIDay.lvl_cd == 'A'][dsnIDay.wndw_hr_nb == snp]'map_id', 'part_id' part_id_IDay['wndw_hr_nb'] = snp IDaypart_id = IDaypart_id.append(part_id_IDay) part_idList = pd.concat([part_id, part_id_IDay]) return(part_idList) from pnl.exp.Engine import IDList part_idList = IDList.get_partIDlist(var_bus_dt, part_rltnshp, cmpnt_chrg, iday_cmpnt_chrg, [8,11,12]) The IDList class isn't even doing anything, you can just define get_partIDlist() as a module-scope function in pnl.exp.Engine and change your import line to: from pnl.exp.Engine import get_partIDlist
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49361075
has comment: http://stackoverflow.com/comment/85725309
score: 0
has comment: http://stackoverflow.com/comment/85722368
has comment: http://stackoverflow.com/comment/85725727
has comment: http://stackoverflow.com/comment/85725560
has comment: http://stackoverflow.com/comment/85725286
has comment: http://stackoverflow.com/comment/85726883
has comment: http://stackoverflow.com/comment/85727501
has comment: http://stackoverflow.com/comment/85722385
has comment: http://stackoverflow.com/comment/85724414
has comment: http://stackoverflow.com/comment/85727249
type: Answer
has comment: http://stackoverflow.com/comment/85725184
has body: You need to import TextBlob from textblob module from textblob import TextBlob tweet = TextBlob(tweet) From the Docs: &gt;&gt;&gt; from textblob import TextBlob &gt;&gt;&gt; wiki = TextBlob("Python is a high-level, general-purpose programming language.") More info
answers question: http://stackoverflow.com/q/49361038
has comment: http://stackoverflow.com/comment/85722527

http://stackoverflow.com/comment/85810656
type: QuestionComment
has text: Well as you can see neither of those are expecting `request` as an argument. Again, why are you passing it?
type: Comment
comment on: http://stackoverflow.com/q/49404701
score: 0

http://stackoverflow.com/q/49431270
upvote count: 4
score: 4
type: AnsweredQuestion
has body: When building a python gensim word2vec model, is there a way to see a doc-to-word matrix? With input of sentences = [['first', 'sentence'], ['second', 'sentence']] I'd see something like*: first second sentence doc0 1 0 1 doc1 0 1 1 *I've illustrated 'human readable', but I'm looking for a scipy (or other) matrix, indexed to model.wv.index2word. And, can that be transformed into a word-to-word matrix (to see co-occurences)? Something like: first second sentence first 1 0 1 second 0 1 1 sentence 1 1 2 I've already implemented something like word-word co-occurrence matrix using CountVectorizer. It works well. However, I'm already using gensim in my pipeline and speed/code simplicity matter for my use-case.
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49589053
linked to: http://stackoverflow.com/q/35562789
tagged with: gensim
has answer: http://stackoverflow.com/a/49539666
tagged with: nlp
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49589053
has title: word co-occurrence matrix from gensim
possible better answer: http://stackoverflow.com/a/49539666
tagged with: python

http://stackoverflow.com/a/49310737
has body: Note that cv2.calcHist returns a 1D array, not an image, so you cannot save it with cv2.imwrite, but rather use a standard data file, such as CSV (comma separated values) for instance. If it's OK for you to store only one histogram per file, the easiest solution is to use a simple text file: import cv2 import numpy as np from matplotlib import pyplot as plt image = cv2.imread(image_path) hist = cv2.calcHist([image], [0], None, [256], [0,256]) with open('histo.txt', 'w') as file: file.write(list(hist)) # save 'hist' as a list string in a text file then later: with open('histo.txt', 'r') as file: hist = np.array(eval(file.read()) # read list string and convert to array On the other hand, if your goal is not to save but to plot the histogram, matplotlib may be the easiest tool for that. This code snippet plots all three histograms for the R, G and B channels of your image: import cv2 import numpy as np from matplotlib import pyplot as plt image = cv2.imread(image_path) colors = ('b','g','r') for n, color in enumerate(colors): hist = cv2.calcHist([image], [n], None, [256], [0,256]) plt.plot(hist, color=color) plt.xlim([0, 256]) plt.show()
has comment: http://stackoverflow.com/comment/85647586
has comment: http://stackoverflow.com/comment/85649819
upvote count: 2
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85646014
has comment: http://stackoverflow.com/comment/85653843
answers question: http://stackoverflow.com/q/49310466

http://stackoverflow.com/a/49287201
type: Answer
answers question: http://stackoverflow.com/q/49286496
score: 0
has comment: http://stackoverflow.com/comment/85680536
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85582311
has body: I don't know how much Dropout(0.5) is helping your model. It seems that BatchNormalization() may be a good replacement. You may want to consider a LSTM layer after your the embedding layer. You can add dropout to LSTM directly. E.g.: model.add(LSTM(lstm_out, dropout_U=0.2, dropout_W=0.2)) For a nice full example, I'd invite you to review this model: https://www.kaggle.com/ngyptr/lstm-sentiment-analysis-keras Hope this helps and good luck! Edit: Based on my comment below I think your model may be training on non-character tokens because if you use this text_to_array(self,path) function, your validation accuracy is .79, .85, and .87: import re def text_to_array(self,path): ''' Takes a path argument and retrieves all the text lines from within a folder''' name_list = [] texts = [] for file_ in os.listdir(path): name_list.append(file_) for i in name_list: file_ = open(path+i) for line in file_.read().splitlines(): # I just preprocessed your text here texts.append(re.sub('[^a-zA-z0-9\s]','',line.lower())) return texts Please let me know if this helps.
has comment: http://stackoverflow.com/comment/85626059
accepted answer of: http://stackoverflow.com/q/49286496

http://stackoverflow.com/comment/85730451
has text: @Marat Thank you so much for your help! :) As I am new to Arduino, I will read up on the function and hopefully, try it tonight! :) I will update you again on the results. (:
comment on: http://stackoverflow.com/q/49343682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49340845
has body: I am setting up tensorflow-gpu version. I had python 3.6.4 installed before but it is said this version doesn't support my current NVDIA GPU so i downloaded 3.5.x which works perfectly right now. So I have 3 versions right now, 2.7 3.5,3.6. But the python version management now is a mess. Since I have changed my environment variable to E:\Python35\Scripts typing 'python' won't invoke python shell now, but 'py' does.And it seems to invoke the newest 3,6.4 version. I actually hope it could invoke 3.5.x instead. But the weird thing is when i use pip3 to install no matter what, it would use the pip3 of python35. I guess thats because I set python35 in environment variable. But to summarize my questions: 1.if assume I set both pip3 of python36 and python35 in my %PATH%, which one it will use when i type pip3? 2.why 'py' command will work? how to make pip3 and python keyword work at the same time? pip3 needs E:\Python35\Scripts while 'python' will need E:\Python35 which seems to be a conflict. Sorry if this is a stupid question, but i am new to this. Would also appreciate some documentations where the explanations are, there are just plenty of things on the internet and would cost hours to find. Thanks in advance! Guess i am spending more time on trying to save a little of not typing py -3.5 or py -3.6 everytime...
tagged with: python-2.7
score: 0
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85682431
tagged with: python-3.x
has title: different versions of python on the same windows10 computer confusions
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85681891

http://stackoverflow.com/q/49327296
accepted answer: http://stackoverflow.com/a/49327656
tagged with: telegram
downvote count: 0
score: 18
tagged with: python
upvote count: 18
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/70537997
answer count: 2
tagged with: bots
has answer: http://stackoverflow.com/a/49327656
has title: How to send bold text using Telegram Python bot
has answer: http://stackoverflow.com/a/70537997
has body: I am writing a telegram bot in Python. I want to send messages with bold letters. I tried to inclose message inside both * and **, but it does not solve the problem. Is there a function for mark up or HTML formatting or a way to do it?
linked to: http://stackoverflow.com/q/8924173
favorite count: 0
type: Question

http://stackoverflow.com/q/49344639
type: Question
tagged with: xpath
tagged with: python-3.x
has body: I am trying to scrap two web pages by using scrapy but i am not getting the expected output. Also trying to extract the data as json file but output file is blank. So far i have tried below mentioned code: from plants.items import PlantsItem class PlantsSpider(scrapy.Spider): name = "plants" allowed_domains = ["greatplantpicks.org"] #Scraping web page start_urls = ["http://www.greatplantpicks.org/plantlists/by_plant_type/conifer"] def parse(self, response): In order to get the output as json i have used below command: scrapy crawl plants -o trees_json.json But i am not getting any output except some log detail which is mentioned below: 2018-03-18 04:47:29 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: plants) 2018-03-18 04:47:29 [scrapy.utils.log] INFO: Versions: lxml 4.2.0.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.5.2 (default, Nov 23 2017, 16:37:01) - [GCC 5.4.0 20160609], pyOpenSSL 17.5.0 (OpenSSL 1.1.0g 2 Nov 2017), cryptography 2.1.4, Platform Linux-4.13.0-37-generic-x86_64-with-Ubuntu-16.04-xenial 2018-03-18 04:47:29 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'plants', 'FEED_FORMAT': 'json', 'FEED_URI': 'trees_json.json', 'SPIDER_MODULES': ['plants.spiders'], 'NEWSPIDER_MODULE': 'plants.spiders', 'ROBOTSTXT_OBEY': True} 2018-03-18 04:47:29 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.feedexport.FeedExporter'] 2018-03-18 04:47:29 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scr…
has comment: http://stackoverflow.com/comment/85694947
tagged with: python
type: AnsweredQuestion
score: 0
has title: Scrapy - Data Extraction (as json)
accepted answer: http://stackoverflow.com/a/49344705
has answer: http://stackoverflow.com/a/49344705
answer count: 1
has comment: http://stackoverflow.com/comment/85689441
tagged with: scrapy

http://stackoverflow.com/q/49356565
answer count: 1
tagged with: django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85713613
tagged with: heroku
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31685688
has comment: http://stackoverflow.com/comment/85713598
has comment: http://stackoverflow.com/comment/85713120
has comment: http://stackoverflow.com/comment/85713582
has answer: http://stackoverflow.com/a/49371304
accepted answer: http://stackoverflow.com/a/49371304
tagged with: python
has comment: http://stackoverflow.com/comment/85729546
has body: I have a Django app that I've deployed to production on Heroku. I have a settings package with different settings for local and production. In my local settings, I have DEBUG set to True and I'm able to both run the server and load the homepage. In my production settings module, everything is identical except for DEBUG being set to False and the addition of hostnames to ALLOWED_HOSTS. For some reason, when I try to access the site (either locally or on heroku) with the production settings, I'm getting a 400 Bad Request. I think there might be something wrong with the format of my hostnames but I'm not sure: ALLOWED_HOSTS = ['https://test_app.herokuapp.com/','http://127.0.0.1:8000/'] What could be causing the 400 error? Should the urls be formatted differently?
has comment: http://stackoverflow.com/comment/85713717
tagged with: django-settings
downvote count: 0
has title: 400 Error when visiting Django domain in production
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85713385

http://stackoverflow.com/comment/85696587
type: QuestionComment
has text: What return `print (df['aid'].head().apply(type))` ?
comment on: http://stackoverflow.com/q/49348396
score: 0
type: Comment

http://stackoverflow.com/comment/85701735
has text: @Alex, so is your question answered then? If so, please mark your problem as solved by adding the checkmark to the answer. This will signify to others as well that your problem was resolved.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49348936
type: Comment

http://stackoverflow.com/q/49417232
type: Question
has comment: http://stackoverflow.com/comment/85836393
duplicate of: http://stackoverflow.com/q/2158395
linked to: http://stackoverflow.com/q/2158395
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49417322
tagged with: list
has comment: http://stackoverflow.com/comment/85836324
accepted answer: http://stackoverflow.com/a/49417322
has title: Python - How to flatten nested list getting unique values
answer count: 1
tagged with: python
has body: this is my function : extract_unique_elements([2,[[2,4,5],"c",["c","d"]]]) which should return: {2, 4, 5, “c”, “d”} (in the form of set). I looked for some answers but they all for 2D lists. Thank you. But now I already have a solution. thank you all for your help. def extract_unique_elements(lst): unique = [] def recursion_occurs_here(element): for item in element: if isinstance(item, list): recursion_occurs_here(item) else: unique.append(item) recursion_occurs_here(lst) extracted = set(unique) return extracted
tagged with: unique

http://stackoverflow.com/q/49323620
type: Question
has comment: http://stackoverflow.com/comment/85648671
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49707775
has title: Reading a csv file in to Python
answer count: 1
downvote count: 3
has body: I am trying to read a csv file using Python. But I get the following error utf-8' codec can't decode byte 0xa3 in position 28: invalid start byte One of the column in my Dataset is a string one. However some of them in this column are treated as number and some other as string Please help me....
has comment: http://stackoverflow.com/comment/85648607
favorite count: 0

http://stackoverflow.com/comment/85770458
has text: @Main yep , yw~ :-) happy coding
comment on: http://stackoverflow.com/a/49384618
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49426343
score: 0
has body: In this block: if number &gt; 1: print_numbers(number-1) print(number) the interpreter enters the print_numbers function under that condition, but will afterwards also print the number. Your expected effect would occur if you put the print in an else branch: if number &gt; 1: print_numbers(number-1) else: print(number)
type: Answer
answers question: http://stackoverflow.com/q/49425956

http://stackoverflow.com/q/49435621
has title: How to define variable name in Jupyter notebook through interactive widget (python)
answer count: 1
tagged with: python
has body: I need the following functionality: #what do you want to name the processed file? (widget here) filename=(widget input string) I did not find any easy examples in the widget documentation or other searches.
tagged with: jupyter-notebook
type: Question
accepted answer: http://stackoverflow.com/a/49436987
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49436987

http://stackoverflow.com/comment/85641547
score: 0
type: Comment
type: AnswerComment
has text: That's not exactly correct. You can use `print` as a function in Python 2.7 (maybe older versions, too, but these should not be used since years). Just import the correct future, which is a good idea anyway.
comment on: http://stackoverflow.com/a/49320282

http://stackoverflow.com/comment/85837282
comment on: http://stackoverflow.com/q/49417747
type: QuestionComment
has text: For most of the operators, they _already_ support this by looking up special methods with double underscores. That's how numpy does exactly your example out of the box. For a set of new functions you create, you can create the same kind of protocol—calling `f` on a function first calls its `__arg__` method. (Although you're probably better off calling it `arg` or `_arg`.)
score: 0
type: Comment

http://stackoverflow.com/q/49420112
has comment: http://stackoverflow.com/comment/85841649
has title: comparing values in two or more keys in python dict
type: Question
has comment: http://stackoverflow.com/comment/85841679
has answer: http://stackoverflow.com/a/49420188
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85841965
upvote count: 1
has comment: http://stackoverflow.com/comment/85841701
has answer: http://stackoverflow.com/a/49420386
has body: I want to compare the values for 2 or more keys in python dict and return the highest value. I can find max for 2 keys but I am clueless for 3 keys and above. Here is my code for 2 keys comparison: d = {} d['right'] = [0.1, 0.3, 0.5] d['left'] = [0.2, 0.1, 0.4] result = [list(d)[0] if x &gt; y else list(d)[1] for x,y in zip(list(d.values())[0], list(d.values())[1])] # result: ['left', 'right', 'right'] now what's the best way to do it for 3 keys? # input: d = {} d['right'] = [0.1, 0.3, 0.5] d['left'] = [0.2, 0.1, 0.4] d['back'] = [0.0, 0.2, 0.8] # expected result: ['left', 'right', 'back'] PS: I try not to use numpy, pandas, or any library possible. Or if I have to use, I try to stick with whatever base library available in python.
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85841918
answer count: 3
has answer: http://stackoverflow.com/a/49420417
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/85648415
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49323339
has text: You can use a combination of buttons and conditions that can be applied per click with bindings. However you will need to attempt this on your own first and when/if you get stuck you can ask your question here with the code you have attempted.
type: Comment

http://stackoverflow.com/q/49429940
has comment: http://stackoverflow.com/comment/110392651
has body: How to use Jinja2 to dynamically generate form inputs and labels from list? For example, say I have lists: A = ["name", "city", "state","phone"] B = ["album", "artist", "genre"] C = ["title","author","category", "subcategory"] And there are buttons labeled A, B and C. I want to dynamically generate a form depending on which button was clicked. So if B was clicked, I want to use items in B to dynamically generate: album artist genre
tagged with: http://stackoverflow.com/tag/html
answer count: 1
accepted answer: http://stackoverflow.com/a/49430796
has title: Use Jinja to dynamically generate form inputs and labels from python list
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85862326
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85861647
tagged with: python
tagged with: jinja2
has answer: http://stackoverflow.com/a/49430796
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/85843598
comment on: http://stackoverflow.com/a/49421301
type: AnswerComment
has text: You can build the `count` in one line as `collections.Counter(itertools.chain(*a))`.
score: 1
type: Comment

http://stackoverflow.com/comment/85724567
score: 0
type: Comment
type: QuestionComment
has text: Did you forget a "{" when copying the data?
comment on: http://stackoverflow.com/q/49362245

http://stackoverflow.com/a/49333816
score: 0
has body: I had the hardest time getting this to work. The trick was the $ #!python2 import re yourlist = ['abc1_def23', 'abc10_def99', 'abc9_def9', 'abc955_def9', 'abc_def9', 'abc9_def9288', 'abc49_def9234'] for item in yourlist: if re.search(r'abc[0-9]+_def[0-9][0-9]$', item): print item, 'is a match'
type: Answer
answers question: http://stackoverflow.com/q/49333036

http://stackoverflow.com/comment/85717800
has text: See https://stackoverflow.com/a/33054922/137386
score: 0
comment on: http://stackoverflow.com/q/49357063
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49416019
type: Answer
answers question: http://stackoverflow.com/q/49415900
score: 0
has comment: http://stackoverflow.com/comment/85833973
has body: Use pandas: import pandas as pd s = pd.Series(['Apple.', "Trump's", "They're", "I'm", "¿Hablas", "$12", "H4ck3r"]) s.str.extract(r'(\w+)') Output: 0 Apple 1 Trump 2 They 3 I 4 Hablas 5 12 6 H4ck3r Name: 0, dtype: object

http://stackoverflow.com/comment/85707065
type: QuestionComment
score: 4
has text: Is it possible that you have another `dbconn.py` somewhere else on your module path? Or that you just forgot to save the latest changes to `dbconn.py` so it doesn't actually have that `testme` method? Or that your actual code has a typo and it defines `testem` instead?
comment on: http://stackoverflow.com/q/49353348
type: Comment

http://stackoverflow.com/q/49400430
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/85802803
has answer: http://stackoverflow.com/a/49400845
score: 0
has body: I have a csv of names, transaction amount and an exact longitude and latitude of the location where the transaction was performed. I want the final document to be anonymized - for that I need to change it into a CSV where the names are hashed (that should be easy enough), and the longitude and latitude are obscured within a radius of 2km. I.e, changing the coordinates so they are within no more than 2 km from the original location, but in a randomized way, so that it is not revertible by a formula. Does anyone know how to work with coordinates that way?
tagged with: geohashing
type: UnansweredQuestion
answer count: 1
tagged with: geolocation
tagged with: coordinates
type: Question
has title: Anonymizing geo location coordinates in python

http://stackoverflow.com/q/49402041
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85805311
score: -3
tagged with: python
has body: The code is below i=0 a=0 Matrix[0]=0 Matrix = [1 for i in range(1000)] while i&lt;1000: i=i+1 Matrix[i]=(1/1000)*((i*(1/1000))^2 a=a+Matrix[i] print (a) When I try to run the program, Python highlight the first a in the 8th row and it says invalid syntax. I can't figure out what is the problem with the code. Much appreciated if you helped
has answer: http://stackoverflow.com/a/49402161
type: Question
accepted answer: http://stackoverflow.com/a/49402161
has comment: http://stackoverflow.com/comment/85805335
has comment: http://stackoverflow.com/comment/85805302
has comment: http://stackoverflow.com/comment/85805352
upvote count: 0
answer count: 1
downvote count: 3
has title: Invalid syntax in a variable in Python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/49431655
downvote count: 0
upvote count: 1
has title: Python Multithreaded Processing Clogging Up Memory
favorite count: 0
score: 1
has body: I am new to multithreaded processing in Python, but have been using the following code to run a multithreaded download, but after running this for several hours it eats up my memory over time and then stalls due to lack of free memory. I'm trying to figure out an alternative method that will allow me to run this process for several hours without having to worry about memory consumption: def worker() while True: item = jq.get() download_stuff(item) jq.task_done() input_list = [1,2,3,4,5,6,7,8,9...] num_threads = 8 q = Queue jq = JoinableQueue() for i in range(num_threads): t = Thread(target=worker) t.daemon = True t.start() for item in input_list: jq.put(item) jq.join()
tagged with: python
tagged with: memory
type: Question
tagged with: download
answer count: 0
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/a/49296872
score: 5
has comment: http://stackoverflow.com/comment/85595828
downvote count: 0
has body: You need to assign it back to m[i] in the loop: for i in range(len(m)): m[i] = [1./item if item != 0. else item for item in m[i]] And the i+=1 is not needed because the for loop does that for you. In order to avoid the sublist being shorter than the original sublist, you need to move the if from the end of the list comprehension (which basically filters which items are processed) to the front (so the value itself is a ternary expression that evaluates to 1/item or item, depending on the value of item). At this point you should probably watch the presentation Loop like a Native and rewrite it for example as: for i, x in enumerate(m): m[i] = [1./item if item != 0. else item for item in x]
answers question: http://stackoverflow.com/q/49296799
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85596211
has comment: http://stackoverflow.com/comment/85595758

http://stackoverflow.com/q/49323339
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85649192
has comment: http://stackoverflow.com/comment/85649092
type: Question
has title: Python 3 tkinter: Switch Button
has answer: http://stackoverflow.com/a/49323729
tagged with: python
has comment: http://stackoverflow.com/comment/85649127
upvote count: 4
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85649352
has comment: http://stackoverflow.com/comment/85648415
has body: I want to create my own widget with the following description: There are three buttons labelled low, medium, high. At any time either none of them is activated or exactly one. The one which is activated should have a sunken relief. If I click on one button the relief of all other buttons should be raised while the activated button should be sunken. How do I implement this on tkinter python3? I was able to do it for one button: This function is defined prior: def toggleLowDeer(): if DeerLowButton.config('relief')[-1] == 'sunken': DeerLowButton.config(relief="raised") else: DeerLowButton.config(relief="sunken") The button is created afterwards DeerLowButton = Button(root, text="L", width=1, relief="raised", command=toggleLowDeer) DeerLowButton.place(x=10, y=280)
score: 2
accepted answer: http://stackoverflow.com/a/49323729
type: AnsweredQuestion
downvote count: 2
tagged with: button

http://stackoverflow.com/comment/85812683
has text: Ok, so if I was accessing specifically '2' in the first list, would I use `newlists[0][3]`? edit: brilliant, that's worked perfectly, thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49405675
type: Comment

http://stackoverflow.com/comment/85879055
score: 0
comment on: http://stackoverflow.com/q/49435971
type: QuestionComment
type: Comment
has text: If you can't copy-paste the error message in CMD, could you take a picture? That'll help with figuring out the problem. But also, are you running CMD in the same folder as your `button.png` file?

http://stackoverflow.com/q/49312838
tagged with: pandas
has title: python merge row of text with same category
has answer: http://stackoverflow.com/a/49313089
has answer: http://stackoverflow.com/a/49312997
type: Question
tagged with: numpy
answer count: 2
type: UnansweredQuestion
tagged with: python
has body: I'm new to python can anyone help me with this. For example, I have a data frame of data = pd.DataFrame({'a': [1,1,2,2,2,3], 'b': [12,22,23,34,44,55], 'c'['a','','','','c',''], 'd':['','b','b','a','a','']}) I want to sum a and ignore the different in b data = ({'a':[1,2,3],'c':['a','c',''],'d':['b','baa','']}) How can I do this?
has comment: http://stackoverflow.com/comment/85627510
score: 0

http://stackoverflow.com/comment/85668368
score: 1
type: Comment
has text: Possible duplicate of ['pip' is not recognized as an internal or external command](https://stackoverflow.com/questions/23708898/pip-is-not-recognized-as-an-internal-or-external-command)
type: QuestionComment
comment on: http://stackoverflow.com/q/49333343

http://stackoverflow.com/comment/85684486
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49342018
score: 0
has text: Edited question to include all mean and covariances.

http://stackoverflow.com/comment/85821616
type: QuestionComment
has text: from django.forms import ModelForm from django import forms from plagiarism.models import File1,File2 class FilesCreate2(ModelForm): class Meta: model=File2 exclude=() widgets={'secondfile':forms.Textarea(attrs={'cols':50,'rows':100})}
score: 0
comment on: http://stackoverflow.com/q/49408730
type: Comment

http://stackoverflow.com/q/49377952
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85756563
has answer: http://stackoverflow.com/a/49377993
has body: currently I am using for s in list: print(*s) but it displays the list output as ['this is'] ['the output'] But I would like the output to be displayed as this is the output There should be a simple solution but i am still yet to come across one.
has comment: http://stackoverflow.com/comment/85758605
tagged with: output
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49378082
tagged with: display
tagged with: list
tagged with: printing
answer count: 3
has comment: http://stackoverflow.com/comment/85756670
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85804889
type: Question
has answer: http://stackoverflow.com/a/49378066
has title: How to "properly" display a list in python without brackets

http://stackoverflow.com/comment/85864052
has text: Exactly what I was looking for. Thanks!!! Never used get with dictionary before always used [ ] to recall values.
type: AnswerComment
comment on: http://stackoverflow.com/a/49413412
score: 0
type: Comment

http://stackoverflow.com/comment/85647769
has text: @CBroe Got it! I completely missed this part. I was just reading through it fast. In any case, most marketers use Facebook to try to sell something, so most interactions are fake anyway.
type: Comment
comment on: http://stackoverflow.com/q/49321748
score: 0
type: QuestionComment

http://stackoverflow.com/a/49336145
type: Answer
has body: So Python prints everything inside the quote marks. So... if you want your string to be "hello [your name]" you need to put that inside the quotation marks to print it. it would look like this. print(""hello [your name]"") and your string would be "hello [your name]"
score: 0
answers question: http://stackoverflow.com/q/49335427

http://stackoverflow.com/comment/85653763
has text: Paandittya's code below shows an example. The key concept is that character formatting (font) is specified at the *run* level. All text in a run shares the same character formatting. So you need to break the binary substrings out into a separate run and set its formatting to your desired look.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49317431
score: 1

http://stackoverflow.com/q/49279597
score: 2
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49283434
tagged with: set
has body: I have a set in which every element is a tuple of 2 tuples, each of the tuples contains itself 3 elements/fields, for example an element of the set would look like: (('q0','l0','s0'),('q1','l1','s1')) I need to look for specific fields of the elements of the set. The way i do this now is: for set_element in my_set: s0 = set_element[0] s1 = set_element[1] if s0 == '('q0','l0','s0')': "add this set_element to another set" Now this works, but with a really high number of elements of the set I don't find this very efficient because every time I have to iterate through all the elements of the set and I can't exploit the efficiency of sets. Is there a more efficient way to to this? Consider that i may also need to access to just one specific field like 'q0' edit: I'll make a more detailed example, let's assume I have this set of elements: x= [(('q0','l0','s0'),('q1','l1','s1')),(('q0','l1','s0'), ('q1','l2','s2')),(('q0','l0','s4'),('q1','l1','s1')), (('q2','l2','s2'),('q3','l3','s3')),(('q4','l4','s4'),('q5','l5','s5'))] and that i want to extract all the elements in which the first tuple has q0 as a element, so in this case the result would be (('q0','l0','s0'),('q1','l1','s1')) (('q0','l1','s0'),('q1','l2','s2')) (('q0','l0','s4'),('q1','l1','s1'))
has title: How to look for elements in a set that satisfy a certain condition on the element itself?
type: Question
tagged with: hash
accepted answer: http://stackoverflow.com/a/49281613
upvote count: 2
has comment: http://stackoverflow.com/comment/85562300
has comment: http://stackoverflow.com/comment/85561928
has answer: http://stackoverflow.com/a/49281613
possible better answer: http://stackoverflow.com/a/49279761
downvote count: 0
has comment: http://stackoverflow.com/comment/85563174
tagged with: python
has answer: http://stackoverflow.com/a/49279761
has comment: http://stackoverflow.com/comment/85564511
favorite count: 0

http://stackoverflow.com/q/49319575
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49660589
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/85719248
accepted answer: http://stackoverflow.com/a/49660589
type: AnsweredQuestion
tagged with: aws-xray
upvote count: 3
has comment: http://stackoverflow.com/comment/85669872
has body: I have just started working with AWS Xray and I am using it with AWS Lambda. The thing is I notice duplication of AWS Xray Nodes on service map. For example SNS is categorised as AWS::SNS and Remote call. Where as they are just both the same thing, have exact same traces and avg response time. Just displayed as two different nodes. Does anyone have any idea how to reduce this noise? I am using patch_all() function to patch all services. Here are the images : Image 1 Image 2 Here are the images and gist for traces. Image SNS,Image Remote,Image Remote (details),Image SNS(Details),Gist Update: I have added the images as asked by @Rohit The problem was solved using Using following replacement from aws_xray_sdk.core import patch_all patch_all() //replaced by from aws_xray_sdk.core import patch patch('boto3') //etc etc
downvote count: 0
answer count: 1
has title: AWS X-Ray shows duplicate nodes in the Service Map
tagged with: aws-sdk
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85692424
tagged with: aws-lambda

http://stackoverflow.com/a/49384129
answers question: http://stackoverflow.com/q/49383977
has body: The builtint sys.exit() raises a SystemExit-Exception. As you are catching any type of exception when you don't define the Exception to catch (except: without an Exception Type) the SystemExit gets also caught. Ultimately the function will run until the last line where you wrote pass. Best thing to do is to always catch specific Exceptions and never ever catch all Exceptions with an except:. Furthermore you should put the check if self.sorting is not in self.output_table.column_headers outside the try catch where you check for a valid self.sorting.
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85769244
upvote count: 3
has comment: http://stackoverflow.com/comment/85769399
downvote count: 0

http://stackoverflow.com/a/49371247
answers question: http://stackoverflow.com/q/49371170
has body: got it: First if (0 &lt;= norm_gp_x &lt;= 1 and 0 &lt;= norm_gp_y &lt;= 1): then: file.write('[' + norm_gp_x + ', ' + norm_gp_y + ']') So you're adding strings and integers. This triggers an exception, and since you used an universal except: pass construct, the code skips every iteration (note that this except statement also catches the KeyboardInterrupt exception you're trying to catch at a higher level, so that doesn't work either) Never use that construct. If you want to protect about a specific exception (ex: IOError), use: try IOError as e: print("Warning: got exception {}".format(e)) so your exception is 1) focused and 2) verbose. Always wait until you get exceptions that you want to ignore to ignore them, selectively (read Catch multiple exceptions in one line (except block)) So the fix for your write it: file.write('[{},{}]'.format(norm_gp_x, norm_gp_y)) or using the list representation since you're trying to mimic it: file.write(str([norm_gp_x, norm_gp_y])) Aside: your other issue is that you should use append mode with open('/the/path/to/the/file.txt', 'a') as file: or move you open statement before the loop, else you'll only get the last line in the file (a classic) since w mode truncates the file when opening. And you can drop flush since exiting the context closes the file.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85743497
downvote count: 0
type: Answer
score: 6
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49371170
has comment: http://stackoverflow.com/comment/85744312
has comment: http://stackoverflow.com/comment/85743679
has comment: http://stackoverflow.com/comment/85744357

http://stackoverflow.com/q/49364654
score: 3
has body: I have dataframe users with different columns. My goal is to add the column [uses_name] which should be True when a password is the same as each users first or last name. For example, [user_name] in twelve row contain milford.hubbard. Then in [uses_name] will be True, because the [password] and [last_name] are the same. To do this, I create two columns [first_name] and [last_name] with regular expressions. When create [uses_name] I have trouble with | operator. I am read more in pandas doc about Boolean indexing but not find an answer. My code: import pandas as pd users = pd.read_csv('datasets/users.csv') # Extracting first and last names into their own columns users['first_name'] = users['user_name'].str.extract(r'(^\w+)', expand=False) users['last_name'] = users['user_name'].str.extract(r'(\w+$)', expand=False) # Flagging the users with passwords that matches their names users['uses_name'] = users['password'].isin(users['first_name'] | users['last_name']) # Counting and printing the number of users using names as passwords print(users['uses_name'].count()) # Taking a look at the 12 first rows print(users.head(12)) When I try to compile this, I give an error: TypeError: unsupported operand type(s) for |: 'str' and 'bool' First 12 rows in users dataframe with created first_name and last_name columns: id user_name password first_name last_name 0 1 vance.jennings joobheco vance jennings 1 2 consuelo.eaton 0869347314 consuelo eaton 2 3 mitchel.perkins fabypotter mitchel perkins 3 4 odessa.vaughan aharney88 odessa vaughan 2 3 mitchel.perkins fabypotter mitchel perkins 3 4 odessa.vaughan aharney88 odessa vaughan 4 5 araceli.wilder acecdn3000 araceli wilder 5 6 shawn.harrington 5278049 shawn harrington 6 7 evelyn.gay master evelyn gay 7 8 noreen.hale murphy noreen hale 8 9 gladys.ward lwsves2 gladys ward 9 10 brant.zimmerman 1190KAREN5572497 brant zimmerman 10 11 leanna.abbott aivlys24 leanna abbott 11 12 milford.hubbard hubbard milford hubbard
tagged with: dataframe
has title: TypeError: unsupported operand type(s) for |: 'str' and 'bool'
has answer: http://stackoverflow.com/a/49364719
downvote count: 1
favorite count: 0
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/49364762
tagged with: boolean
has answer: http://stackoverflow.com/a/49364762
accepted answer: http://stackoverflow.com/a/51613339
has answer: http://stackoverflow.com/a/49364682
tagged with: python
has answer: http://stackoverflow.com/a/51613339
answer count: 4
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/85787845
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49392274
type: Comment
has text: Thank you for your input, I figured out I need a loop but cant seem to structure it right to output correctly. After trying to run your example code I get the following errors. Traceback (most recent call last): File "C:/Users/Gwfox/Documents/pythontest/test1234567890.py", line 17, in <module> main() File "C:/Users/Gwfox/Documents/pythontest/test1234567890.py", line 9, in main for number in range(N): # the variable number will get every value from 0 to N-1 in each iteration TypeError: 'str' object cannot be interpreted as an integer

http://stackoverflow.com/a/49388234
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49388141
has comment: http://stackoverflow.com/comment/85777989
accepted answer of: http://stackoverflow.com/q/49388141
type: Answer
score: 0
has body: data["response"]["data_block"][0]["Number"] Try above line
has comment: http://stackoverflow.com/comment/85777958

servo
tags question: http://stackoverflow.com/q/49420719
tags question: http://stackoverflow.com/q/49353430
type: Tag
tag name: servo

http://stackoverflow.com/comment/85808168
has text: Full code or at least a snippet would be ideal to give you more precice answers. Also: Have you tried running the code to see what it does?
comment on: http://stackoverflow.com/q/49403536
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/85563174
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49279597
type: Comment
has text: Can you provide some data (doesn't have to be large, just more than one element) so that we can benchmark? Believe it or not, creating test data is the type of manual work which reduces responder-interest!

http://stackoverflow.com/comment/85637367
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49315436
score: 0
has text: @MartinEvans it worked! Thank you! Please post this as an answer What could be the reason?

http://stackoverflow.com/a/78889503
downvote count: 1
has body: Beware of beepy ... It turned out to be the cause of exit code 139 in my case.
answers question: http://stackoverflow.com/q/49414841
type: Answer
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/139127615

http://stackoverflow.com/a/49384299
score: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49355434
has body: To navigate to a webpage you just write driver.get(__url__) you can do this in your program multiple times
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49355434

http://stackoverflow.com/a/49308840
upvote count: 1
answers question: http://stackoverflow.com/q/49307165
has body: Your access database is mathsquiz.accdb (not mdb). replace the provider: Provider=Microsoft.Jet.OLEDB.4.0 With Microsoft ACE OLEDB 12.0 provider: Provider=Microsoft.ACE.OLEDB.12 install driver Microsoft ACE OLEDB 12.0
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/85739496
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49366352
has text: Make sure you close the file so all data is flushed to the file. Better, use a `with` statement to automatically close the file.

http://stackoverflow.com/comment/85820980
type: AnswerComment
comment on: http://stackoverflow.com/a/49409194
has text: Small corner case: without taking into account whitespace or word boundaries, there will be false positives from using `in`: e.g. the key ‘france’ will match ‘hello my name is francesca’
type: Comment
score: 2

http://stackoverflow.com/a/76769389
downvote count: 0
score: 1
upvote count: 1
has body: For the following configuration: Django==3.0.11 redis==2.10.6 celery==4.0.0 kombu==4.0.0 I updated the following configuration on the settings.py file and it worked. CELERY_SETTINGS = { 'CELERY_TIMEZONE': TIME_ZONE, 'CELERY_ENABLE_UTC': True, 'CELERY_RESULT_BACKEND': REDIS_URL, 'CELERY_SEND_TASK_SENT_EVENT': True, 'CELERY_TASK_SERIALIZER': 'pickle', 'CELERY_RESULT_SERIALIZER': 'pickle', 'CELERY_ACCEPT_CONTENT': ['pickle', 'json'], } Don't forget to update the actual value of TIME_ZONE and REDIS_URL The reason could be the Celery 4 version uses JSON as the serializer by default, while the celery3 version uses Pickle by default. The old Django may not be expecting the JSON format from the tasks. So, If you are using the very old Django version, this could help you.
type: Answer
answers question: http://stackoverflow.com/q/49373825

http://stackoverflow.com/q/49424010
has body: My code: import cv2 cap = cv2.VideoCapture(0) cv2.namedWindow('frame', cv2.WINDOW_NORMAL) while True: key = cv2.waitKey(0) &amp; 0xFF ret, frame = cap.read() cv2.imshow('frame', frame) if key == ord('q'): cap.release() cv2.destroyAllWindows() break if key == ord('c'): cv2.imwrite('capture.jpg', frame) cap.release() cv2.destroyAllWindows() I run this code. It shows the gray display. I point the camera at an object and press the 'c' key. It shows not the object image but the image of what the camera pointed at when I run the code, and saves it. I point the camera at somewhere else and press 'c' key agein. It shows the image of the object which it saw at 3. and save it. The camera lags 1 step. Why?
answer count: 1
has title: Why cv2.imwrite lags 1 step?
favorite count: 0
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/49424146
tagged with: python
accepted answer: http://stackoverflow.com/a/49424146
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/85856014
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85856114

http://stackoverflow.com/q/49408242
type: AnsweredQuestion
answer count: 2
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85820326
downvote count: 0
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/85821622
type: Question
has comment: http://stackoverflow.com/comment/85818329
possible better answer: http://stackoverflow.com/a/49408601
accepted answer: http://stackoverflow.com/a/49408575
has comment: http://stackoverflow.com/comment/85820365
has body: I want to minimize the following LPP: c=60x+40y+50z subject to 20x+10y+10z>=350 , 10x+10y+20z>=400, x,y,z>=0 my code snippet is the following(I'm using scipy package for the first time) from scipy.optimize import linprog c = [60, 40, 50] A = [[20,10], [10,10],[10,20]] b = [350,400] res = linprog(c, A, b) print(res) The output is : screenshot of the output in Pycharm 1.Can someone explain the parameters of the linprog function in detail, especially how the bound will be calculated? 2.Have I written the parameters right? I am naive with LPP basics, I think I am understanding the parameters wrong.
has answer: http://stackoverflow.com/a/49408601
has comment: http://stackoverflow.com/comment/85818450
tagged with: python
has answer: http://stackoverflow.com/a/49408575
tagged with: linear-programming
has title: scipy.optimize.linprog - difficulty understanding the parameters
tagged with: numpy

http://stackoverflow.com/q/49307379
has answer: http://stackoverflow.com/a/49308788
has comment: http://stackoverflow.com/comment/85616899
has body: I've already install pandas from either the terminal and add pandas in pycharm project interpreter. However, every time I run a program which uses pandas it keeps reminding me there's an error. RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa Traceback (most recent call last): File "/Users/Rabbit/PycharmProjects/NLP/review2vector.py", line 7, in &lt;module&gt; from pandas import DataFrame File "/Users/Rabbit/Library/Python/2.7/lib/python/site-packages/pandas/__init__.py", line 35, in &lt;module&gt; "the C extensions first.".format(module)) ImportError: C extension: numpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. I also followed this question's answer How to solve import error for pandas? But it does not work for me.
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/85616881
linked to: http://stackoverflow.com/q/30761152
tagged with: pandas
has title: How to solve pandas import error in pycharm?
has answer: http://stackoverflow.com/a/49308173
type: Question
answer count: 2
tagged with: pycharm
has comment: http://stackoverflow.com/comment/85620294
type: UnansweredQuestion

http://stackoverflow.com/q/49395252
upvote count: 1
tagged with: flask
has title: Send response to EventSource after webook (Flask + uWSGI + nginx)
score: 1
tagged with: python
tagged with: eventsource
tagged with: uwsgi
favorite count: 0
type: Question
answer count: 0
has body: I have Flask application with route (webhook) receiving POST requests (webhooks) from external phone application (incomming call = POST request). This route sets threading.Event.set() and based on this event, another route (eventsource) sends an event stream to opened EventSource connection on a webpage created by yet another route (eventstream). telfa_called = Event() telfa_called.clear() call = "" @telfa.route('/webhook', methods=['GET', 'POST']) def webhook(): global call print('THE CALL IS HERE') x = request.data y = ET.fromstring(x.decode()) caller_number = y.find('caller_number').text telfa_called.set() # setting threading.Event for another route return Response(status=200) @telfa.route('/eventstream', methods = ['GET','POST']) @login_required def eventstream(): jsid = str(uuid.uuid4()) return render_template('telfa/stream.html', jsid=jsid) def eventsource_gen(): while 1: if telfa_called.wait(10): telfa_called.clear() print('JE TO TADY') yield "data: {}\n\n".format(json.dumps(call)) @telfa.route('/eventsource', methods=['GET', 'POST']) def eventsource(): return Response(eventsource_gen(), mimetype='text/event-stream')` Everything works great when testing in pure Python application. The problem starts, when I move this to production server, where I use uWSGI with nginx. (Other parts of this Python application work without any troubles.) When the eventSource connection is opened and incomming webhook should be processed, whole flask server stucks (for all other users, too), page stops to load and I cannot find, where the error is. I only know, the POST request from external application is received, but the response to EventSource is not made. I suspect it has something to do with processes - the EventSource connection from JavaScript is one process, the webhook route another - and they do not communicate. So or so, I suppose this has to have very trivial solution, but I didn't find it in past 3 days and nights. Any hints, please? Thanks in advance. To be complet…
type: UnansweredQuestion
tagged with: webhooks
downvote count: 0

http://stackoverflow.com/a/49310199
has comment: http://stackoverflow.com/comment/85731649
has comment: http://stackoverflow.com/comment/85731591
score: 3
answers question: http://stackoverflow.com/q/49310086
has comment: http://stackoverflow.com/comment/85657895
has body: You can use pd.Series.value_counts for this: df['count'] = df['id'].map(df['id'].value_counts()) Result: index id name dob visit count 0 0 111 Joe 1/1/2000 1/1/2018 3 1 1 111 Joe 1/1/2000 1/5/2018 3 2 2 122 Bob 1/1/1999 2/8/2018 1 3 3 133 Jill 1/2/1988 7/9/2017 1 4 4 111 Joe 1/1/2000 12/31/2018 3
has comment: http://stackoverflow.com/comment/85650263
has comment: http://stackoverflow.com/comment/85662550
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49310086

http://stackoverflow.com/comment/85633874
type: Comment
type: AnswerComment
score: 1
has text: jezrael to the rescue! It sure looks like that worked. I needed to adjust `sort_values(['sim', 'time'])`... but that was trivial. Thanks!
comment on: http://stackoverflow.com/a/49316168

http://stackoverflow.com/comment/85832732
type: Comment
has text: Use a *container* like a list or a dict, don't use a bunch of variables with dynamic execution using `exec`. That's a really bad design
type: QuestionComment
comment on: http://stackoverflow.com/q/49415432
score: 2

http://stackoverflow.com/comment/85909068
score: 0
comment on: http://stackoverflow.com/q/49353661
type: Comment
has text: @CyrielN: Oops, you're right: it is not sufficient to examine the intersection on the line between the centers, one must also ensure the gears do not interfere elsewhere. I wonder if you can model the complementary gear as a geometric subtraction from a disk? (I.e, disk is rotated clockwise by the same angle as gear is rotated clockwise, and for all angles, the gear shape is subtracted from the disk.) That should take care of the interference issues. Or is this just another way of stating what you implemented in the question already? (Such gears may not transfer torque, just rotate together.)
type: QuestionComment

http://stackoverflow.com/comment/85698564
type: Comment
has text: You should post the actual traceback. "Mysql" != "mysql" so the error, as you stated it, doesn't match your code
score: 0
comment on: http://stackoverflow.com/q/49349329
type: QuestionComment

http://stackoverflow.com/comment/85741070
score: 1
comment on: http://stackoverflow.com/q/49369192
type: Comment
type: QuestionComment
has text: Thanks a lot! Solution here : https://stackoverflow.com/questions/26294333/parse-french-date-in-python import dateparser a = "Février 2017" print(dateparser.parse(a).date())

bigdata
tags question: http://stackoverflow.com/q/49438954
tags question: http://stackoverflow.com/q/49434728
tags question: http://stackoverflow.com/q/49290553
tags question: http://stackoverflow.com/q/49289785
tags question: http://stackoverflow.com/q/49421619
type: Tag
tags question: http://stackoverflow.com/q/49305978
tag name: bigdata

http://stackoverflow.com/q/49354961
has body: I have a remote file and its url. Id like to read a line from it, using the pointer to the first character of the line, without downloading it. Had the file been local, I'd use file.seek(pointer) to set the file pointer and use file.readline(). How do I do it when the file is remote?
tagged with: file-pointer
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85710260
type: Question
tagged with: file-handling
type: UnansweredQuestion
tagged with: python
has title: How to read a line large remote file given file pointer in Python 3?
has comment: http://stackoverflow.com/comment/85710258

http://stackoverflow.com/q/49321247
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85643525
has comment: http://stackoverflow.com/comment/85643490
has answer: http://stackoverflow.com/a/49321481
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has title: Dynamically defining variables from a dictionary
tagged with: python
tagged with: variables
score: -1
has comment: http://stackoverflow.com/comment/85643812
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/85643599
answer count: 1
tagged with: string
downvote count: 1
has body: I am trying to dynamically define variables from a dictionary in python. I need my variables to be strings, they should appear something like this: lightgreen = "#2ecc71". To do this I added HEX_VALUE = "'" + HEX_VALUE + "'" however adding this I encountered an error &gt; Traceback (most recent call last): line 22, in &lt;module&gt; exec("%s=%s" % (COLOUR_NAME, HEX_VALUE)) File "&lt;string&gt;", line 1 darkblue:='#2980b9' ^ SyntaxError: invalid syntax As seen from above, this adds ':' to the first part of the variable, so my question is: how can I prevent this? COLOURS = { "lightgreen":"'#2ecc71'", "darkgreen":"#27ae60", "lightblue":"#3498db", "darkblue:":"#2980b9", "lightpurple":"#e74c3c", "darkpurple":"#8e44ad", "lightred":"#e74c3c", "darkred":"#c0392b", "lightorange":"#e67e22", "darkorange":"#d35400", "lightyellow":"#f1c40f", "darkyellow":"#f39c12", "lightteal": "#1abc9c", "darkteal": "#16a085", "lightnavy": "#34495e", "darknavy": "#2c3e50" } for COLOUR_NAME, HEX_VALUE in COLOURS.items(): HEX_VALUE = "'" + HEX_VALUE + "'" exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))

http://stackoverflow.com/a/49419966
answers question: http://stackoverflow.com/q/49419672
type: Answer
has body: This is hard to answer without you sharing how you try to run the file. The error is telling you it did not find the required arguments passed in when you ran the file. Since you specified required = True for the -i, -p, and -m arguments you must always pass them in or make them optional if they are not needed to run your program.
accepted answer of: http://stackoverflow.com/q/49419672
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49435905
type: UnansweredQuestion
tagged with: python
has title: how can i get the value on ON_RECOGNIZING_SPEECH_FINISHED: {'text': 'what you doing Google'} Google Assistant SDK Ubilinux UP2 Board
score: 0
has body: how can i get the value on ON_RECOGNIZING_SPEECH_FINISHED: {'text': 'what you doing Google'} in google assistant ON_CONVERSATION_TURN_STARTED ON_END_OF_UTTERANCE ON_RECOGNIZING_SPEECH_FINISHED: {'text': 'what you doing Google'} ON_RESPONDING_STARTED: {'is_error_response': False} ON_RESPONDING_FINISHED ON_CONVERSATION_TURN_FINISHED: {'with_follow_on_turn': False}
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/49438958
answer count: 1
tagged with: google-assistant-sdk
type: Question
tagged with: linux
tagged with: embedded-linux
has comment: http://stackoverflow.com/comment/85874188

http://stackoverflow.com/q/49312300
has comment: http://stackoverflow.com/comment/85775791
upvote count: 2
downvote count: 2
duplicate of: http://stackoverflow.com/q/18877484
answer count: 1
has body: I need to read this CSV to an array of floats. I'm new to python and unsure how to convert because when I read in the CSV it says that I am using type "Dictreader" hence why I am trying to convert. Thanks! [Screenshot of where I'm at][1] import csv with open('NP.csv') as csvfile: NP = csv.DictReader(csvfile) with open('A.csv') as csvfule: A = csv.DictReader(csvfile) [r, c] = size(NP); [r2, c2] = size(A); for i in range(0, r): for j in range(0, c): NP(i,j) = float(NP(i,j)); for i in range(0, r2): for j in range(0, c2): A(i,j) = float(A(i,j));
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49387894
has comment: http://stackoverflow.com/comment/85626423
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85626561
tagged with: python
linked to: http://stackoverflow.com/q/18877484
has comment: http://stackoverflow.com/comment/85627033
score: 0
has title: Read CSV to float array

http://stackoverflow.com/a/49359918
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49359646
has body: The activate script does this around line 43: VIRTUAL_ENV="/full/path/to/venv1" export VIRTUAL_ENV _OLD_VIRTUAL_PATH="$PATH" PATH="$VIRTUAL_ENV/bin:$PATH" export PATH # unset PYTHONHOME if set if ! [ -z "${PYTHONHOME+_}" ] ; then _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" unset PYTHONHOME fi if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then _OLD_VIRTUAL_PS1="$PS1" if [ "x" != x ] ; then PS1="$PS1" else PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1" fi export PS1 fi so it will still look (and show it in your prompt) for the original venv1 directory. Unless your machine2 has the same directory tree things will not work.
type: Answer
answers question: http://stackoverflow.com/q/49359646
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85741266
has text: What you see here is Python's default representation of a byte array. If you don't like it, write your own. (Which is not meant to be harsh. You may already be doing that even for a simple object such as a text string. After all, `'this is a string\n'` doesn't look "nice" either – at the very least you'd want to lose the quotes!)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49369650
score: 0

http://stackoverflow.com/comment/85736581
comment on: http://stackoverflow.com/q/49367406
has text: @gelazari You are being suggested to provide the data as a [hex dump](https://en.wikipedia.org/wiki/Hex_dump). I would recommend posting only the first few hundred bytes if you're willing to go this way.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85800249
has text: There's no way to convert _any_ date string format without some additional information, because that's ambiguous. Does `02-03-18` mean European 2 March or American 3 Feb? Is `18-03-17` European 18 March 2017 or Japanese 17 March 2018?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49399555

http://stackoverflow.com/a/49400923
has body: Suppose you have this input: s = '0x53 0x48 0x41 0x53 0x48 0x49' You can store values in list like follow: l = list(map(lambda x: int(x, 16), s.split())) To convert it to ASCII use chr(): res = ''.join(map(chr, l))
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49400780
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85849042
type: Comment
has text: how do I do that?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49403452

http://stackoverflow.com/comment/85630163
type: AnswerComment
comment on: http://stackoverflow.com/a/49313639
score: 0
has text: @bharathI our office wifi has blocked that port so I connected with a seperate wifi connection and it worked. Thanks for the input
type: Comment

http://stackoverflow.com/q/49407908
has title: Continous receiving & sending on a socket
accepted answer: http://stackoverflow.com/a/49411105
answer count: 1
has answer: http://stackoverflow.com/a/49411105
type: Question
has comment: http://stackoverflow.com/comment/85818557
tagged with: sockets
tagged with: python
has body: I'm working on assignment where I need to connect to a server (no details of server are disclosed), capture the reply, modify it and send it back for verification. I have created following code which does what I need, but the issue is that after 1st correct reply, server sends another. Code: # -*- encoding: utf-8 -*- import socket from decryptmsg import decryptmsg from cleanmsg import cleanmsg #connection ip="&lt;IP&gt;" port=4000 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) def recvall(sock): BUFFER = 8192 data = b'' while True: part = sock.recv(BUFFER) data += part if len(part) &lt; BUFFER: break return data while True: print "[+] start communication" data = recvall(sock) print data data = cleanmsg(data) if data != None: valmis = decryptmsg(str(data)) if valmis == None: print "[-] no results" break else: print "[+] sending message... " sock.send(valmis) continue When I hit the second question, I get the input captured fine with this code and processed as expected, but when I try to send the 2nd reply back I get error: Traceback (most recent call last): File "challenge.py", line 28, in &lt;module&gt; sock.send(valmis) socket.error: [Errno 32] Broken pipe If I do not close or shutdown the socket, no reply is ever sent to server. How can I tell my client to send the message and wait for reply without socket.shutdown? Or if I need to open new socket for each loop, how should the loop be constructed? The reply from server changes each time so if I open new connection completely and request for data, I get new reply and the process starts from beginning again. UPDATE: the issue seems to be when trying to receive the second reply from server, only the first line of message is received by client.
has comment: http://stackoverflow.com/comment/85820245
has comment: http://stackoverflow.com/comment/85819794
has comment: http://stackoverflow.com/comment/85823763
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49393116
type: AcceptedAnswer
upvote count: 41
score: 41
type: Answer
answers question: http://stackoverflow.com/q/49392845
has body: From docs (Section Forward references) When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later. A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. so in order to solve that just wrap the type with quotes, like this: from typing import Dict class WeekDay: def __init__(self, day_number, day_name): self.day_name = day_name self.day_number = day_number @staticmethod def get_week_days() -&gt; Dict[str, 'WeekDay']: # quote WeekDay weekdays = { "monday": WeekDay(1, "Monday"), "tuesday": WeekDay(2, "Tuesday"), "wednesday": WeekDay(3, "Wednesday"), "thursday": WeekDay(4, "Thursday"), "friday": WeekDay(5, "Friday"), "saturday": WeekDay(6, "Saturday"), "sunday": WeekDay(7, "Sunday") } return weekdays
accepted answer of: http://stackoverflow.com/q/49392845
downvote count: 0

http://stackoverflow.com/comment/85700215
has text: Just to add that spacy has a [Matcher](https://spacy.io/api/matcher) object that can help with RegEx matching. One of the [examples](https://spacy.io/usage/linguistic-features#on_match) talks about adding NER annotations using a `Matcher`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49307026
type: Comment

http://stackoverflow.com/a/49394304
has comment: http://stackoverflow.com/comment/85799022
has comment: http://stackoverflow.com/comment/85790653
has comment: http://stackoverflow.com/comment/85821509
score: 1
has body: Your view is incorrect. objs queryset should be defined in context for render function. For example: def user_panel(request): if request.user.is_authenticated: context = {'objs': Document.objects.all()} return render(request, 'main/user_panel.html', context) else: return render(request, 'main/login.html') Here is more on render function: https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render
has comment: http://stackoverflow.com/comment/85821640
type: Answer
has comment: http://stackoverflow.com/comment/85820785
has comment: http://stackoverflow.com/comment/85804586
answers question: http://stackoverflow.com/q/49393777
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49378754
accepted answer: http://stackoverflow.com/a/49457593
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49457593
answer count: 1
has title: InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
tagged with: tensorflow
type: Question
has body: I had an error: "InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float." And I can't tell why it happened. I want to make a CNN model for sentence classifications. Now I set a random data as data for training. Due to there is text data, it can't become square matrix like MNIST data after "reshape" the data. Instead, it is a 10*100 matrix. Maybe it is a problem of my code. import tensorflow as tf import numpy as np from numpy.random import RandomState # sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None,1000], name='x_input') y_ = tf.placeholder(tf.float32, shape=[None,2], name='y_input') # x = tf.image.convert_image_dtype(x,tf.float32) # Define funstions. def weight_variable(shape): initial = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1,shape=shape) return tf.Variable(initial) def conv2d(x,W,m,n): return tf.nn.conv2d(x,W,strides=[1,m,n,1],padding = 'SAME') def max_pool_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') x_1 = tf.reshape(x, [-1,10,100,1]) # Convolution Layer #1 W_conv1 = weight_variable([2,20,1,25]) b_conv1 = bias_variable([25]) h_conv1 = tf.nn.relu(conv2d(x_1,W_conv1,1,1)+b_conv1) # Pooling Layer #1 h_pool1 = tf.nn.max_pool(h_conv1,ksize=[1,2,20,1],strides=[1,1,1,1],padding='VALID') # Convolution Layer #2 W_conv2 = weight_variable([3,9,25,100]) b_conv2 = bias_variable([100]) h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2,3,9)+b_conv2) # Pooling Layer #2 h_pool2 = tf.nn.max_pool(h_conv2,ksize=[1,3,3,1],strides=[1,3,3,1],padding='VALID') # Dense Layer pool_shape = h_pool2.get_shape().as_list() nodes = pool_shape[1]*pool_shape[2]*pool_shape[3] W_fc1 = weight_variable([nodes,200]) b_fc1 = bias_variable([200]) h_pool2_flat = tf.reshape(h_pool2,[-1,nodes]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1) # Dropout regulation keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropo…
tagged with: python

http://stackoverflow.com/q/49399940
tagged with: textbox
favorite count: 0
type: Question
has body: The following code creates a Kivy app with a single screen, MainScreen, displaying a Label and TextInput object. If you give some keyboard input when the app first loads, it prints in the console with information about which key was pressed. However, if you then click in the TextInput object the keyboard refocuses so you can type in the TextInput object. However, once you click back out of the TextInput object, e.g. on the label or background, and press more keys, the same console printing operation doesn't execute; it seems that the keyboard doesn't 'defocus' from the TextInput object. How do I recapture keyboard focus after clicking out of a TextInput object? from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.uix.screenmanager import Screen, ScreenManager from kivy.uix.textinput import TextInput kv = '''ScreenManagement: MainScreen: &lt;MainScreen&gt;: name: "main" BoxLayout: Label: text: "Label" font_size: 20 size_hint: 0.2,0.1 TextInput input_filter: 'float' font_size: 20 hint_text: "Input Text" size_hint: 0.2,0.1''' class MainScreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): print('INFO: The key', keycode, 'has been pressed') return True # return True to accept the key. Otherwise, it will be used by the system. class ScreenManagement(ScreenManager): pass class MainApp(App): def build(self): return Builder.load_string(kv) if __name__ == "__main__": MainApp().run()
has comment: http://stackoverflow.com/comment/85805577
has title: Recapture keyboard focus in Kivy after clicking out of a `TextInput` object
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49401066
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: focus
tagged with: keyboard-events
answer count: 1
tagged with: kivy
has answer: http://stackoverflow.com/a/49401066

http://stackoverflow.com/a/49359117
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49359052
score: 2
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49359052
has body: Firstly, don't use 30 variables, use a list aod[] Secondly, use for i in range(7039, 7069): aod[i] = yourFunction(aod[i]) to override existing list

http://stackoverflow.com/q/49403845
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/49415803
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85808895
answer count: 2
has comment: http://stackoverflow.com/comment/85808748
accepted answer: http://stackoverflow.com/a/49403911
possible better answer: http://stackoverflow.com/a/49415803
has answer: http://stackoverflow.com/a/49403911
has title: Convert a list of numpy vectors to 2D numpy array
has comment: http://stackoverflow.com/comment/85808744
type: Question
tagged with: numpy
has body: I have a list of numpy arrays. My list contains 5000 numpy arrays and each one has the size (1x1000). I want to construct a numpy array of size 5000x1000. I am trying to do something like: db_array = np.asarray(db_list) # my db_list has 5000 samples of 1x1000 size The result was a matrix of size (5000, 1, 1000). How can I construct a matrix with size (5000, 1000)?
has comment: http://stackoverflow.com/comment/85809226

http://stackoverflow.com/q/49290357
tagged with: jetbrains-ide
favorite count: 0
type: Question
has body: I am working with PyCharm and am trying to create a module from code I've created so that I can import it into new files. In IntelliJ you can start the module creator but in PyCharm this option does not seem to exist. Without a module when I type: import my_code I receive a warning saying "No module named my_code". I've tried creating packages to replace the module but this does not work. How do you repackage code in PyCharm so you can import it into a new file? The project structure is quite simple. I have a number of files I've created as part of a tutorial. I want to make one of the files, "Importing_Files" a module so that I can import it into another file, i.e., "Import_Tester". I've added a picture below to show the tree.
has comment: http://stackoverflow.com/comment/85736760
score: 1
tagged with: python
has title: Creating Modules with PyCharm
tagged with: pycharm
has comment: http://stackoverflow.com/comment/85832757
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87458159
has answer: http://stackoverflow.com/a/56550775
upvote count: 1

http://stackoverflow.com/comment/85631211
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49314696
has text: sorry for inconvenience.I am using python-2.7
type: Comment

http://stackoverflow.com/q/49421699
linked to: http://stackoverflow.com/q/5823465
tagged with: python
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/116162671
has title: Python Subprocess.pOpen runs slow when memory is occ
has answer: http://stackoverflow.com/a/76474624
has comment: http://stackoverflow.com/comment/112699639
has comment: http://stackoverflow.com/comment/91364441
has comment: http://stackoverflow.com/comment/85866549
tagged with: subprocess
has comment: http://stackoverflow.com/comment/91732187
has body: I wrote a python script that uses subprocess.Popen to call command line tool look to do the binary search on a file. For example p = subprocess.Popen('look -b "abc" testfile.txt',executable='/bin/bash', stdout=subprocess.PIPE, stderr=STDOUT, shell=True) out, err = p.communicate() result = out.decode() print(result) What this snippet of code does is that it calls the system command look to perform a binary search the file called testfile.txt for the string abc. It works fine if you just have this snippet of code. However, when your memory is loaded with some large files, it becomes significantly slow. For example, if you do: a = read_a_large_file() #Like GBs of data p = subprocess.Popen('look -b "abc" testfile.txt',executable='/bin/bash', stdout=subprocess.PIPE, stderr=STDOUT, shell=True) out, err = p.communicate() result = out.decode() print(result) a[0] The subprocess part takes a very long time to execute. Running the look command is very fast in shell as it performs binary search on sorted files. Any help will be appreciated! Thanks!
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/116633862
has comment: http://stackoverflow.com/comment/112666910
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85874391
has comment: http://stackoverflow.com/comment/116162160
has comment: http://stackoverflow.com/comment/85860119
type: UnansweredQuestion

http://stackoverflow.com/a/49403260
has comment: http://stackoverflow.com/comment/85807600
type: Answer
has body: If you want renters, you should query User, not Agreement. renters = User.objects.exclude(renter01=None) (Note, having renter01 as the reverse relation makes no sense; unless you have a good reason, you should keep it as the default, which is agreement_set.)
score: 2
has comment: http://stackoverflow.com/comment/85811148
downvote count: 0
has comment: http://stackoverflow.com/comment/85807742
answers question: http://stackoverflow.com/q/49403209
upvote count: 2

http://stackoverflow.com/a/49320282
downvote count: 1
answers question: http://stackoverflow.com/q/49320238
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85644613
has body: In Python 3 you can do: print(*words_list) because print is just a function and the * operator in this context will unpack elements of your list and put them as positional arguments of the function call. In older versions you'd need to concatenate (join) elements of the array first, possibly converting them to strings, if they are not strings already. This can be done like this: print ' '.join([str(w) for w in words_list]) or, more succinctly, using generator expression instead of list comprehension: print ' '.join(str(w) for w in words_list) Yet another alternative is to use the map function, which results in even shorter code: print ' '.join(map(str, words_list)) However, if you are on Python 2.6+ but not on Python 3, you can get print as a function by importing it from the future: from __future__ import print_function print(*words_list)
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85641547
accepted answer of: http://stackoverflow.com/q/49320238

http://stackoverflow.com/q/49323532
answer count: 1
tagged with: selenium
type: Question
has body: Bar Graph is generated on Web Page (developed using AngularJS) using data from database. Graph is created using CANVAS. Once graph is completed loaded, if you click on Red part, it will open one pop-up which will have table containing the values - Total and Missed. Same for Green - Total & Hit. Graph will always have two colors - RED & GREEN. I am trying to test this Graph using Robot Framework. I am able to Click on graph and then read the value from popup table. Only issue is I am clicking randomly. I want to identify the RED and GREEN and then Click it. After inspecting above element in IE, below information I am getting for above Graph. Please let me know the way how to identify the element in graph. Preferable option is Robot Framework but ready for any other solution also.
tagged with: robotframework
tagged with: java
tagged with: javascript
tagged with: python
accepted answer: http://stackoverflow.com/a/49324353
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49324353
has title: Clicking on graph created in Canvas (AngularJS)
linked to: http://stackoverflow.com/q/3277369

http://stackoverflow.com/comment/85784120
comment on: http://stackoverflow.com/q/49391043
type: QuestionComment
type: Comment
score: 0
has text: Would recommend removing passwords from anything you post publicly.

http://stackoverflow.com/comment/85825549
type: QuestionComment
comment on: http://stackoverflow.com/q/49407434
has text: If word boundaries are an issue, `re.replace` is probably better.
score: 0
type: Comment

http://stackoverflow.com/a/63222905
has body: How about this? grades = {60:'D',70:'C',80:'B',90:'A',100:'A'} myscore = 72 print(grades.get(int(myscore/10)*10,'F'))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49437777

http://stackoverflow.com/q/49374126
score: 1
answer count: 1
tagged with: derivative
tagged with: activation-function
favorite count: 0
has body: I am trying to write a neural network MLP model from scratch. However, I am stuck on the derivative of softmax function. I know that the softmax function in python code is def softmax(input_value): input_value -= np.max(input_value) return np.exp(input_value) / np.sum(np.exp(input_value)) However, I dont know how to write the code for the softmax derivative. Can anyone show me how to write the code in python? Thank you so much!
type: Question
has answer: http://stackoverflow.com/a/72290459
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86156325
tagged with: neural-network
tagged with: softmax
tagged with: python
has title: how to write softmax derivative in python code
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85784307
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49390954
has text: I mean instead of == something like is "equal or part of" @Wen

http://stackoverflow.com/a/49370614
has body: .pkl can serialize a very wide range of objects, not just text data.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49370591
has comment: http://stackoverflow.com/comment/85743123
has comment: http://stackoverflow.com/comment/85742896
score: 1
type: Answer

http://stackoverflow.com/comment/85575501
comment on: http://stackoverflow.com/a/49286200
score: 2
type: Comment
has text: This may block the GUI while the sound is being played, pass `False` as the second argument so that the sound is played _asynchronously_.
type: AnswerComment

http://stackoverflow.com/q/49435915
type: Question
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/49436047
has comment: http://stackoverflow.com/comment/85873810
tagged with: python
has body: how to convert reshape 1D numpy array to 2D numpy array and fill with zeroes on the columns. For example: Input: a = np.array([1,2,3]) Expected output: np.array([[0, 0, 1], [0, 0, 2], [0, 0, 3]]) How do I do this?
has answer: http://stackoverflow.com/a/49435970
has answer: http://stackoverflow.com/a/49436047
possible better answer: http://stackoverflow.com/a/49436010
has title: Left pad a 1D column vector with 0s
has answer: http://stackoverflow.com/a/49436010
type: AnsweredQuestion
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/85873740
score: 1
has comment: http://stackoverflow.com/comment/85873856
favorite count: 0
tagged with: numpy

http://stackoverflow.com/comment/85685314
has text: @sascha you are absolutely right I mixed up with Lasso regression I will edit my post thank you But my point still holds because in Ridge you improve sparsity by taking into account the input match, like a RBF kernel.
type: Comment
comment on: http://stackoverflow.com/a/49342359
type: AnswerComment
score: 0

http://stackoverflow.com/q/49433240
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85868440
tagged with: python
has comment: http://stackoverflow.com/comment/85868361
has title: What is the glob2 module?
has comment: http://stackoverflow.com/comment/85868660
tagged with: glob
score: 2
has answer: http://stackoverflow.com/a/49433448
has body: import glob2 from datetime import datetime filenames = glob2.glob("*.txt") with open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")+".txt", 'w') as file: for filename in filenames: with open(filename, "r") as f: file.write(f.read() + "\n") I was working in python and came across this name glob, googled it and couldn't find any answer, what does glob do, why is it used for?
has comment: http://stackoverflow.com/comment/85868324
has comment: http://stackoverflow.com/comment/97489765
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/57062442
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/85698682
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49349446
score: 1
has text: btw instead of `df1 = pd.read_csv(DATA_FILE1,sep=',',encoding='ISO-8859-1',index_col=['CookieID'])` its better to load every column like I did below, because I need the data from all the columns.

http://stackoverflow.com/a/49317796
type: Answer
score: -1
has body: The error message "expected an indented block" means that it expects the code to look like this: with open("test.txt") as f: for f in set(words): if words.count(f) == 2: print(f) Note that each sub-block after a colon is written one more space to the right. Better practice is to use larger indentation, such as four spaces.
answers question: http://stackoverflow.com/q/49309767
downvote count: 1
upvote count: 0

http://stackoverflow.com/a/70736859
type: Answer
score: -1
has body: In my case, the GPU on colab is super fast compared to my Nvidia GPU card on PC- based on training speeds. However, when doing simulations, which I can only presume involves CPU, my PC is nearly 50% faster (i7, 10th Gen)
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49360888

http://stackoverflow.com/q/49363564
has body: I have made a sentiment analyses on a couple of tweets from Twitter. I made this in a for loop and got the results I needed. The next step is to put it into a DataFrame. I am trying to put a for loop into a DataFrame. This is the for loop: x = 1 for tweet in public_tweets: print(x) print(tweet.text) analysis = TextBlob(tweet.text) print(analysis.sentiment) x= x+1 I want to have two columns called 'Tweets' and 'Sentiment'. Can anyone help me out? Thanks!
type: Question
tagged with: for-loop
answer count: 1
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49363650
has title: how to get the results of a for loop in a dataframe in Python
accepted answer: http://stackoverflow.com/a/49363650
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/85820496
score: 0
has text: I've updated the code with all the details since some of you asked for. I don't want to upload any file. All I need to happen is the user should input data in the form and the inputted data should go to the database.
comment on: http://stackoverflow.com/q/49408730
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49297783
upvote count: 4
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49297480
has body: One alternative below, but @jezrael's solution is optimal. Performance benchmarking %timeit original(df) # 149ms %timeit jp(df) # 81ms %timeit jez(df) # 47ms def original(df): result_df = pd.DataFrame() for diff in df['diff'].unique(): tmp_df = df.loc[df['diff']&lt;=diff,:] tmp_df = tmp_df.groupby(['country', 'campaign'], as_index=False).apply(lambda x: x.user_id.nunique()).reset_index() tmp_df['diff'] = diff tmp_df.columns=['country', 'campaign', 'unique_ppl', 'diff'] result_df = pd.concat([result_df, tmp_df],ignore_index=True, axis=0) return result_df def jp(df): result_df = pd.DataFrame() lst = [] lst_append = lst.append for diff in df['diff'].unique(): tmp_df = df.loc[df['diff']&lt;=diff,:] tmp_df = tmp_df.groupby(['country', 'campaign'], as_index=False).agg({'user_id': 'nunique'}) tmp_df['diff'] = diff tmp_df.columns=['country', 'campaign', 'unique_ppl', 'diff'] lst_append(tmp_df) result_df = result_df.append(pd.concat(lst, ignore_index=True, axis=0), ignore_index=True) return result_df def jez(df): df1 = pd.concat([df.loc[df['diff']&lt;=x].assign(diff=x) for x in df['diff'].unique()]) df2 = (df1.groupby(['diff','country', 'campaign'], sort=False)['user_id'] .nunique() .reset_index() .rename(columns={'user_id':'unique_ppl'}) .reindex(columns=['country', 'campaign', 'unique_ppl', 'diff'])) return df2
accepted answer of: http://stackoverflow.com/q/49297480
type: Answer
score: 4

http://stackoverflow.com/comment/85780576
has text: You can also do all of this like that: `lst = sorted(set(sum(line.split() for line in romeo)))`
comment on: http://stackoverflow.com/q/49389332
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49321625
upvote count: 2
type: AcceptedAnswer
score: 2
downvote count: 0
has body: This works for me: hm = sns.heatmap(corr, cmap="YlGnBu", annot=True) hm.set_xticklabels(labels=corr.columns.values, rotation=90) hm.set_yticklabels(labels=corr.columns.values, rotation=0)
type: Answer
accepted answer of: http://stackoverflow.com/q/49321361
answers question: http://stackoverflow.com/q/49321361

http://stackoverflow.com/a/49391715
upvote count: 1
has comment: http://stackoverflow.com/comment/85785016
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85785390
answers question: http://stackoverflow.com/q/49391213
has body: First things first: there already is something that does precisely what you're trying to do, so it would be wise and effective to just use it: for char in text: bin(int(char)) The problem in your code, I guess, is that you're using Python 3.x, where standard division between integers returns a float (as of [https://www.python.org/dev/peps/pep-0238/][PEP-0238]). Here is a suggestion on how you should change your function for it to work. You can check it against the built-in bin function: def decToBin(n): wynik = "" while n &gt; 0: wynik = str(n % 2) + wynik n = n // 2 return wynik
type: Answer

http://stackoverflow.com/q/49381873
answer count: 2
has comment: http://stackoverflow.com/comment/85765040
has comment: http://stackoverflow.com/comment/85764629
tagged with: encode
score: -2
has answer: http://stackoverflow.com/a/49382352
has title: Transform unicode \xe9 to é (python 2.7)
upvote count: 1
linked to: http://stackoverflow.com/q/2783079
has comment: http://stackoverflow.com/comment/85764851
linked to: http://stackoverflow.com/q/2596714
has answer: http://stackoverflow.com/a/49382135
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49382352
has comment: http://stackoverflow.com/comment/85766441
linked to: http://stackoverflow.com/q/42323347
has comment: http://stackoverflow.com/comment/85764662
linked to: http://stackoverflow.com/q/27197507
downvote count: 3
tagged with: python-unicode
tagged with: python
possible better answer: http://stackoverflow.com/a/49382135
has comment: http://stackoverflow.com/comment/85764856
duplicate of: http://stackoverflow.com/q/42323347
favorite count: 0
type: Question
tagged with: decode
has body: I'm trying to transform this unicode value: string_value = u'd\xe9cid\xe9' to string_value = u'décidé' I feel like I've tried everything: decoded_str = string_value.decode('utf-8') or string_value = str(string_value) decoded_str = string_value.encode('latin1').decode('utf-8') or string_value = string_value.decode('latin-1') for this one the result is: d\xc3\xa9cid\xc3\xa9 I have the same result if I do: string_value = string_value.encode('utf-8') I've read from: How do I convert 'blah \xe9 blah' to 'blah é blah' also from: Why does Python print unicode characters when the default encoding is ASCII? and: How do I convert a unicode to a string at the Python level? EDIT: My problem is I need to use the data, I mean if I have : string_value = u'mai 2017 \u2013 Aujourd\u2019hui' which is : mai 2017 – Aujourd’hui I want to do: string_list = string_value.split('-') But the result is: [u'mai 2017 \u2013 Aujourd\u2019hui'] And I would: ['mai 2017', 'Aujourd’hui'] NEW EDIT: I understand that I'm going to the wrong direction, thanks to your answer. \xe9 is the right representation of 'é' and it's not a problem. My real issue is why does json.loads() transform 'mai 2017 – Aujourd’hui' to 'mai 2017 \u2013 Aujourd\u2019hui' ?

http://stackoverflow.com/comment/85801291
has text: you want to add or fetch? please clearly specify what you want it's hard to understand what you want to achieve. add example of what you desire after executing the code
comment on: http://stackoverflow.com/q/49399979
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85668587
has text: Apologies as I wasn't clear. Trying to wrap my head around how to explain it. For each geohash `N` there are `M` chunks of consecutive rows associated with `N` spread over the dataframe. For each chunk `M`, I want to calculate the duration spent at that geohash. Then across the dataframe, I would calculate the min/max/average for each set of durations associated with each `N`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49333312
score: 0

http://stackoverflow.com/q/49369299
accepted answer: http://stackoverflow.com/a/49381874
tagged with: scipy
favorite count: 0
has answer: http://stackoverflow.com/a/49381874
has title: PyDSTool do not recognize SciPy version
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55731120
linked to: http://stackoverflow.com/q/48251201
tagged with: python
possible better answer: http://stackoverflow.com/a/55731120
type: Question
score: 2
answer count: 2
has body: I have installed PyDSTool package : pip install PyDSTool==0.90.2 It return : Requirement already satisfied: PyDSTool==0.90.2 in /usr/local/lib/python2.7/dist-packages/PyDSTool-0.90.2-py2.7.egg Requirement already satisfied: six in /usr/local/lib/python2.7/dist-packages (from PyDSTool==0.90.2) Requirement already satisfied: scipy&gt;=0.9 in /usr/local/lib/python2.7/dist-packages (from PyDSTool==0.90.2) Requirement already satisfied: numpy&gt;=1.6 in /usr/local/lib/python2.7/dist-packages (from PyDSTool==0.90.2) It tell me that requirement for scipy is already satisfied but in python: ~$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import PyDSTool Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/PyDSTool-0.90.2-py2.7.egg/PyDSTool/__init__.py", line 76, in &lt;module&gt; raise RuntimeError("SciPy v0.5.1 or above is required") RuntimeError: SciPy v0.5.1 or above is required I already try the solution from this post and also saw this unanswered post which seems to have a similar problem but using conda instead of pip. EDIT : I also try to download package and install with the setup.py associated but I still have the same problem EDIT 2: To solve this problem an other option is to downgrade scipy : pip install scipy==0.19.1
upvote count: 2
linked to: http://stackoverflow.com/q/48898350
downvote count: 0

http://stackoverflow.com/a/49437805
answers question: http://stackoverflow.com/q/49437665
score: 1
type: Answer
has body: You can create a new set: number_set = set() for object in old_set: try: number_set.add(int(object)) except ValueError: print("Not a number") print(number_set) You can also try removing all non-numeric objects from the set: for object in old_set: try: x = int(object) execpt ValueError: old_set.remove(object)
downvote count: 0
upvote count: 1

constraints
type: Tag
tags question: http://stackoverflow.com/q/49302597
tags question: http://stackoverflow.com/q/49390243
tag name: constraints
tags question: http://stackoverflow.com/q/49299179

http://stackoverflow.com/a/49454835
answers question: http://stackoverflow.com/q/49398152
score: 0
type: Answer
has body: "No keyword withy the name cx_Oracle" means that you are using 'cx_Oracle' as keyword. I do not see given library in commonly used Robot Extended libraries. If the case is that you installed the library wrongly and imported it correctly into Robot script as: *** Settings *** Library MyLibraryName then I would expect it to fail on the import. I agree with Dinesh. Try to use the Database Library first. Or if you cannot use Database Library (the Connect To Database Using Custom Params has limitations), it is possible to write your own Robot Library that would reuse the cx_Oracle python library and expose keywords to robot. It is generally not that complicated and I did that with pyodbc.

http://stackoverflow.com/q/49352746
answer count: 1
type: Question
has title: Pandas merge on subgroups of dataframe
tagged with: group-by
has answer: http://stackoverflow.com/a/49352799
tagged with: dataframe
tagged with: python
has body: Consider the dataframe df: SCHOOL ID SET NAME 0 Foo 1 0 Ben 1 Foo 2 0 Ben 2 Foo 3 1 Chris 3 Foo 4 1 Joe 4 Foo 5 0 Tom 5 Bar 1 0 Harry 6 Bar 2 1 Jeff 7 Bar 3 0 George 8 Bar 4 1 Tom I want to create the new dataframe SCHOOL ID SET NAME PREV_NAME 0 Foo 1 0 Ben None 1 Foo 2 0 Ben Ben 2 Foo 3 1 Chris None 3 Foo 4 1 Joe Chris 4 Foo 5 0 Tom Ben 5 Bar 1 0 Harry None 6 Bar 2 1 Jeff None 7 Bar 3 0 George Harry 8 Bar 4 1 Tom Jeff where PREV_NAME is the previous NAME (sorted by ID) in the same SCHOOL and SET as a given record. If there were no SET condition, then I could do something like df_copy = df.copy() df_copy['ID'] = df_copy['ID'] + 1 df.merge(df_copy, on=['SCHOOL', 'ID'], how='left') As there is a SET condition, we need a way of grouping each unique (SCHOOL, SET) pair and then applying the above merge (noting that we can no longer use the ID) with the new index. How would I achieve this using Pandas?
score: 0
tagged with: pandas-groupby
tagged with: pandas
type: UnansweredQuestion

http://stackoverflow.com/q/49361114
has comment: http://stackoverflow.com/comment/85752984
answer count: 1
has answer: http://stackoverflow.com/a/49377372
type: Question
has body: I am trying test my python script using jenkins.Issue I am facing is with the test report generation I have created a folder 'test_reports' in my jenkins workspace. C:\Program Files (x86)\Jenkins\jobs\PythonTest\test_reports But then when I run the script from jenkins I get the error as, ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error? How do I actually configure the test report? Is the xml file generated automatically? Any help would be greatly appreciated
tagged with: testing
tagged with: jenkins
type: UnansweredQuestion
tagged with: python
score: 0
has title: How to configure xml Report in jenkins
tagged with: report

http://stackoverflow.com/q/49331054
tagged with: google-api
has title: oauth2client for Blogger posting from a telegram bot in Heroku server
tagged with: python
tagged with: google-oauth
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49776110
tagged with: oauth2client
linked to: http://stackoverflow.com/q/16396433
answer count: 1
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49776110
favorite count: 0
type: Question
tagged with: heroku
has body: I have just deployed my telegram bot with python-telegram-bot in Heroku. My webhooks bot uses blogger for posting certain things. I did this until now with a sligthly modified custom version of sample_tools, from module google_apli_client. my_tools: """ dependencies: pip3 install --upgrade google-api-python-client This is a slightly modified implementation for substituting googleapiclient.sample_tools. It helps customizing some paths for my project files under different environments """ from __future__ import absolute_import from environments import get_active_env __all__ = ['init'] import argparse import os from googleapiclient import discovery from googleapiclient.http import build_http from oauth2client import tools, file, client def init(argv, name, version, doc, scope=None, parents=[], discovery_filename=None): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags. """ if scope is None: scope = 'https://www.googleapis.com/auth/' + name # Parser command-line arguments. parent_parsers = [tools.argparser…

http://stackoverflow.com/comment/114766025
comment on: http://stackoverflow.com/q/49380572
has text: @MadPhysicist I'm aware of that, unfortunately the unanswered queue and points aren't really something I care about anymore. I consider actually meaningful accept marks to bear a greater value for the overall community.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85597637
score: 1
has text: I used this code: driver.find_element_by_xpath("""//*[@id="react-root"]/section/main/article/header/section/div[1]/span/button""").click()
type: Comment
comment on: http://stackoverflow.com/a/49297707
type: AnswerComment

http://stackoverflow.com/comment/85708912
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167060/discussion-between-membranepotential-and-jpp).
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49354090

http://stackoverflow.com/a/49422402
has body: You can use move_to_element from ActionChains. Locate the element you want to scroll to and move_to_element will scroll to it from selenium.webdriver.common.action_chains import ActionChains element = driver.find_element(...) ActionChains(driver).move_to_element(element).perform()
answers question: http://stackoverflow.com/q/49422023
has comment: http://stackoverflow.com/comment/115099974
score: 0
type: Answer

http://stackoverflow.com/q/49340169
tagged with: python
accepted answer: http://stackoverflow.com/a/49340378
score: -1
has comment: http://stackoverflow.com/comment/85681974
has answer: http://stackoverflow.com/a/49340378
type: Question
tagged with: numpy
downvote count: 2
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/85680658
upvote count: 1
has title: use of ellipsis in modifying numpy arrays
favorite count: 0
type: AnsweredQuestion
has body: I saw the following code here, which tries to iterate a numpy array arr and modify its elements. However, I do not quite understand what the purpose of using ellipsis (...) is here. If I removed the ellipsis (i.e. using x = x*2), then the elements of arr will not be modified. Hope to get some hints from you! Thanks. for x in np.nditer(arr,op_flags='readwrite'): x[...] = x*2;

http://stackoverflow.com/q/49304817
tagged with: torch
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85635039
score: 0
tagged with: pytorch
has title: PyTorch: Comparing predicted label and target label to compute accuracy
answer count: 1
has comment: http://stackoverflow.com/comment/85716910
type: Question
has body: I'm trying to implement this loop to get the accuracy of my PyTorch CNN (The complete code of it is here) My version of the loop is so far: correct = 0 test_total = 0 for itera, testdata2 in enumerate(test_loader, 0): test_images2, test_labels2 = testdata2 if use_gpu: test_images2 = Variable(test_images2.cuda()) else: test_images2 = Variable(test_images2) outputs = model(test_images2) _, predicted = torch.max(outputs.data, 1) test_total += test_labels2.size(0) test_labels2 = test_labels2.type_as(predicted) correct += (predicted == test_labels2[0]).sum() print('Accuracy of the network on all the test images: %d %%' % ( 100 * correct / test_total)) If I run it like this, I get: &gt; Traceback (most recent call last): File &gt; "c:/python_code/Customized-DataLoader-master_two/multi_label_classifier_for2classes.py", &gt; line 186, in &lt;module&gt; &gt; main() File "c:/python_code/Customized-DataLoader-master_two/multi_label_classifier_for2classes.py", &gt; line 177, in main &gt; correct += (predicted == test_labels2[0]).sum() File "C:\anaconda\envs\pytorch_cuda\lib\site-packages\torch\tensor.py", &gt; line 360, in __eq__ &gt; return self.eq(other) RuntimeError: invalid argument 3: sizes do not match at &gt; c:\anaconda2\conda-bld\pytorch_1519501749874\work\torch\lib\thc\generated\../THCTensorMathCompareT.cuh:65 I used test_labels2 = test_labels2.type_as(predicted) to have both tensors as LongTensors, which seems to work fine to avert the "Expected this...but got..." errors. They look like this now: test_labels2 after conversion: 0 1 1 0 1 0 [torch.cuda.LongTensor of size 3x2 (GPU 0)] predicted: 1 1 1 [torch.cuda.LongTensor of size 3 (GPU 0)] I supppose the problem now is, that test_labels2[0] is returning a row but not the column. How do I get this to work?
has comment: http://stackoverflow.com/comment/85628226
tagged with: python-3.x
tagged with: tensor
accepted answer: http://stackoverflow.com/a/49384714
has comment: http://stackoverflow.com/comment/85678210
tagged with: python
has answer: http://stackoverflow.com/a/49384714

http://stackoverflow.com/a/49306116
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85615055
has body: Just use a set, which by definition, is: an unordered collection with no duplicate elements x = ['apple','banana','coconut','apple','banana','coconut','apple','banana','coconut'] print(set(x)) Output: {'apple', 'coconut', 'banana'} If you want it as a list: &gt;&gt;&gt; unique = list(set(x)) ['coconut', 'apple', 'banana']
has comment: http://stackoverflow.com/comment/85614623
downvote count: 0
answers question: http://stackoverflow.com/q/49306038
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85615594
has comment: http://stackoverflow.com/comment/85614596
has comment: http://stackoverflow.com/comment/85615036
has comment: http://stackoverflow.com/comment/85614610
accepted answer of: http://stackoverflow.com/q/49306038
has comment: http://stackoverflow.com/comment/85614493
has comment: http://stackoverflow.com/comment/85614515

http://stackoverflow.com/a/49352131
has body: The problem is that you've defined your method as a staticmethod, but then you're trying to use it as a normal method. With a normal method, when you do obj.meth(a, b), it callsCls.meth(obj, a, b), giving you that obj value as a self argument. With a static method, obj.meth(a, b) just calls Cls.meth(a, b). There is no self argument. So, the error is because you're asking for self, root, value but only passing root, value. Just as the exception says, you're one argument short. And meanwhile, you're trying to use that self within the method body, so you can't just get rid of it. If you really want this to be a staticmethod on the tree, since the only thing you're actually doing with self is calling a staticmethod on the class, you can use the class name explicitly, like this: @staticmethod def contains(root, value): if (root is None): return None elif (root.value==value): return root elif (root.value &lt; value): BinarySearchTree.contains(root.right,value) else: BinarySearchTree.contains(root.left,value) And then your code will work. Well, it'll get rid of that exception; it still has other bugs (like not returning the result of the recursive call back up the chain). But I don't understand why you wanted a staticmethod in the first place. My guess is that you're trying to port what's basically a ML-translated-to-Java design. In Java, putting a bunch of free functions in a useless class counts as OO. In Python, you don't need to do that; you just have free functions on the module. A staticmethod doesn't really give you anything extra here except confusion. Or you can actually translate this to OO. For example, if you merge the tree and node types (or turn the tree into a node handle for the root that passes the method through), you can make contains a perfectly normal method. Then you have to put the None check before each recursive call instead of at the top, but that's it.
downvote count: 0
has comment: http://stackoverflow.com/comment/85704446
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85704500
accepted answer of: http://stackoverflow.com/q/49352062
type: Answer
answers question: http://stackoverflow.com/q/49352062
has comment: http://stackoverflow.com/comment/85704551
has comment: http://stackoverflow.com/comment/85704879
score: 2
upvote count: 2

http://stackoverflow.com/q/49284640
possible better answer: http://stackoverflow.com/a/49284744
score: -3
has body: Hello I have the following dictionary: dictionary = {'key1': ['color1','color2'],'key2':['car1','car2'],'key3':['frut1']} from it I would like to get the following lists: key1 = ['color1','color2'] key2 = ['car1','car2'] key3 = ['frut1'] I need to create this lists on the fly from the dictionary I tried: list_keys = dictionary.keys() list_values = dictionary.values() and then: keys, values = zip(*dictionary.items()) However I dont have the result that I need I think that maybe this task could be completed using exec, but I dont know how to proceed since that I would like to appreciate support to overcomet this task.
has answer: http://stackoverflow.com/a/49284744
has comment: http://stackoverflow.com/comment/85572233
has title: How to get on the fly the following lists?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49284860
has answer: http://stackoverflow.com/a/49284860
has comment: http://stackoverflow.com/comment/85572129
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/85572302
has comment: http://stackoverflow.com/comment/85575692
favorite count: 0
has comment: http://stackoverflow.com/comment/85572231
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85572172
has comment: http://stackoverflow.com/comment/85572424
upvote count: 0

http://stackoverflow.com/q/49395324
has body: I am trying to get the list of volumes attached to the instances. The console shows that there is no error in the code but I get a NULL response. Could you please help me understand the problem? import boto3 def lambda_handler(event, context): region = "ap-southeast-2" ec2 = boto3.resource("ec2", region_name=region) available_volumes = ec2.volumes.all() print(available_volumes)
type: UnansweredQuestion
tagged with: amazon-ec2
answer count: 1
has comment: http://stackoverflow.com/comment/85792752
tagged with: python
has comment: http://stackoverflow.com/comment/85792608
has comment: http://stackoverflow.com/comment/85793519
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85793183
score: 0
has comment: http://stackoverflow.com/comment/85793144
has title: NULL response from AWS Lambda - get ec2 volumes
has answer: http://stackoverflow.com/a/49395876
tagged with: aws-lambda
type: Question

http://stackoverflow.com/q/49288679
favorite count: 0
type: Question
has body: I am currently attempting to solve a homework problem. The problem states to collect user inputted numbers and then arrange them using asterisks to display a graph, with the largest number having forty asterisks and the rest becoming smaller as the numbers decrease. _NumberList= [] print("Please type 'quit' to stop entering numbers.") print("Please type 'print' to view the list that has been entered so far.") a= True while a: _number= input("Please enter a number or make a selection. ") if _number.isdigit(): _number=int(_number) _NumberList.append(_number) elif _number.isalpha(): _number= _number.lower() if _number== 'quit': a= False if _number== 'print': print(_NumberList) else: print("Please use digits to enter a number.") print("For exmaple: 'ten' should be typed at '10'") else: print("Invalid entry.") _NumberList.remove(max(_NumberList)) for i in range(len(_NumberList)): _NumberList.remove(max(_NumberList)) However, I am unsure as to how to find the given proportions utilizing the numerical data. Thus far, I have considered utilizing the .pop function, but it simply isn't making a ton of sense so far. I considered making them go up by one step, but again, that doesn't seem logical, and the program can run for more than forty numbers. I know I will need to utilize a loop, hence the for loop at the end, but I'm not sure as to how to continue from there.
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49288769
tagged with: list
upvote count: 2
answer count: 1
downvote count: 0
has title: Using Astericks to Display a Bargraph of User Inputted Numbers in Python
accepted answer: http://stackoverflow.com/a/49288769

http://stackoverflow.com/comment/85653251
has text: Your code does run anything because you merely define two routines and exit without calling either.
comment on: http://stackoverflow.com/q/49325795
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49370456
tagged with: python
tagged with: merge
score: 0
type: UnansweredQuestion
has body: Here is my code. Basically, I am trying to figure out common rows based on a column called 'PolicyNum' (which has to be a variable, and therefore I cannot use df.PolicyNum.isin method). while you can suggest a better way to do it, I am also wondering why would the length of the two dataframes (printing in lines 11 and 12) be different? import pandas as pd def getPreparedDataForComparison( baseDataFrame, secondaryDataFrame, sourceName, indexKey): baseDataFrameCommon = baseDataFrame[(baseDataFrame[indexKey].isin(secondaryDataFrame[indexKey]) == False)] baseDataFrameCommon['COMBO'] = baseDataFrameCommon.apply(lambda x :','.join(x.astype(str)),axis=1) baseDataFrameCommon['DataSource'] = sourceName return baseDataFrameCommon def compareDataFrames(dataframe1, dataframe2, indexKey): dataframe1Common = getPreparedDataForComparison(dataframe1, dataframe2, 'TXT', indexKey) dataframe2Common = getPreparedDataForComparison(dataframe2, dataframe1, 'SQL', indexKey) print(len(dataframe1Common)) print(len(dataframe2Common)) def sampleData1(): cols = ['PolicyNum','firsttransactiondate','subsequentbonustotalcumulative','subsequentpremiumtotalcumulative','totalautocumulative','totalautoposteffectivedatecumulative','totalpartialcumulative','totalpartialposteffectivedatecumulative'] sourceData = [ ('E001','#1985-01-01#',100,100,100,100,100,100), ('E002','#1985-01-01#',200,200,200,200,200,200), ('E003','#1985-01-01#',100,100,100,100,100,100), ('E004','#1985-01-01#',100,100,100,100,100,100), ('E005','#1985-01-01#',100,100,100,100,100,100), ('E201','#1985-01-01#',100,100,100,100,100,100), ('E202','#1985-01-01#',100,100,100,100,100,100), ('1006','#1985-01-01#',100,100,100,100,100,100), ('1007','#1985-01-01#',100,100,100,100,100,100), ('1008','#1985-01-01#',100,100,100,100,100,100),] x = pd.DataFrame(sourceData,columns=cols) return x def sampleData2(): cols = ['PolicyNum','firsttransactiondate','subsequentbonustotalcumulative','subsequentpremiumtotalcumulative','totalautocumulative','totalaut…
has comment: http://stackoverflow.com/comment/85742582
answer count: 1
has answer: http://stackoverflow.com/a/49372624
has comment: http://stackoverflow.com/comment/85743220
has comment: http://stackoverflow.com/comment/85743752
has comment: http://stackoverflow.com/comment/85742961
type: Question
has comment: http://stackoverflow.com/comment/85743604
has comment: http://stackoverflow.com/comment/85743500
tagged with: pandas
has comment: http://stackoverflow.com/comment/85744084
has title: Merging two dataframes based on column values available in both databases, where column name is not known

http://stackoverflow.com/q/49405766
tagged with: http://stackoverflow.com/tag/csv
has title: Convert string list of dict from csv into JSON object in python
has comment: http://stackoverflow.com/comment/85814026
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49406534
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49405809
possible better answer: http://stackoverflow.com/a/49406534
has answer: http://stackoverflow.com/a/49405809
tagged with: python
tagged with: csv-import
type: AnsweredQuestion
score: 0
has body: I have a csv where for one column values are in list of dict like below [{'10': 'i ve been with what is now comcast since 2001 the company has really grown and improved and delivers a great service along with great customer service ', 'aspects':['service']}, {'20': 'good service but lack of options to allow it be more affordable allowing individual channel choices would be great ', 'aspects':['lack', 'service']}, {'30': 'it a good service but very expensive', 'aspects':['service']}, {'40': 'good service', 'aspects':['service']}, {'50': 'good service but over priced ', 'aspects':['service']}] Now because when I am reading this from CSV its a string I am not able to convert it to original type of list of dict and then json . How I can actually achieve this . Solution : data = output[output.aspects == aspect]['column1'].tolist() listData=ast.literal_eval(data[0]) return json.dumps(listData)

http://stackoverflow.com/q/49386121
tagged with: hdf5
has comment: http://stackoverflow.com/comment/85813852
has body: Short Description I have an issue where an hdf5 file has been written on a Windows machine and is unable to be opened on a Linux machine. The error message is "OSError: Unable to open file (bad superblock version number)". (As such, this issue may not be related to h5py at all, but rather a general linux/windows compatibility issue in python file open). Long Description A python virtual environment with the following packages was used on both Windows and Linux: Flask-0.12.2 Flask-RESTful-0.3.6 Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 aniso8601-3.0.0 click-6.7 h5py-2.7.1 h5py-cache-1.0 itsdangerous-0.24 lockfile-0.12.2 numpy-1.14.0 pytz-2018.3 six-1.11.0 On Windows, the file could be opened and read without issues, but on Linux it couldn't, throwing an OSError. Simply starting a new python session and typing the following is enough: import h5py f1 = h5py.File("myfile.hdf5", "r") Full error: Traceback (most recent call last): File "stdin", line 1, in module File "/usr/local/lib/python3.6/site-packages/h5py/_hl/files.py", line 312, in _ _ init_ _ fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr) File "/usr/local/lib/python3.6/site-packages/h5py/_hl/files.py", line 142, in make_fid fid = h5f.open(name, flags, fapl=fapl) File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper File "h5py/h5f.pyx", line 78, in h5py.h5f.open OSError: Unable to open file (bad superblock version number) The HDF5 file is written on a Windows machine with Java HDF5 Library from a program that I cannot modify, with hdf5 java 1.10.0 in SWMR (single-write, multiple-reader) mode. It is possible that the program doesn't close the file properly before sending it further to my program, a light-weight Linux application. In http://web.mit.edu/fwtools_v3.1.0/www/H5.format.html, the "Version Number of the Super Block" is described as follows... This value is used to determine the format of the information in th…
linked to: http://stackoverflow.com/q/46125758
has comment: http://stackoverflow.com/comment/85809507
type: Question
accepted answer: http://stackoverflow.com/a/49413130
has answer: http://stackoverflow.com/a/49413130
downvote count: 0
tagged with: python
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/85813182
has title: python h5py file read "OSError: Unable to open file (bad superblock version number)"
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85827966
tagged with: linux
tagged with: h5py
has comment: http://stackoverflow.com/comment/85812850
linked to: http://stackoverflow.com/q/26613570
score: 7
tagged with: windows
answer count: 1

http://stackoverflow.com/a/49421961
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49421144
has body: Full code can be this type:: import MySQLdb import MySQLdb.cursors encoding = "utf8mb4" db = MySQLdb.connect( host='', user='', passwd='', db='', compress=1, port=, charset='utf8mb4', use_unicode=True, ) cursor = db.cursor() data = [ ('Jane','dffd','sdas','sdas'), ('Jane','dffd','sdas','sdas'), ('Jane','dffd','sdas','sdas') ] sql = "INSERT INTO test VALUES %s;" %(str(tuple(data)).replace('((','(').replace('))',')')) print(sql) // you can print the sql query and verify to insert data on test mysqlworkbech for confirm data structure is cursor.execute(sql) db.commit() db.close()

http://stackoverflow.com/comment/85628340
comment on: http://stackoverflow.com/a/49312549
score: 0
type: AnswerComment
has text: But I am not able to use and change the res inside the recursion. How do I do that?
type: Comment

http://stackoverflow.com/comment/85874793
type: QuestionComment
has text: This answer has worked for me in the past: https://stackoverflow.com/a/312464/3282436
score: 0
comment on: http://stackoverflow.com/q/49436376
type: Comment

http://stackoverflow.com/comment/128362384
score: 0
has text: You don't have to compare a dictionary to an empty dictionary: you can just write `if not os.listdir(path):` instead. Otherwise I can't see how this answer differs from a later answer with 8 votes. https://stackoverflow.com/a/54034774/952234
comment on: http://stackoverflow.com/a/49284171
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49288533
tagged with: list
accepted answer: http://stackoverflow.com/a/49288575
tagged with: python
has answer: http://stackoverflow.com/a/49288575
tagged with: append
has title: Python automatically extract list index in and append data
score: 0
answer count: 1
tagged with: loops
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I don't know how to describe the problem. Given an example: a=[[1,2],[3,4],[5,6]] b=[['a','b'],['c','c']] x=[a,b] Now I want to append the elements of elements of x to their previous elements, (in this case b's elements on every a's elements), that I can use t=[] for i in a: for j in b: t.append(i+j) then my desired result became: t [[1, 2, 'a', 'b'], [1, 2, 'c', 'c'], [3, 4, 'a', 'b'], [3, 4, 'c', 'c'], [5, 6, 'a', 'b'], [5, 6, 'c', 'c']] In this case I know there are a and b in x, so I can append them. However, if I don't know how many items in x, how could I append the elements? like x=[a,b,c,d,e,...] Have tried with loops, but seems not good. I am thinking combination but not sure how to do that.
tagged with: combinations
type: AnsweredQuestion

http://stackoverflow.com/q/49290755
tagged with: python
upvote count: 2
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87445749
favorite count: 0
type: Question
has title: Dickey Fuller Test shows significance but the mean is not constant
has comment: http://stackoverflow.com/comment/85588889
has body: I'm trying to examine whether my timeseries is stationary using Dickey Fuller Test. Looking at my raw data, I'm quite sure that they are not stationary. However, after implementing Dickey Fuller Test on my data using python, the results show that my timeseries is sationary (with a very low p-value). My code and the results are as follow: def test_stationarity(timeseries): #Determing rolling statistics rolmean = timeseries.rolling(window=7,center=False).mean() rolstd = timeseries.rolling(window=7,center=False).std() #Plot rolling statistics: orig = plt.plot(timeseries, color='blue',label='Original') mean = plt.plot(rolmean, color='red', label='Rolling Mean') std = plt.plot(rolstd, color='black', label = 'Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean &amp; Standard Deviation') #plt.savefig('stationarity_{}.png'.format(timeseries.columns.values[0])) #plt.show(block=False) #Perform Dickey-Fuller test: print ('Results of Dickey-Fuller Test:') dftest = adfuller(timeseries.values.ravel(), autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used']) for key,value in dftest[4].items(): dfoutput['Critical Value (%s)'%key] = value print (dfoutput) The data is a timesries of physical cross-border electricity flow between Germany and France in hourly time-frame. Negative values indicate electricity flow from Germany to France Results of Dickey-Fuller Test: Test Statistic -7.252678e+00 p-value 1.763304e-10 Lags Used 4.600000e+01 Number of Observations Used 2.031600e+04 Critical Value (1%) -3.430672e+00 Critical Value (5%) -2.861682e+00 Critical Value (10%) -2.566846e+00 Can someone please explain me how come this is possible? Is there any assumption to use the Dickey Fuller test?
has comment: http://stackoverflow.com/comment/85584625
type: UnansweredQuestion
tagged with: arima

http://stackoverflow.com/comment/85663822
comment on: http://stackoverflow.com/q/49330004
score: 0
type: QuestionComment
has text: This didn't effect the performance, but if you use `pd.util.testing.assert_frame_equal()` it will show that the first dataframe is using `Int64Index` on level 0 & the second is using `Float64Index` on level 0.
type: Comment

http://stackoverflow.com/q/49353337
has comment: http://stackoverflow.com/comment/85706945
has comment: http://stackoverflow.com/comment/85706991
has comment: http://stackoverflow.com/comment/85706981
has answer: http://stackoverflow.com/a/49353408
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85706960
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85706925
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85706948
score: -1
has body: Write a function named uniqueWords that counts how many different words there are in each line of an input file and writes that count to a corresponding line of an output file. The input file already exists when uniqueWords is called. uniqueWords creates the output file. Input. The function uniqueWords takes two parameters: inFile, a string that is the name of a text file that is to be read. The file that inFile refers to contains only lower case letters and white space (no punctuation marks or other special characters). outFile, a string that is the name of the file to which uniqueWords writes its output. The input file is in the current working directory. uniqueWords should create the output file in that directory. Output. For each line of inFile, uniqueWords should write a corresponding line to outFile containing a single integer: the number of unique words on the line. If the content of the file turn.txt is below, a time to build up a time to break down a time to dance a time to mourn a time to cast away stones a time to gather stones together the function call uniqueWords('turn.txt', 'turnOut.txt') should create a file named turnOut.txt with this content: 7 5 8 This is what I got so far: def uniqueWords(file_input, file_output): for line in file_input: words = line.split(" ") uniqueWords = set(words) total = len(uniqueWords) file_output.write(str(total) + "\n") file_input = open("turn.txt", "r") file_output = open("turnOut.txt", "w") uniqueWords('turn.txt', 'turnOut.txt') The code is giving me the following error: file_output.write(str(total) + "\n") AttributeError: 'str' object has no attribute 'write'
has title: I/O Can't Write To File

http://stackoverflow.com/a/49304133
score: 0
answers question: http://stackoverflow.com/q/49303791
type: Answer
has body: This is my take on this problem: import itertools nucleotide='ATC----GCTGTA--A-----T' # group the repeated positions gaps = [(k, sum(1 for _ in vs)) for k, vs in itertools.groupby(nucleotide)] # text formating summary_head = "Number of gaps = {0}" summary_gap = """ Index Position of Gap region {0} = {2} to {3} Length of Gap region {0} = {1} """ # Print output print summary_head.format(len([g for g in gaps if g[0]=="-"])) gcount = 1 # this will count the gap number position = 0 # this will make sure we know the position in the sequence for i, g in enumerate(gaps): if g[0] == "-": gini = position # start position current gap gend = position + g[1] - 1 # end position current gap print summary_gap.format(gcount, g[1], gini, gend) gcount+=1 position += g[1] This generates your expected output: # Number of gaps = 3 # Index Position of Gap region 1 = 3 to 6 # Length of Gap region 1 = 4 # Index Position of Gap region 2 = 13 to 14 # Length of Gap region 2 = 2 # Index Position of Gap region 3 = 16 to 20 # Length of Gap region 3 = 5 EDIT: ALTERNATIVE WITH PANDAS import itertools import pandas as pd nucleotide='ATC----GCTGTA--A-----T' # group the repeated positions gaps = pd.DataFrame([(k, sum(1 for _ in vs)) for k, vs in itertools.groupby(nucleotide)]) gaps.columns = ["type", "length"] gaps["ini"] = gaps["length"].cumsum() - gaps["length"] gaps["end"] = gaps["ini"] + gaps["length"] - 1 gaps = gaps[gaps["type"] == "-"] gaps.index = range(1, gaps.shape[0] + 1) summary_head = "Number of gaps = {0}" summary_gap = """ Index Position of Gap region {0} = {1[ini]} to {1[end]} Length of Gap region {0} = {1[length]} """ print summary_head.format(gaps.shape[0]) for index, row in gaps.iterrows(): print summary_gap.format(index, row) This alternative has the benefit that if you are analyzing multiple sequences you can add the sequence identifier as an extra column and have all the data from all your sequences in a single data structure; something like this: import itertools import pandas a…

http://stackoverflow.com/a/49313260
type: Answer
answers question: http://stackoverflow.com/q/49313221
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49313221
has body: As &gt; is lower precedence than &amp;, A &gt; X &amp; B is parsed as A &gt; (X &amp; B) but what you want is (A &gt; X) &amp; B.

http://stackoverflow.com/q/49407517
has title: Matplotlib recursion error when showing consecutive plots
answer count: 0
tagged with: matplotlib
has body: I have a list with roughly 3000 items (every item is a list of 10points). One item might look like this: [['-19.05364812189936' '-8.078571934798015'] ['-4.481956059532247' '10.88512402551382'] ['-15.985506732813608' '-19.92397590361446'] ['-1.2933416017009214' '-10.233128986534373'] ['-19.640113394755492' '2.7974946846208364'] ['-9.466119773210488' '1.8171420978029766'] ['4.998052799433026' '-0.5782990786676117'] ['-7.883010276399716' '-9.731805457122608'] ['-2.754521615875266' '-18.244450744153085'] ['-17.105912473423103' '13.09440644932672'] ['right' '0']] What I want in the end is to plot the first item, do some user interaction (assign a label to the plotted points), confirm (save to another list: 10 points + label) and plot the next and so on. Here is my current code: import numpy as np import Utils as utils import matplotlib.pyplot as plt methods = utils.ClusteringMethods() db = utils.DbConnection() formations = methods.readFromDump('testNewInterval') formation_list = [] formation_list.append('5-3-2') formation_list.append('4-4-2') formation_list.append('4-3-3') labelled_formations = [] def add_formation_def(): name = input('Please specify formation') if(name not in formation_list): formation_list.append(name) else: print('Already there, please try again') def showOptionList(): for idx, item in enumerate(formation_list): print(idx, ' - ', item) def getCurrentFormation(index): return formations[index] def showClearPlot(): ax1.clear() ax1.imshow(im, extent=[-55, 55, -35, 35], aspect='auto') def nextPlot(): print('in next plot..') global currentIndex global currentFormation currentIndex = currentIndex +1 ax1.clear() ax1.imshow(im, extent=[-55, 55, -35, 35], aspect='auto') currentFormation = getCurrentFormation(currentIndex) showPlot(currentFormation) def showPlot(currentFormation): orientation = currentFormation[-1][0] print('orientation: ', orientation) currentFormation = currentFormation[:-1] for point in currentFormation: ax1.plot(float(point[0]), float(point[…
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85816250
score: 2
has comment: http://stackoverflow.com/comment/85816393

http://stackoverflow.com/comment/85593130
score: 0
has text: I was just want to make the answerer easier
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49295002

routes
type: Tag
tags question: http://stackoverflow.com/q/49438740
tag name: routes

http://stackoverflow.com/comment/85705587
type: QuestionComment
comment on: http://stackoverflow.com/q/49352707
type: Comment
has text: `now()` doesn't generate a tuple, it generates a `datetime` object. You can see that by printing it out: `datetime.datetime(2018, 3, 18, 13, 56, 10, 763983)`. And `datetime` objects have attributes and methods. Which you can look up with `help` in your REPL, or in the docs.
score: 0

screen-scraping
tags question: http://stackoverflow.com/q/49398568
tag name: screen-scraping
tags question: http://stackoverflow.com/q/49396531
type: Tag

http://stackoverflow.com/q/49432605
has comment: http://stackoverflow.com/comment/85867135
favorite count: 0
type: Question
has body: I am developing a system where I am avoiding an accident by slowing down the motor speed using distance provided by ultrasonic sensor. Also, if accident happens, it must be sense through sw420 and accident occurred result should be displayed. The problem is that, i have code for both motor mgmt. - distance sensing and impact detection. But as I want them to run parallel i.e.., both are running at same time. How to do it? Eg. If car is running smoothly, suddenly another car hits you from, let's say, from back.....then automatically, sw420 sensor should sense it and alert the accident occurred message. Or in other words, some type of multiprocessing concept is needed which i am unaware of. Here's what i have done till now - 1. Motor is perfectly slowing down when ultrasonic sensor senses shorter distance. import RPi.GPIO as GPIO import time # Define GPIO For Driver motors GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(18, GPIO.OUT) gpio.setwarnings(False) gpio.setmode(gpio.BOARD) gpio.setup(7,gpio.OUT) pwm=GPIO.PWM(18,100) # Define GPIO for ultrasonic central GPIO_TRIGGER_CENTRAL = 23 GPIO_ECHO_CENTRAL = 24 GPIO.setup(GPIO_TRIGGER_CENTRAL, GPIO.OUT) # Trigger &gt; Out GPIO.setup(GPIO_ECHO_CENTRAL, GPIO.IN) # Echo &lt; In # Functions for driving def goforward(): pwm.start(100) GPIO.output(12, True) GPIO.output(16, False) GPIO.output(18, True) def goforwardslow(): GPIO.output(12, True) GPIO.output(16, False) GPIO.output(18, True) def stopmotors(): GPIO.output(12, False) GPIO.output(16, False) GPIO.output(18, False) def buzzer(): try: while True: gpio.output(7,0) time.sleep(0.2) gpio.output(7,1) time.sleep(0.2) except KeyboardInterrupt: gpio.cleanup() exit #Detect front obstacle def frontobstacle(): # Set trigger to False (Low) GPIO.output(GPIO_TRIGGER_CENTRAL, False) # Allow module to settle time.sleep(0.2) # Send 10us pulse to trigger GPIO.output(GPIO_TRIGGER_CENTRAL, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER_CENTRAL, Fal…
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85867274
downvote count: 0
tagged with: raspberry-pi3
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85867202
has title: Ultrasonic sensor, dc motor and sw420 in Python
has comment: http://stackoverflow.com/comment/86102927
tagged with: sensors
score: 1

http://stackoverflow.com/comment/85871464
type: Comment
score: 0
type: QuestionComment
has text: 'from multiprocessing import Process #and on sign_up() p = Process(target=send_email_and_insert) p.start() p.join()`
comment on: http://stackoverflow.com/q/49434727

http://stackoverflow.com/q/49333333
has answer: http://stackoverflow.com/a/49333365
downvote count: 0
has body: This is a hackerrank problem "to insert a node in the nth position of a linked list". From the problem's description, we are supposed to insert 10 at position 1. 3 &gt; 5 &gt; 4 &gt; 2 &gt; Null is an existing linked list and we have to insert 10 at index one. The output should look like this 3 &gt;10 &gt; 5 &gt; 4 &gt; 2 &gt; Null. This is my code: def InsertNth(head, data, position): temp = Node(data) if (head == None): head = temp #if head is Null then new node is the head temp.next = None #return head else: current = head i = 0 while(i &lt; position - 1): #for i in range(position-1): current = current.next i = i +1 next_node = current.next #keep the address to the next element current.next = temp . temp.next = next_node return head The output I get using this code is 2&gt; 10 &gt; 5 &gt; 4 &gt; 2 &gt; Null, which is wrong. I tried a lot to fix, but the code looks fine to me. Can anyone please point out my error, with some explanation ?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85669212
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85669250
tagged with: linked-list
score: 1
has title: inserting a node in the nth position of a linked list
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/62329255
answer count: 2
accepted answer: http://stackoverflow.com/a/49333365
has answer: http://stackoverflow.com/a/62329255

http://stackoverflow.com/q/49323540
tagged with: python
has answer: http://stackoverflow.com/a/49561285
has title: Visual Studio 2017 Python Environment not working
tagged with: intellisense
favorite count: 0
type: Question
has body: I have a problem with my Visual Studio 2017 Community. I installed Visual with Python, but Intellisense doesn't detect Python modules. Screen1 Screen2 Screen3 Screen4 I repaired Visual Studio - it doesn't solve problem. I reinstall python 3.64 - it also doesn't solve problem.
answer count: 2
has comment: http://stackoverflow.com/comment/85649508
tagged with: environment-variables
has answer: http://stackoverflow.com/a/72018268
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: visual-studio

http://stackoverflow.com/q/49279948
favorite count: 0
type: Question
tagged with: noise
tagged with: python-3.x
has body: I'm trying to create a list of a certain number of arrays, say 10, where each array is comprised of a number of random numbers between two values in a normal distribution. What I have so far is: noise = abs(np.random.normal(0,0.1,20)) noise1 = [] for i in range(10): noise1 = noise.append(range(i,10)) Where 'noise' is an array of 20 random positive values between 0 and 0.1. Now I want to create a list of 10 of these arrays with different random numbers each time called 'noise1'. Using this method I get the error 'TypeError: 'numpy.ndarray' object is not callable', meaning the program tries to use the array as a function, but I don't know how to solve the problem. Would really appreciate some help!
has comment: http://stackoverflow.com/comment/85562652
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/49280093
accepted answer: http://stackoverflow.com/a/49280093
upvote count: 1
score: 1
answer count: 1
tagged with: arrays
downvote count: 0
has title: Trying to create a list of lists of a random noise sample in Python 3.X

http://stackoverflow.com/comment/85797508
type: QuestionComment
has text: Possible duplicate of [Tornado: DummyFuture does not support blocking for results](https://stackoverflow.com/questions/42425318/tornado-dummyfuture-does-not-support-blocking-for-results)
score: 0
comment on: http://stackoverflow.com/q/49359418
type: Comment

http://stackoverflow.com/a/49426494
answers question: http://stackoverflow.com/q/49426422
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49426422
has body: You are returning the value of wrapper. Instead just return the function. def auth_login(func): def wrapper(*args, **kwargs): print("Authenticating......") func(*args, **kwargs) return wrapper # Here was the issue. @auth_login def login(username, password): print("Successfully logged in:",username) login('setu', 'setu')
has comment: http://stackoverflow.com/comment/85853951
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85854122
upvote count: 3

http://stackoverflow.com/a/58976743
type: Answer
answers question: http://stackoverflow.com/q/49407659
has body: I had a similar problem and ended up using the 7z Command Line (7za.exe), since it supports more functions than Python's tarfile, including deleting files from archive. The downside of this solution is that you need to carry the 7za.exe file around with the program. In your case, you could use something like os.system("7za d x.tar a.txt") Do however keep in mind that os.system is deprecated and you should use subprocess. Never used it, so I can't really help more.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49313000
answers question: http://stackoverflow.com/q/49312914
score: 1
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49312914
type: AcceptedAnswer
has body: You could rename the user_id column in df2 to id. Since the name is the same, it won't be duplicated. df2 = pd.read_csv('b.csv').rename(columns={'user_id': 'id'}) df3 = pd.merge(df1, df2, on='id', how='outer') Otherwise you can drop the user_id column adter the merge. df3 = df3.drop('user_id', axis=1)

http://stackoverflow.com/a/49301930
score: 10
type: Answer
has body: Try using lambda function numbers = map(lambda n: setToZeroIfDivisibleBy(n, divisor=3), numbers) And rather than pass did you mean return n?
upvote count: 10
accepted answer of: http://stackoverflow.com/q/49301880
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49301880

http://stackoverflow.com/a/49353887
accepted answer of: http://stackoverflow.com/q/49352249
has body: Since you did post minimal code this small example to help you resolve your issue, the error is telling you that you are calling your function before the widget is created. import time from tkinter import * def update_clock(): now = time.strftime("%H:%M:%S") clock.configure(text=now) clock.after(1000, update_clock) root = Tk() clock = Label(root, bg="red") clock.pack() update_clock() # make sure you call this after you label has been packed root.mainloop()
answers question: http://stackoverflow.com/q/49352249
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85708520
type: Answer

http://stackoverflow.com/q/49419073
score: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
has title: Append string to matching columns (with various data types) in the same Pandas dataframe
type: Question
accepted answer: http://stackoverflow.com/a/49419088
has answer: http://stackoverflow.com/a/49419088
tagged with: python
has body: I am looking for a way to turn this set of data columns0 columns1 columns2 row1 bill bill row2 $0.00 $0.00 row3 Free $1.25 row4 $1.50 $1.25 into this ... columns0 columns2 columns3 row1 bill( match) bill(match) row2 $0.00(match) $0.00(match) row3 Free $1.25 row4 $1.50 $1.25 when I use this df.loc[(df['columns1'] == df['columns2 ']), :] += ' (Match)' columns0 columns1 columns2 row1**(match)** bill( match) bill( match) row2**(match)** $0.00(match) $0.00(match) row3 Free $1.25 row4 $1.50 $1.25 I am getting a match on the columns0 as well.I would only like "match" to be on only columns1 and columns2. I need some way to match the similarity across rows or even columns to find the match. If anyone has a better way to go about this then or has resources that could help me figure out this issue in python + pandas issue, please comment.
tagged with: multiple-columns
type: AnsweredQuestion

http://stackoverflow.com/comment/85795342
score: 0
has text: So you have a csv text file or an excel file?
comment on: http://stackoverflow.com/q/49395981
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49370745
answer count: 1
has title: Tkinter image function returns nothing
score: -1
tagged with: image
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85742809
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85742714
upvote count: 0
type: UnansweredQuestion
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49370878
has body: My problem is when I call image1 it works but doesn't show any image at all Here is the full code of the program: from Tkinter import * from PIL import Image, ImageTk import random root = Tk() n = random.randint(1,1) def image1(): image = Image.open("400.jpg") image = image.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image) def image2(): image = Image.open("236.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image2) def image3(): image = Image.open("258.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image3) def image4(): image = Image.open("20130818_145719.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image4) def image5() : image = Image.open("DSC01190.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image5) def image6(): image = Image.open("DSC01472.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image6) def image7(): image = Image.open("IMG_0029.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image7) def image8(): image = Image.open("IMG_0204.jpg") image = image1.resize((500, 250), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image8) label = Label(image=image1()) # keep a reference! label.pack() root.mainloop()
has comment: http://stackoverflow.com/comment/85742808
linked to: http://stackoverflow.com/q/16424091
duplicate of: http://stackoverflow.com/q/16424091

http://stackoverflow.com/a/49319767
answers question: http://stackoverflow.com/q/49319667
type: Answer
has body: That's one of the possible solutions (note that I am using list a list). If you want to support even more options without extending a list you might be interested in adding some RegExp. positive = ['yes','Yes','y','Y'] negative = ['no','No', 'n','N'] month = "March" while True: a = input('The month that you want to archive is March' '(Y or N) ? ') if a in negative: input("You will now leave, press Enter......") break elif a in positive: print("Let's do it") input("The archive will start now, press Enter......") break else: print("Enter either 'Y' to continue or 'N' to leave") print (month)
score: 0

http://stackoverflow.com/q/49324892
tagged with: mrjob
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Python Map Reduce Mr job
tagged with: python
tagged with: mapreduce
tagged with: hadoop
has body: I am new to python programming so excuse me in advance if I ask something that is easily solved. I want to use MapReduce for processing a csv file that has some values and the output must return the maximum value.This is the script i've written so far: from mrjob.job import MRJob class MRWordCounter(MRJob): def mapper(self, key, line): for word in line.split(','): yield 'MAXIMUM VALUE IN FILE:',int(word) def reducer(self, word, occurrences): yield word, max(occurrences) if __name__ == '__main__': MRWordCounter.run() Now, the script works fine, it maps and reduces to the maximum value and prints it as an output but I think the way I implement it with the yield 'MAXIMUM VALUE IN FILE:' is incorrect since the mapper always sends that string to the reducer. Can someone confirm if that is the incorrect way to implement it and recommend me how I can fix it?
score: 1
tagged with: max
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50262033

http://stackoverflow.com/q/49332811
favorite count: 0
accepted answer: http://stackoverflow.com/a/49333124
type: Question
tagged with: numpy
upvote count: 2
tagged with: shift
tagged with: dataframe
tagged with: python
has body: I need to iterate over a dataframe to get the values from the first date to move to the next row and start with same first value. Importantly, I need the new inputs to stop at the column range and not overflow past day5 in the example below. current output: day1 day2 day3 day4 day5 date 2018-03-16 1.0 2.0 3.0 4.0 5.0 2018-03-17 NaN NaN NaN NaN NaN 2018-03-18 NaN NaN NaN NaN NaN 2018-03-19 NaN NaN NaN NaN NaN 2018-03-20 NaN NaN NaN NaN NaN desired output: day1 day2 day3 day4 day5 date 2018-03-16 1.0 2.0 3.0 4.0 5.0 2018-03-17 NaN 1.0 2.0 3.0 4.0 2018-03-18 NaN NaN 1.0 2.0 3.0 2018-03-19 NaN NaN NaN 1.0 2.0 2018-03-20 NaN NaN NaN NaN 1.0 sample code to iterate: data = [1, 2, 3, 4, 5] columns_name = ['day1', 'day2', 'day3', 'day4', 'day5'] df = pd.DataFrame(data) df = df.T df.columns = columns_name dates = pd.date_range('2018-03-16', '2018-03-20').tolist() dates_df = pd.DataFrame(dates) dates_df.columns = ['date'] dfs = [df, dates_df] combined = pd.concat(dfs, axis=1) combined = combined.set_index(['date'])
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49333124
tagged with: pandas
answer count: 1
downvote count: 0
has title: Iterating over rows in pandas, shifting values to the right by one

http://stackoverflow.com/comment/85589209
comment on: http://stackoverflow.com/a/49286229
score: 0
has text: I was actually basing it on the best example I found on training on images. I've edited it to categorical and actually the filename field in the csv read by pandas has a label which is a number and there's atleast 1000 of them. I do have over 200,000 images so I also don't expect it to overfit.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49428723
tagged with: pathlib
has comment: http://stackoverflow.com/comment/85858761
score: 4
upvote count: 6
has body: Today I learned that for open(filename).read() we cannot expect that the resources bound to the hidden file object are given back immediately, although I observed this on my system. (See the accepted answer of the question Does reading an entire file leave the file handle open?). The second answer made me resist to roll my own helper function, it told me that pathlib already offers exactly this function. But actually, this seems not to be the case. With the following script (test.py), I get different results: # The German accent characters are Ä,Ö,Ü,ä,ö,ü, and ß. from pathlib import Path; def pathlib_read_text(filename, encoding=None): return Path(filename, encoding=encoding).read_text() def mylocal_read_text(filename, encoding=None): with open(filename, encoding=encoding) as f: return f.read() def test(fun): print(fun+'_read_text:') print(eval(fun+'_read_text')(__file__, 'utf-8')) test('pathlib') test('mylocal') The output to the Windows console (python test.py) contains Ã",Ã-,Ão,Ã¤,Ã¶,Ã¼, and ÃY. in the first block, when I redirect the output into a file, I get the second block wrong (In Notepad++ it's displayed xC4,xD6,xDC,xE4,xF6,FC, and xDF in White on Black) if the file is treated as utf-8. Is there anything I overlooked? I tried to examine the 3.6.3 code, but found no bug so far ... read_text (1170) open (1152) Edit The following version reinforces my feeling that it's a bug in pathlib or in one of the underlying libraries/functions. Maybe it's only a Windows issue, where the default encoding is mostly different from utf-8. Now it's sufficient to run the test in a console window. accents = ''' Ä,Ö,Ü,ä,ö,ü,ß ''' from pathlib import Path; import codecs def pathlib_read_text(filename, encoding=None, errors=None): return Path(filename, encoding=encoding, errors=errors).read_text() def mylocal_read_text(filename, encoding=None, errors=None): with open(filename, encoding=encoding, errors=errors) as f: return f.read() def space_it(error): return ' '; codecs.register…
has title: Unexpected results from Path.read_text (of pathlib) when reading utf-8 encoded file
has comment: http://stackoverflow.com/comment/85859150
tagged with: file-io
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/7409780
has answer: http://stackoverflow.com/a/78575764
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85859104
tagged with: encoding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/126141056
has comment: http://stackoverflow.com/comment/126153330
tagged with: python

http://stackoverflow.com/a/49312361
has comment: http://stackoverflow.com/comment/85626911
has comment: http://stackoverflow.com/comment/85626799
has comment: http://stackoverflow.com/comment/85626823
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85626892
downvote count: 0
has comment: http://stackoverflow.com/comment/85626888
has body: It seems you are trying to run a Python2 librairy with Python3. varlist1 = list( set(weights.values() + biases.values()) - set(varlist2) ) The above line is correct in Python2 where dict.values() returns a list, but is not in Python3 where it returns a special type dict_values. If you can fix this code, the following would be valid in both Python2 and Python3 varlist1 = list((set(weights.values()) | set(biases.values())) - set(varlist2)) Otherwise, you cannot use this library with Python3.
accepted answer of: http://stackoverflow.com/q/49312282
type: Answer
has comment: http://stackoverflow.com/comment/85626894
has comment: http://stackoverflow.com/comment/85626866
has comment: http://stackoverflow.com/comment/85626938
has comment: http://stackoverflow.com/comment/85764290
answers question: http://stackoverflow.com/q/49312282
has comment: http://stackoverflow.com/comment/85626732
has comment: http://stackoverflow.com/comment/85626917
has comment: http://stackoverflow.com/comment/85626702
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85626883

http://stackoverflow.com/a/49436047
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49435915
has body: a = np.array([1,2,3]) Option 1 np.pad (this should be fast) np.pad(a[:, None], ((0, 0), (2, 0)), mode='constant') array([[0, 0, 1], [0, 0, 2], [0, 0, 3]]) Option 2 Assign a slice to np.zeros (also very fast) b = np.zeros((3, 3)) b[:, -1] = a array([[0., 0., 1.], [0., 0., 2.], [0., 0., 3.]])
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49435915
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85613977
has text: Is the request invoking the lambda or is it failing in the api gateway?
comment on: http://stackoverflow.com/q/49286852
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85606011
has text: Hah. I'm guessing there's something wrong with my assignment then! The requirements state that what i described should be possible but after all the time I've spent on it I feel like you're right. Guess there's a typo or something somewhere! Thanks for the clarification!
type: Comment
comment on: http://stackoverflow.com/a/49301592
score: 0
type: AnswerComment

http://stackoverflow.com/comment/96926202
has text: What is the default initialization if I don't specify one?
type: AnswerComment
score: 58
comment on: http://stackoverflow.com/a/49433937
type: Comment

http://stackoverflow.com/comment/85580355
type: Comment
comment on: http://stackoverflow.com/q/49288559
type: QuestionComment
has text: Can you post part of 'test.txt'?
score: 0

http://stackoverflow.com/comment/85736346
type: AnswerComment
has text: thanks, that really helped. Do you know any links or technichal insights of doing this in python?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49367430

http://stackoverflow.com/comment/85836677
type: Comment
comment on: http://stackoverflow.com/q/49417352
score: 2
has text: The easy way: `noletters = phone.translate(str.maketrans( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "2223334445556667777888999922233344455566677778889999")) `
type: QuestionComment

http://stackoverflow.com/comment/86101988
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49482105
has text: is that will access nextoken? or I need to access it with another way? could u plz help me in this way?

http://stackoverflow.com/comment/85590064
type: QuestionComment
score: 0
has text: Does it returns when you gives directly the field name and variable instead of dynamic parameter ?
comment on: http://stackoverflow.com/q/49293712
type: Comment

http://stackoverflow.com/comment/85703539
score: 0
comment on: http://stackoverflow.com/q/49351716
type: Comment
type: QuestionComment
has text: I meant the expected output for your json

http://stackoverflow.com/comment/85798121
has text: In case of `break` on successful condition it will exit while loop and continue executing statements after while statement to till end. But in `return` it will come out from that method and no statements will be executed after the loop. Write a print statement after while loop to see difference.
comment on: http://stackoverflow.com/q/49398282
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49312325
has body: You can use re to condense the solution: import re data = [re.split('\W+', i.strip('\n')) for i in open("letters.txt")] last_data = [[int(a), b] for a, *b in data] Output: [[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]]
score: 0
answers question: http://stackoverflow.com/q/49312298
type: Answer

http://stackoverflow.com/comment/85704366
type: Comment
has text: What is this `{{=` syntax? Some other Javascript plugin maybe?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49351202

http://stackoverflow.com/comment/132708942
has text: Asynchronous operations won't give you significant improvement here, as GET NEXT has to be executed sequentially. You should, however, use GET BULK instead, which processes much more data in one run. Sadly Ilya didn't give you that hint.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49307045

http://stackoverflow.com/q/49353752
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm hitting an API that sends a JSON response with two key:value pairs. I'm currently saving the response to my dataframe by hitting the API 2 different times and using withColumn to save each key:value pair to a column separately, instead of hitting the API once and saving both key:value pairs at once. Does anyone have guidance on how to do this properly? My dataframe is one column that contains the values I ship to the API: businessId dksldfaw2 kkldsdok3 djdfkdfk3 23lksdlk8 The JSON response: {response: FirstDataPoint: "SomethingSomething" SecondDataPoint: "SomethingSomething"} My code (which calls the API twice to parse one response): def FirstVariableCode(businessId): response = api.query(id=businessId) x = response['FirstVariable'].encode('utf-8').strip() return x def SecondVariableCode(businessId): response = api.query(id=businessId) y = response['SecondVariable'].encode('utf-8').strip() return y FirstVariableCode = udf(FirstVariableCode, StringType()) SecondVariableCode = udf(SecondVariableCode, StringType()) df.withColumn('FirstVariable', FirstVariableCode(df.businessId)) df.withColumn('SecondVariable', SecondVariableCode(df.businessId)) How can I hit the API once and save both values to their respective columns correctly? I feel like I'm using 'withColumn' as a crutch and not doing this properly. Thanks
tagged with: apache-spark
answer count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/49355156
has title: Use Requests Module and return response to Pyspark Dataframe
accepted answer: http://stackoverflow.com/a/49355156
type: Question
tagged with: pyspark

http://stackoverflow.com/a/49418457
type: Answer
has comment: http://stackoverflow.com/comment/85838625
score: 0
answers question: http://stackoverflow.com/q/49417023
has body: I guess this is specified by your assignment, but in real life, I would use a dictionary of dictionaries as the basis of your ... dictionary and not a bunch of if statements: def translate(word,language): dictionary = { "french": {"cat":"chat", "dog":"chien"}, "german": {"cat":"katze", "dog":"hund"}, "spanish": {"cat":"gato", "dog":"perro"} } return(dictionary.get(language).get(word,word)) This yields: &gt;&gt;&gt; translate("cat","french") 'chat' &gt;&gt;&gt; translate("cat","german") 'katze' &gt;&gt;&gt; translate("dog","german") 'hund' &gt;&gt;&gt; translate("mouse","spanish") 'mouse' Here it returns the original word if it is not found. You'd want to build in error handling for words or languages that weren't in dictionary,

http://stackoverflow.com/a/49324936
has comment: http://stackoverflow.com/comment/85651323
type: Answer
has body: use merge df1.merge(df2, left_on=['a', 'b'], right_on=['u', 'v'], how='left') It basically is a left join
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85651382
answers question: http://stackoverflow.com/q/49324898

http://stackoverflow.com/a/49340194
answers question: http://stackoverflow.com/q/49314270
downvote count: 0
has body: I had the same error. In the older versions of the dbf module, I was able to write dbf files by opening them just with Tbl.open() However, with the new version (dbf.0.97), I have to open the files with Tbl.open(mode=dbf.READ_WRITE) in order to be able to write them.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49314270
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85690012

http://stackoverflow.com/comment/108223020
type: AnswerComment
has text: This doesn't work for me. I can activate my environment, then open python and it is 3.8 (as I want it to be), but when I open jupyter notebook, the only option for a new file is in Python 2.
score: 6
comment on: http://stackoverflow.com/a/49430918
type: Comment

http://stackoverflow.com/a/53761784
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49297630
upvote count: 2
has body: You can create a custom class to hook into the makemigrations class and add your custom migrations stuff then execute using the "runscript" command. Below is a sample module where the file is named custom_migrations.py and located in a "scripts" folder off one of your apps: from django.core.management.commands.makemigrations import Command """ To invoke this script use: manage.py runscript custom_migrations --script-args [app_label [app_label ...]] name=my_special_migration verbosity=1 """ class MyMigrationMaker(Command): ''' Override the write method to add more stuff before finishing ''' def write_migration_files(self, changes): print("Do some stuff to \"changes\" object here...") super().write_migration_files(changes) def run(*args): nargs = [] kwargs = {} # Preload some options with defaults and then can be overridden in the args parsing kwargs['empty'] = True kwargs['verbosity'] = 1 kwargs['interactive'] = True kwargs['dry_run'] = False kwargs['merge'] = False kwargs['name'] = 'custom_migration' kwargs['check_changes'] = False for arg in args: kwarg = arg.split('=', 1) if len(kwarg) &gt; 1: val = kwarg[1] if val == "True": arg_val = True elif val == "False": arg_val = False elif val.isdigits(): arg_val = int(val) else: arg_val = val the_kwargs[kwarg[0]] = arg_val else: nargs.append(arg) MyMigrationMaker().handle(*nargs, **kwargs)

installation
tags question: http://stackoverflow.com/q/49295992
tags question: http://stackoverflow.com/q/49436922
tags question: http://stackoverflow.com/q/49327445
tags question: http://stackoverflow.com/q/49311983
tags question: http://stackoverflow.com/q/49329079
tags question: http://stackoverflow.com/q/49324241
tag name: installation
tags question: http://stackoverflow.com/q/49359744
tags question: http://stackoverflow.com/q/49342847
tags question: http://stackoverflow.com/q/49419171
tags question: http://stackoverflow.com/q/49373535
type: Tag

http://stackoverflow.com/q/49331426
type: UnansweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85664925
downvote count: 3
has body: Im trying to create a list of a sliding window from a pandas dataframe but instead of giving me the specific values it only returns the header. Why is this happening and what can I do to get around this? import pandas as pd batch_size = 3 data = pd.DataFrame([1,2,3,4,5,6,7,8,9]) def process(data): batches = [] for i in range(len(data) - batch_size + 1): batches.append(list(data.iloc[i:i + batch_size])) return batches process(data)
tagged with: pandas
has title: pandas returning header instead of values
has comment: http://stackoverflow.com/comment/85664958
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49331470
has answer: http://stackoverflow.com/a/49331533
upvote count: 2
has comment: http://stackoverflow.com/comment/85664944
answer count: 2
has comment: http://stackoverflow.com/comment/85664889

http://stackoverflow.com/a/49281320
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49280402
accepted answer of: http://stackoverflow.com/q/49280402
type: Answer
has body: You can do everything you are wanting to do within PIL. If you are wanting to reduce the value of every pixel by half, you can do something like: import PIL im = PIL.Image.open('input_filename.jpg') im.point(lambda x: x * .5) im.save('output_filename.jpg') You can see more info about point operations here: https://pillow.readthedocs.io/en/latest/handbook/tutorial.html#point-operations Additionally, you can do arbitrary pixel manipulation as: im[row, col] = (r, g, b)

http://stackoverflow.com/a/49407868
has comment: http://stackoverflow.com/comment/85843924
type: Answer
answers question: http://stackoverflow.com/q/49407711
has comment: http://stackoverflow.com/comment/85847424
score: 0
has comment: http://stackoverflow.com/comment/85819002
has body: Well try to debug your code by yourself first. Anyhow for your question Why is this happening? : It gives you error in postCode = split_address[4] because your list has 4 elements 0,1,2,3 and you are accessing the 4th element which is not present.. you don't have the index[4] thats why it gives you error out of range! Updated Area: In your for loop the length of split_address is changing to 4 and 5 and when the length is 4 and your are trying to get index[4] it will give definitely gives you error of index out of range to solve this issue you have to add a check on it. Try this: import re import requests r = requests.get('https://halalhmc.org/outlets-by-name/') from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('div', attrs={'class':'outlet-content'}) records = [] for result in results: name = result.find('h3').text fullAddress = (result.find('p', attrs={'class':'outlet-address'})).text split_address = fullAddress.split(',') address1 = split_address[0] city = split_address[1] city1 = split_address[2] validPcode = re.match(&quot;[A-Z]{2}[0-9] [0-9][A-Z]{2}&quot;,split_address[3]) if validPcode: postCode = split_address[3] else: county = split_address[3] if len(split_address) is 4: postCode = split_address[3] elif len(split_address) is 3: postCode = split_address[4] records.append((name,address1[10:],city,city1,postCode)) # only for checking print records[1] print records[2] print records[3] print records[4] print records[5] i have modified your code little bit and only adds one check on it(split_address). Hope you will understand and it will help you! :)
upvote count: 1
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49407711

http://stackoverflow.com/comment/135581586
comment on: http://stackoverflow.com/a/49470953
has text: @rozi A similar iteration concept can be applied to write data to a file, but the target file will likely get data in a wrong order because with imap, the pool process which starts and finishes first would write its data chunk first. Also, if two processes try to write to a file at the same time this will throw an error because the file is locked by one of them. You can solve this of course in different ways but keep your requirements in mind. Check here https://superfastpython.com/multiprocessing-pool-imap/#:~:text=The%20imap()%20function%20should,all%20issued%20tasks%20have%20completed.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49402786
tagged with: parsing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85815260
type: UnansweredQuestion
has body: I want to parse/extract content stored in pdf and docx files which are stored in hdfs. The python libraries available (like docx2txt, pdfminer) are not working in the hdfs. These files are giving a binary output if I try to read with the native hdfs libraries. Are there any python libraries which can do such task? Or a way in which we can convert the binary files to extract the data.
tagged with: python
linked to: http://stackoverflow.com/q/49357302
has comment: http://stackoverflow.com/comment/85860127
tagged with: hadoop
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/85843421
downvote count: 0
tagged with: hdfs
upvote count: 1
has comment: http://stackoverflow.com/comment/85815495
has title: parse docx and pdf in hdfs

http://stackoverflow.com/comment/85878479
score: 0
comment on: http://stackoverflow.com/q/49437047
type: Comment
type: QuestionComment
has text: Try printing `np.where(M1 == A)` and see what you get. You should get the indices you need.

http://stackoverflow.com/comment/85747536
type: Comment
type: AnswerComment
has text: Sorry about that, I've misread the question. A simply re-raise should fix though
score: 0
comment on: http://stackoverflow.com/a/49372905

http://stackoverflow.com/q/49387439
has answer: http://stackoverflow.com/a/49658285
favorite count: 0
type: Question
answer count: 2
score: 2
upvote count: 2
type: UnansweredQuestion
has title: Heroku fails on install pip requirements
downvote count: 0
tagged with: pip
has answer: http://stackoverflow.com/a/49387650
tagged with: heroku
tagged with: setuptools
has body: Something very strange is happening in Heroku, I normally install my packages when I do a git push heroku master, but now what worked for months for me not work anymore. Here is the error: remote: -----&gt; Python app detected remote: -----&gt; Installing pip remote: -----&gt; Installing requirements with pip remote: Obtaining django-widget-tweaks from git+https://github.com/julianogouveia/django-widget-tweaks/#egg=django-widget-tweaks (from -r /tmp/build_843fc05109f047351641f1b9e1db069d/requirements.txt (line 2)) remote: Cloning https://github.com/julianogouveia/django-widget-tweaks/ to /app/.heroku/src/django-widget-tweaks remote: Complete output from command python setup.py egg_info: remote: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] remote: or: -c --help [cmd1 cmd2 ...] remote: or: -c --help-commands remote: or: -c cmd --help remote: remote: error: invalid command 'egg_info' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /app/.heroku/src/django-widget-tweaks/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to partnersbit-prod. What is more crazy about is that the egg_info error is a setuptools pip error, and the heroku always use the last version of pip with setuptools. Someone has a ideia to how to start debugging this on heroku? The heroku documentation doesn't say anything about this and the stackoverflow already opened issue about this problem is incomplete and not well documented.
tagged with: python

http://stackoverflow.com/a/72522430
score: 1
downvote count: 0
upvote count: 1
type: Answer
has body: According to the documentation, the following would return the doc id of the final element in the db in TinyDB 4.7.0: el = db.all()[-1] record = db.get(doc_id=el.doc_id) Using Document IDs
answers question: http://stackoverflow.com/q/49385888

http://stackoverflow.com/comment/85780856
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49377321
has text: You accept it by clicking the check mark. See here: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work ... upvoting requres 15 rep, so you can't yet

http://stackoverflow.com/comment/85835543
has text: [Literally googled, "How to remove lines from plot matplotlib:"](https://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a-matplotlib-plot?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49416776
type: QuestionComment

http://stackoverflow.com/comment/85621254
has text: No, if the `shutil.move` completes then the original file is removed via `os.unlink`. When I run the script again, I start by generating the backup, mapping to the shared source directory and shared destination directory and then starting the transfer. The old backup is manually removed prior to starting another transfer.
type: Comment
comment on: http://stackoverflow.com/q/49309508
type: QuestionComment
score: 0

http://stackoverflow.com/a/49325076
has comment: http://stackoverflow.com/comment/85652675
accepted answer of: http://stackoverflow.com/q/49323752
type: Answer
has comment: http://stackoverflow.com/comment/85651976
upvote count: 3
has comment: http://stackoverflow.com/comment/85653278
downvote count: 0
type: AcceptedAnswer
has body: I don't know the win32com api, but if you want to do a depth first search, you can try something like this. def dfr(folders, tardir): for folder in folders: # if `folder` follows python convention, it should be iterable. if folder.Name == tardir: # is it the correct folder? return folder match = dfr(folder.Folders, tardir) # recurse into child folders if match: # return result from recursive call of dfr() if successful # This was missing in your code, which is why it returns None return match tf = dfr(o.Folders, "Journal") print(tf) The reason why your function returns None, is that you only return if the folder name matches. But since that might happen several levels deep in the recursion, you also have to propagate the result up the stack to the initial caller. If you don't do that, python functions return None by default.
answers question: http://stackoverflow.com/q/49323752
score: 3

http://stackoverflow.com/q/49409124
has comment: http://stackoverflow.com/comment/85835237
type: Question
has comment: http://stackoverflow.com/comment/85833158
tagged with: pygraphviz
has comment: http://stackoverflow.com/comment/85830406
tagged with: flowchart
has title: Drawing a large number of graphs using Graphviz
type: UnansweredQuestion
tagged with: python
tagged with: graphviz
has body: I want to use graphviz to generate a large number of graphs. Now I have a chart with 10 thousands data which indicate reaction fomulars, like: a + b -> c; e + f -> g ... Is there any convenient way to convert the flow chart to graphs one by one by using graphviz? or any other tools? digraph 1{ node[shape="record"]; edge[style="dashed"]; a[style="filled",color="red",fillcolor="chartreuse"]; b; c; d; a -&gt;b; b -&gt;d; c -&gt;d[color="green"]; d-&gt; a; }
has comment: http://stackoverflow.com/comment/85830378
has comment: http://stackoverflow.com/comment/85841350
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85829563
tagged with: networkx

http://stackoverflow.com/comment/85626186
has text: And finally: you don't need to turn a string into a list in the first place. A string is an iterable collection of characters, just like the list is. (You could even change `loL` into a string, `'ABCDEFGHIJKLMNOPQRSTUVWXYZ'`, or just use `string.ascii_uppercase`, which already is exactly that string.
type: Comment
comment on: http://stackoverflow.com/q/49312066
score: 0
type: QuestionComment

http://stackoverflow.com/q/49346867
has title: Python cannot input values into 2d array
has answer: http://stackoverflow.com/a/49347015
type: Question
tagged with: 2d
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: arrays
has body: I want to input some values into a 2D array. It works for the first part when I input into arr[days][count], however, when I input it the second time when while is days&gt;1, it seems like it doesn't work. For example, is days is 3 and numcows is 2, I can only input values into arr[1][1] not to arr[2][0] and onwards. arr = [[0 for row in range(week+1)] for column in range(numcows)] for days in range(1,week+1): count=0 for count in range(numcows): while days == 1: arr[0][count] = float(input ("Enter cow ID")) ... arr[days][count] = daytotal count = count+1 break while days&gt;1: for count in range(numcows): .... arr[days][count] = daytotal #doesn't work count = count+1 days = days+1 What is wrong with my code?

http://stackoverflow.com/comment/85785907
has text: @martineau, the `varName` and `varVal` are the exception. `varVal` represents a list of values associated with a `varName`. For example `varA = [10]` and `varB = [1,0]`. This association is the issue which causes `it.product` not to work in the way I have coded in the example.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49391455
score: 0

http://stackoverflow.com/comment/85639033
has text: what I meant is that you are missing `transformed = als_model.transform(rating_data)` part
comment on: http://stackoverflow.com/q/49299079
score: 0
type: QuestionComment
type: Comment

nested-forms
type: Tag
tag name: nested-forms
tags question: http://stackoverflow.com/q/49330402

http://stackoverflow.com/comment/85708578
type: Comment
score: 0
type: AnswerComment
has text: And the explicit `np.array` conversion is unnecessary too. Maybe a quick explanation of how that works will please the OP :)
comment on: http://stackoverflow.com/a/49354082

http://stackoverflow.com/comment/85752555
score: 0
type: AnswerComment
has text: Note: It is not the vectors itself but the inner products. Also I am not sure if dividing by that sqrt expression qualifies as linear.
comment on: http://stackoverflow.com/a/49375661
type: Comment

http://stackoverflow.com/q/49294547
has body: I am working on writing a log file (first time still new to programming as a whole) and I want to have the log file write the number of records inserted into a mysql database and a message. eg. 2018-03-15 09:09:59 - 30 records entered in the database I have two functions, one is the actual write function to the log file and the other is to send the message once the records have been entered. write to log function def write_log(): logger = logging.getLogger() logger.setLevel(logging.DEBUG) hf = logging.FileHandler(os.path.join(logdir, logfile), 'a') hf.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(message)s') hf.setFormatter(formatter) logger.addHandler(hf) return True executes query function def execute(con): sql = "INSERT INTO `table`(`value`, `value`, `value`) cursor = con.cursor() try: cursor.execute(sql) con.commit() logging.info(count + 'records entered in the database.') # Obviously this is where I'm wrong. except pyodbc.Error: con.rollback() logging.error('Could not enter records into the database.') cursor.close() con.close() return True and then I call the functions in another script. It all works fine but clearly the count and messages aren't being written the way I want them to be like this 2018-03-15 09:09:59 - 30 records entered in the database I have split the count variable and then the message like this: logging.info(count) logging.info('records entered in the database.') but that doesn't produce the right output for obvious reasons. I appreciate the help. Thank you.
answer count: 1
tagged with: python
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49294666
has answer: http://stackoverflow.com/a/49294666
downvote count: 0
has title: add count in log file python 3.6.4
upvote count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/85591528
tagged with: logfiles
has comment: http://stackoverflow.com/comment/85591759
type: AnsweredQuestion

http://stackoverflow.com/comment/85827902
score: 0
type: Comment
type: QuestionComment
has text: @jpp TypeError: to_excel() got an unexpected keyword argument 'sheetname', with second change, same issue.
comment on: http://stackoverflow.com/q/49412811

http://stackoverflow.com/q/49299107
has body: I have this code: from subprocess import Popen, PIPE class App(QtWidgets.QMainWindow): def __init__(self): super().__init__() # Create some widgets self.setGeometry(500, 500, 300, 300) self.pushButton = QtWidgets.QPushButton( 'Print', self) self.pushButton.setGeometry(20, 20, 260, 30) self.pushButton.clicked.connect(self.print_widget) xlabel = "Hello World" def print_widget(self): p = Popen('echo "This is a test." + xlabel | lpr', shell=True, stdout=PIPE, stderr=PIPE) out, err = p.communicate() app = QtWidgets.QApplication(sys.argv) gui = App() gui.show() app.exec_() When the push button is clicked, the terminal will execute the command: echo "This is a test." + xlabel | lpr and the output will be: But the Output I want is "This is a test. Hello World" but obviously my syntax is wrong and I need help.
has answer: http://stackoverflow.com/a/49299236
tagged with: python
accepted answer: http://stackoverflow.com/a/49299236
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pyqt5
has title: Running a Command in Terminal Using PyQt5 GUI
type: Question
has answer: http://stackoverflow.com/a/49299161
possible better answer: http://stackoverflow.com/a/49299161

http://stackoverflow.com/a/49375714
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49375681
type: Answer
has body: You can use reshape: pd.DataFrame(df.values.reshape(-1,2, order='F'), columns=['First','Second']) Out[12]: array([[10, 40], [20, 50], [30, 60]], dtype=int64)
score: 1

http://stackoverflow.com/comment/85622495
type: AnswerComment
has text: Glad it helped!
type: Comment
comment on: http://stackoverflow.com/a/49310162
score: 0

http://stackoverflow.com/a/62509894
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/115573553
has comment: http://stackoverflow.com/comment/115556688
type: Answer
answers question: http://stackoverflow.com/q/49428469
has body: In Scikit learn library, you have parameter called ccp_alpha as parameter for DescissionTreeClassifier. Using this you can do post-compexity-pruning for DecessionTrees. Check this out https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html

http://stackoverflow.com/q/49334647
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85690906
favorite count: 0
tagged with: deep-learning
has body: I have managed to train a CNN model in Tensorflow which the input is 1D ECG signals of sick and healthy patients. The architecture is composed of CNN-Max pooling-CNN-Max pooling-CNN-Max pooling-CNN-Max pooling-Fully connected-Fully connected-Softmax. I used this code for defining the cost function and training the network: # How we train train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy) # Just initialize sess.run(tf.global_variables_initializer()) # Define accuracy correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1),name='correct_pred') accuracy = tf.reduce_mean(tf.cast( correct_prediction, "float"),name='accuracy') #%% Actually train train= np.reshape(train,[-1,length,1]) test= np.reshape(test,[-1,length,1]) epochs = 200 train_acc = np.zeros(epochs//10) test_acc = np.zeros(epochs//10) start_time = time.time() for i in tqdm(range(epochs), ascii=True): # Record summary data, and the accuracy if (i+1) % 10 == 0: # Check accuracy on train set TRA = accuracy.eval(feed_dict={x: train, y_: onehot_train, keep_prob: 0.75}) train_acc[i//10] = TRA # And now the validation set TEA = accuracy.eval(feed_dict={x: test, y_: onehot_test, keep_prob: 0.75}) test_acc[i//10] = TEA print("Epoch:", '%04d' % (i+1), ", Train accuracy=", "{:.9f}".format(TRA), ", Test accuracy=", "{:.9f}".format(TEA),"--- %s seconds ---" % (time.time() - start_time)) start_time = time.time() train_step.run(feed_dict={x: train,\ y_: onehot_train, keep_prob: 0.75}) after 200 epochs the accuracy of model reaches about 95 percent. After training I saved my model like this #%% Save the weights saver = tf.train.Saver() saved_path=saver.save(sess , 'SavedModel/SCD') But when I use the saved model for evaluating the accuracy with exactly the train data, It shows a 54 percent accuracy. i can't figure out what's the problem. from __future__ import print_function from __future__ import division import scipy.io as sio import numpy as np import tensorflow as tf import time as time from scipy im…
has comment: http://stackoverflow.com/comment/85716828
has title: different accuracy in Tensorflow saved model
has comment: http://stackoverflow.com/comment/85717574
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/85716993
type: Question
has comment: http://stackoverflow.com/comment/85717489
answer count: 0

http://stackoverflow.com/q/49344994
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has body: I am trying to enter username and password using python(2.7.10) and selenium and running into below error?how to fix it? CODE:- from selenium import webdriver import selenium driver = webdriver.Chrome("/Users/username/Downloads/chromedriver") driver.get("http://website.com") username = selenium.document.getElementById("Username") password = selenium.document.getElementById("Password") username.send_keys("username") password.send_keys("password") selenium.find_element_by_name("Login").click() HTML: company Central Login Open Directory Login Username Password Error:- AttributeError: 'module' object has no attribute 'document'
score: 0
upvote count: 1
answer count: 1
tagged with: selenium
downvote count: 1
has answer: http://stackoverflow.com/a/49345114
accepted answer: http://stackoverflow.com/a/49345114
favorite count: 0
type: Question
has title: AttributeError: 'module' object has no attribute 'document'
has comment: http://stackoverflow.com/comment/85690016
has comment: http://stackoverflow.com/comment/85690039

dictionary
tags question: http://stackoverflow.com/q/49372133
tags question: http://stackoverflow.com/q/49301365
tags question: http://stackoverflow.com/q/49331336
tags question: http://stackoverflow.com/q/49398737
tags question: http://stackoverflow.com/q/49323426
tags question: http://stackoverflow.com/q/49355577
tags question: http://stackoverflow.com/q/49423324
tags question: http://stackoverflow.com/q/49289685
tags question: http://stackoverflow.com/q/49394878
tags question: http://stackoverflow.com/q/49402817
tags question: http://stackoverflow.com/q/49415625
tags question: http://stackoverflow.com/q/49285347
tags question: http://stackoverflow.com/q/49339423
tags question: http://stackoverflow.com/q/49367132
tags question: http://stackoverflow.com/q/49283510
tags question: http://stackoverflow.com/q/49310708
tags question: http://stackoverflow.com/q/49405831
tags question: http://stackoverflow.com/q/49332675
tags question: http://stackoverflow.com/q/49354262
tags question: http://stackoverflow.com/q/49331312
tags question: http://stackoverflow.com/q/49289863
tags question: http://stackoverflow.com/q/49312650
tags question: http://stackoverflow.com/q/49308665
tags question: http://stackoverflow.com/q/49324347
tags question: http://stackoverflow.com/q/49310749
tags question: http://stackoverflow.com/q/49348944
tags question: http://stackoverflow.com/q/49355843
tags question: http://stackoverflow.com/q/49389920
tags question: http://stackoverflow.com/q/49408230
tags question: http://stackoverflow.com/q/49373636
tags question: http://stackoverflow.com/q/49353986
tags question: http://stackoverflow.com/q/49300887
tags question: http://stackoverflow.com/q/49399471
tags question: http://stackoverflow.com/q/49366491
tags question: http://stackoverflow.com/q/49325712
tags question: http://stackoverflow.com/q/49305060
tags question: http://stackoverflow.com/q/49323896
tags question: http://stackoverflow.com/q/49287058
tags question: http://stackoverflow.com/q/49315155
tags question: http://stackoverflow.com/q/49341165
tags question: http://stackoverflow.com/q/49420112
tags question: http://stackoverflow.com/q/49437057
tags question: http://stackoverflow.com/q/49363130
tags question: http://stackoverflow.com/q/49308562
tags question: http://stackoverflow.com/q/49296538
tags question: http://stackoverflow.com/q/49283840
tags question: http://stackoverflow.com/q/49438954
tags question: http://stackoverflow.com/q/49307023
tags question: http://stackoverflow.com/q/49361673
tags question: http://stackoverflow.com/q/49290991
tags question: http://stackoverflow.com/q/49372995
tags question: http://stackoverflow.com/q/49437776
tags question: http://stackoverflow.com/q/49282789
tags question: http://stackoverflow.com/q/49435968
tags question: http://stackoverflow.com/q/49419486
tags question: http://stackoverflow.com/q/49418839
tags question: http://stackoverflow.com/q/49335168
tags question: http://stackoverflow.com/q/49380994
tags question: http://stackoverflow.com/q/49325796
tags question: http://stackoverflow.com/q/49317898
tags question: http://stackoverflow.com/q/49337984
tags question: http://stackoverflow.com/q/49416470
tags question: http://stackoverflow.com/q/49437153
tags question: http://stackoverflow.com/q/49282941
tags question: http://stackoverflow.com/q/49389054
tags question: http://stackoverflow.com/q/49318684
tags question: http://stackoverflow.com/q/49353922
tags question: http://stackoverflow.com/q/49395963
tags question: http://stackoverflow.com/q/49387995
type: Tag
tags question: http://stackoverflow.com/q/49287971
tags question: http://stackoverflow.com/q/49340714
tags question: http://stackoverflow.com/q/49343619
tags question: http://stackoverflow.com/q/49367943
tags question: http://stackoverflow.com/q/49350925
tags question: http://stackoverflow.com/q/49395178
tags question: http://stackoverflow.com/q/49351496
tags question: http://stackoverflow.com/q/49328936
tags question: http://stackoverflow.com/q/49435546
tags question: http://stackoverflow.com/q/49410893

http://stackoverflow.com/a/49381061
accepted answer of: http://stackoverflow.com/q/49380994
answers question: http://stackoverflow.com/q/49380994
type: Answer
score: 0
has body: dict1 = {'F0': (117, 118), 'F1': (227, 118), 'F2': (337, 118), 'F3': (447, 118), 'F4': (557, 118)} list1 = [(117, 118), (447, 228), (227, 448), (557, 558),(557, 118)] print {k:v for k,v in dict1.items() if v in list1} #python dict comprehension Output: {'F0': (117, 118), 'F4': (557, 118)}
type: AcceptedAnswer

http://stackoverflow.com/q/49292496
tagged with: pandas
tagged with: python
score: 8
answer count: 2
type: UnansweredQuestion
has title: Reading Excel file without hidden columns in Python using Pandas or other modules
downvote count: 0
has body: Can anyone tell me how to read the Excel file without hidden columns in Python with Pandas or any other modules? When I try to read excel file using Pandas, for example: file_np = pd.read_excel(f_name) the dataframe file_np always contain all the column. From this dataframe, I do not know how to identify which column was hidden in the Excel file. Thank you!
has answer: http://stackoverflow.com/a/49292701
tagged with: excel
favorite count: 0
type: Question
upvote count: 8
has answer: http://stackoverflow.com/a/77957974

http://stackoverflow.com/q/49286228
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49293710
has comment: http://stackoverflow.com/comment/85575338
tagged with: jupyter-notebook
type: AnsweredQuestion
upvote count: 0
has body: I trained a machine learning model using sklearn in a jupyter notebook which took many hours. Next, i shutdown the notebook, but the server is still running locally. Can I just restart the notebook and pickle the model or is it too late?
answer count: 1
tagged with: pickle
tagged with: persistence
accepted answer: http://stackoverflow.com/a/49293710
favorite count: 0
type: Question
tagged with: serialization
has title: Can I pickle sklearn model after restart notebook kernel?
downvote count: 1

http://stackoverflow.com/comment/94219583
score: 0
has text: This error did not go, despite changing the permissions (from properties) or Bit defender settings. However, when I created a new folder as a regular user (not admin) then it started working from that folder. I guess, the folder where you get "permission denied" error must have been created as Admin.
type: Comment
comment on: http://stackoverflow.com/q/49436155
type: QuestionComment

http://stackoverflow.com/q/49349759
has answer: http://stackoverflow.com/a/49349760
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49349760
tagged with: python
has body: I am using Python 3.5 and the mapnik library bindings available through the python-mapnik project. I have multiple versions of the mapnik library on my machine, how can I do a sanity check to see which version of mapnik the is being used by the python bindings?
tagged with: mapnik
upvote count: 2
type: AnsweredQuestion
score: 1
has title: How can I check what version of mapnik I am using in python?
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/97322504
has text: @lucidbrot did you try to run the function from a second file and then get the exception from the first? Another solution could be to import the library inside the function (handling try and except to the function) and try to work your solution from there.
comment on: http://stackoverflow.com/a/55296909
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85796095
score: 1
has text: How do you want to use this string, and what sequence of characters do you want it to contain? It's clear that you're confused about the relationship between the string literal you write, how the string displays, and what's actually in the string. We need more information to know how to explain things and determine what the final code should look like.
comment on: http://stackoverflow.com/q/49396973
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85664230
comment on: http://stackoverflow.com/q/49331011
score: 0
type: Comment
type: QuestionComment
has text: this is not the real string, I just gave an example to shorten it

http://stackoverflow.com/q/49439828
tagged with: regex
has answer: http://stackoverflow.com/a/49440032
possible better answer: http://stackoverflow.com/a/49440032
type: AnsweredQuestion
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/49439996
upvote count: 3
favorite count: 0
type: Question
has title: Capturing posessives and prefixes with Python regex
accepted answer: http://stackoverflow.com/a/49439996
has body: I'm trying to write a regex for Python to capture the various forms of "archipelago" that appear in a corpus. Here is a test string: This is my sentence about islands, archipelagos, and archipelagic spaces. I want to make sure that the archipelago's cat is not forgotten. And we cannot forget the meta-archipelagic and protoarchipelagic historians, who tend to spell the plural 'archipelagoes.' I want to capture the following from the string: archipelagos archipelagic archipelago's meta-archipelagic protoarchipelagic archipelagoes Attempt 1 Using the regex (archipelag.*?)\b and testing with <a href="http://pythex.org/?regex=(archipelag.*%3F)%5Cb&amp;test_string=This%20is%20my%20sentence%20about%20islands%2C%20archipelagos%2C%20and%20archipelagic%20spaces.%20I%20want%20to%20make%20sure%20that%20the%20archipelago%27s%20cat%20is%20not%20forgotten.%20And%20we%20cannot%20forget%20the%20meta-archipelagic%20and%20protoarchipelagic%20historians%2C%20who%20tend%20to%20spell%20the%20plural%20%27archipelagoes.%27&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofollow noreferrer">Pythex, I capture portions of all six forms. But there are problems: archipelago's is captured only as archipelago. I want to get the possessive. meta-archipelagic is captured only as archipelagic. I want to be able to capture hyphenated prefixes. protoarchipelagic is captured only as archipelagic. I want to be able to capture non-hyphenated prefixes. Attempt 2 If I try the regex (archipelag.*?)\s (see <a href="http://pythex.org/?regex=(archipelag.*%3F)%5Cs&amp;test_string=This%20is%20my%20sentence%20about%20islands%2C%20archipelagos%2C%20and%20archipelagic%20spaces.%20I%20want%20to%20make%20sure%20that%20the%20archipelago%27s%20cat%20is%20not%20forgotten.%20And%20we%20cannot%20forget%20the%20meta-archipelagic%20and%20protoarchipelagic%20historians%2C%20who%20tend%20to%20spell%20the%20plural%20%27archipelagoes.%27&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofoll…
has answer: http://stackoverflow.com/a/49440066
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85615181
score: 0
comment on: http://stackoverflow.com/q/49305946
type: QuestionComment
has text: My bad -- you are correct! I fixed the wording. Thanks for pointing it out.
type: Comment

http://stackoverflow.com/comment/85788362
type: QuestionComment
comment on: http://stackoverflow.com/q/49393057
type: Comment
score: 0
has text: @PatrickArtner That just regurgitates the docs, not as helpful for a beginner as providing a real example IMO.

http://stackoverflow.com/q/49399501
accepted answer: http://stackoverflow.com/a/49399522
score: 5
answer count: 1
tagged with: django
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has body: I can't find solution for the TypeError: init() takes 1 positional argument but 2 were given TypeError appears when I try to make migrations in ubuntu concole. error: File "/home/wojciech/workspace/conference_room/conference_room/conference/forms.py", line 8, in NewRoomForm taken = forms.ChoiceField(TAKEN, label='Taken', widget=forms.Select) TypeError: __init__() takes 1 positional argument but 2 were given forms: from django import forms from .models import TAKEN class NewRoomForm(forms.Form): name = forms.CharField(label='Name', max_length=32) number = forms.IntegerField(label='Room Number') taken = forms.ChoiceField(TAKEN, label='Taken', widget=forms.Select) description = forms.CharField(label='Description', widget=forms.Textarea) models: TAKEN = ( (True, 'Yes'), (False, 'No') ) class Room(models.Model): name = models.CharField(max_length=32) number = models.IntegerField() taken = models.BooleanField(choices=TAKEN) description = models.CharField(max_length=128) Any ideas how to fix it?
has title: Django TypeError: __init__() takes 1 positional argument but 2 were given
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/49399522
type: Question

http://stackoverflow.com/q/49336436
has body: I wrote my first Python package in Notepad++ and it ran fine from the command line but having problems running it from Jupyter Notebook. The package/function is saved in Anaconda3.1/Lib/site-packages and seems to load fine but stumbles at the first call to sklearn's train_test_split (which is within my custom function) with the error message: name 'train_test_split' is not defined Within the package that works from the command line, I imported train_test_split() as either ... from sklearn.model_selection import train_test_split #OR import sklearn.model_selection as sksel ... with corresponding calls to train_test_split() and both work. I also tried putting either import statement inside the function definition when calling from Jupyter notebook but still same error persists. Any suggestions, advice most welcome. Thanks,
type: Question
has comment: http://stackoverflow.com/comment/85677003
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85690298
has title: Problems calling self-written Python package from Jupyter Notebook

http://stackoverflow.com/comment/85582493
comment on: http://stackoverflow.com/q/49289493
type: Comment
type: QuestionComment
has text: Your solution works? How is it inefficient?
score: 0

http://stackoverflow.com/a/56504605
has body: So, I achieved that by implementing a post_generation function: class PackageFactory(factory.Factory): class Meta: model = Package company = factory.SubFactory('dashboard.test_factories.CompanyFactory') class CompanyFactory(factory.Factory): class Meta: model = Company @factory.post_generation def default_package(self, create, _, **__): PackageFactory(company=self) The company=self kwarg stops the recursion and the factory is properly created with the desired default package attribute.
upvote count: 4
score: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49329394
type: Answer

http://stackoverflow.com/q/49340762
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49340963
has body: new = ['|&lt;', '@', '1', '3', '7', '0', '8', '\/'] old = ['K', 'A', 'L', 'E', 'T', 'O', 'B', 'V'] ask_user = input("Type a sentence: ") def ask_replace_letters(): ask_user = input("Do you want to replace letters? ").upper() if ask_user == "YES": ask_user1 = input("What letters do you want to replace? ").upper() for letter in ask_user1: if letter not in old: print("This program cannot replace the letter(s): ", letter) print(replace_letters()) elif ask_user == "NO": print(replace_phrases()) else: print("Please enter yes or no.") def replace_letters(): result = ask_user for i in range(len(old)): result = result.replace(old[i], new[i]) return result ask_replace_letters() When I run the code I get: Type a sentence: BYE Do you want to replace letters? yes What letters do you want to replace? BYW This program cannot replace the letter(s): Y 8Y3 This program cannot replace the letter(s): W 8Y3 What I want: Type a sentence: BYE Do you want to replace letters? YES What letters do you want to replace? BYW This program cannot replace the letter(s): YW 8YE Is there a way to go around this? Basically I want the function to take the character the user input, check if it's in the list, change it, and state the ones that couldn't be changed. Sorry I'm still somewhat new to Python.
has answer: http://stackoverflow.com/a/68389228
possible better answer: http://stackoverflow.com/a/49340953
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49340953
accepted answer: http://stackoverflow.com/a/49340849
has comment: http://stackoverflow.com/comment/85682435
has title: How to replace characters based on user input?
type: AnsweredQuestion
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/49340849
upvote count: 1

http://stackoverflow.com/q/49354977
has body: I have the following string: my_string = '1) ServerName sn = ProtobufUtil.toServerName(request.getServer());\\n2) String msg = "Region server " + sn +\\n3) " reported a fatal error:\\\\n" + errorText;\\n4) LOG.error(msg);' I need to convert that string into a list split by symbol \\n. So, the list will be like this: my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\\\n" + errorText;', '4) LOG.error(msg);' ] I used the symbol \\n as the splitter in my code: my_list = my_string.split("\\n") However, the output for the third element in the list is not as I expected. Output: my_list = ['1) ServerName sn = ProtobufUtil.toServerName(request.getServer());', '2) String msg = "Region server " + sn +', '3) " reported a fatal error:\\', '" + errorText;', '4) LOG.error(msg);'] How should the splitter be defined in the code?
tagged with: split
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/85710343
downvote count: 0
has answer: http://stackoverflow.com/a/49356070
possible better answer: http://stackoverflow.com/a/49356070
tagged with: string
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49355030
has comment: http://stackoverflow.com/comment/85711823
tagged with: list
accepted answer: http://stackoverflow.com/a/49355030
tagged with: element
score: 1
has comment: http://stackoverflow.com/comment/85710313
tagged with: python
has title: Splitting the string using a symbol in python
favorite count: 0
has comment: http://stackoverflow.com/comment/85711093
type: Question

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/49404376
tags question: http://stackoverflow.com/q/49415023
tags question: http://stackoverflow.com/q/49402203

http://stackoverflow.com/comment/85669058
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49333249
score: 0
has text: It's likely not a problem with the function but the predictions. How man values are there, can you include them in the post?

http://stackoverflow.com/comment/132328071
has text: The problem is not adequately specified. **What should happen** if some entries with matching strings are **not** adjacent? Should they be merged, or form separate groups? There are separate approaches to each problem.
type: Comment
comment on: http://stackoverflow.com/q/49344761
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85694653
score: 0
has text: Maybe you are missing the argument when you invoke the function
type: Comment
comment on: http://stackoverflow.com/q/49347300
type: QuestionComment

http://stackoverflow.com/comment/85903753
comment on: http://stackoverflow.com/q/49435804
score: 0
has text: are all the above commands are run on docker or on your local laptop environment. Please note in order to install you need to run the commands on docker itself and docker should have prerequisites for PyQt5(like python 3 etc) and you need to install whl corresponding to your OS and platform(32/64bit)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49297830
has comment: http://stackoverflow.com/comment/85597441
has answer: http://stackoverflow.com/a/49297913
type: Question
has comment: http://stackoverflow.com/comment/85597433
has comment: http://stackoverflow.com/comment/85597471
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49297915
has title: How to tell installer (pip/pip3) to install all packages under python3.6?
has answer: http://stackoverflow.com/a/49297895
has body: I have two versions of python ( 2.7 and 3.6.4) installed on ubuntu 16.04. Now I only want to work on 3.6. I want to install few packages like pandas and psycopg2. I tried to install it with pip3 install pandas and it shows successfully installed. However, when I am trying to import from python 3.6 it is throwing me this error: ModuleNotFoundError: No module named 'pandas'. Now the question is how to tell installer (pip/pip3) to install all packages under python3.6 so that I can import the installed packages?
linked to: http://stackoverflow.com/q/30993086
score: 0
has comment: http://stackoverflow.com/comment/85618111
linked to: http://stackoverflow.com/q/34803040
answer count: 3
tagged with: pip

http://stackoverflow.com/comment/85666745
type: AnswerComment
comment on: http://stackoverflow.com/a/49332030
score: 1
has text: Glad you found it and i hope it works for you. pulp is easy to use and easily packages the (imho) best open-source MIP-solver there is, Coin-OR Cbc (if you can live with it's less-than-optimal docs; compared to GLPK and co).
type: Comment

http://stackoverflow.com/comment/85705650
type: Comment
has text: If you want to use `kafka` or `s3transfer` -- perhaps you don't want to work with asyncio code. At least mixing `kafka` calls inside an executor with regular async program gives expectedly slow result. The same is for `s3transfer`. What you need is `aiokafka` and `aiobotocore` usage.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49350346

http://stackoverflow.com/a/49366960
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49366396
type: Answer
has body: It takes long because it compiles all code with Cython - you can either disable it with --no-cython (it will work, but will be slower.), or if you have all machines with same set of libraries, then you can build driver on one of them into form of .egg file, and then install from .egg (it requires easy_install installed). This could be done with following commands python setup.py build python setup.py bdist_egg sudo easy_install &lt;path-to-egg-file&gt;

http://stackoverflow.com/q/49330402
has comment: http://stackoverflow.com/comment/85706808
tagged with: inline-formset
has title: Django nested formsets adding forms dynamically
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/85707711
upvote count: 4
type: AnsweredQuestion
has body: I'm trying to create a survey page using Django that has the functionality to add questions and choices(for each question) dynamically. I have three following model classes: Survey, Question and Choice. I did a lot of research to figure out how to go about implementing the forms and it seems nested formsets using inline_formsets is the right way to go(I used this tutorial). However, I can't figure out how to add questions and choices dynamically with nested formsets.The JavaScript library that I'm trying to use(This library) does not have an example for nested formsets and I'm not sure if it supports it. This code is what i have so far: forms.py from django.forms import BaseInlineFormSet from django.forms import HiddenInput from django.forms import inlineformset_factory from django.forms import ModelForm from .models import * class SurveyForm(ModelForm): class Meta: model = Survey fields = [ 'name', 'description', ] class BaseQuestionFormset(BaseInlineFormSet): def add_fields(self, form, index): super(BaseQuestionFormset, self).add_fields(form, index) form.nested = QuestionChoiceFormset( instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None) def is_valid(self): result = super(BaseQuestionFormset, self).is_valid() print(result) if self.is_bound: for form in self.forms: if hasattr(form, 'nested'): result = result and form.nested.is_valid() return result def save(self, commit=True): for form in self.forms: form.save(commit=commit) result = super(BaseQuestionFormset, self).save(commit=commit) for form in self.forms: if hasattr(form, 'nested'): if not self._should_delete_form(form): form.nested.save(commit=commit) return result QuestionFormset = inlineformset_factory( parent_model=Survey, model=Question, fields='__all__', formset=BaseQuestionFormset, extra=1) QuestionChoiceFormset = inlineformset_factory( parent_model=Question, model=Choice, fields='__all__', extra=1) views.py @login_required def create(request): s…
accepted answer: http://stackoverflow.com/a/49416807
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49416807
tagged with: jquery
tagged with: django-forms
tagged with: nested-forms
has comment: http://stackoverflow.com/comment/85706347
favorite count: 0
type: Question

http://stackoverflow.com/q/49381154
has answer: http://stackoverflow.com/a/49381585
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/85763259
has answer: http://stackoverflow.com/a/49382298
tagged with: python-3.x
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/49381413
has body: I want to return False only if the substring has alphabet letter(s) both before AND after it: e.g. given the target 'at' and strings = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it'] I'd like to return [True, True, True, False]. I have now: def foo(p,i): if p.findall(i): return True return False pat = re.compile(r'\bat\b') [foo(pat,i) for i in strings] which returns [True, False, False, False].
downvote count: 0
has title: Find a substring with conditions with a regex
has comment: http://stackoverflow.com/comment/85762991
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/49381660
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49381585
has answer: http://stackoverflow.com/a/49381413
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/85763008
tagged with: substring

http://stackoverflow.com/q/49429888
tagged with: deep-learning
tagged with: tensor
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Use tf.shape(tensor) as a bound for a loop
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python
has body: Using Tensorflow in Python, I want to use the shape of a placeholder for the bound of a for-loop. However, when I try to do this, I get the error: 'Tensor' object cannot be interpreted as an integer. This shape is not a constant value across the data so we cannot use a tf.constant. How can we solve this problem? Here is a part of our code: def Model(M, v_a, weights, biases, d, N): c = multilayer_perceptron((tf.slice(M, [0, 0], ([d, 1]))), v_a, weights, biases) for i in range(1, N): c = tf.concat([c, multilayer_perceptron((tf.slice(M, [0, i], [d, 1])), v_a, weights, biases)], axis=0) alpha = tf.nn.softmax(tf.reshape(c, [-1])) v_ns = tf.matmul(M, tf.reshape(alpha, [N, 1])) layer_3 = tf.add(tf.matmul(weights['W4'], v_ns), biases['b2']) v_ms = tf.nn.tanh(layer_3) layer_4 = tf.add(tf.matmul(weights['W5'], v_ms), biases['b3']) pred = tf.nn.softmax(tf.reshape(layer_4, [-1])) return pred M = tf.placeholder(tf.float32) I need N to be an integer, but it needs to be equal to the number of columns of the placeholder M, which is not constant across training examples.
has answer: http://stackoverflow.com/a/49431990

heroku
tags question: http://stackoverflow.com/q/49407056
tags question: http://stackoverflow.com/q/49298114
tags question: http://stackoverflow.com/q/49382024
tags question: http://stackoverflow.com/q/49356565
tags question: http://stackoverflow.com/q/49331054
type: Tag
tags question: http://stackoverflow.com/q/49313660
tags question: http://stackoverflow.com/q/49386295
tags question: http://stackoverflow.com/q/49376754
tags question: http://stackoverflow.com/q/49433292
tags question: http://stackoverflow.com/q/49422490
tags question: http://stackoverflow.com/q/49353830
tags question: http://stackoverflow.com/q/49302514
tag name: heroku
tags question: http://stackoverflow.com/q/49306996
tags question: http://stackoverflow.com/q/49387439
tags question: http://stackoverflow.com/q/49341093

http://stackoverflow.com/comment/85782116
has text: It removes all the commas :( not the last one
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49371949

http://stackoverflow.com/a/49367216
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49365883
has comment: http://stackoverflow.com/comment/85736230
has body: If your hosts are on different subnets, you cannot connect them without knowing their IP Addresses. They are isolated from each other, you must forward the ports to their IPs from your router configuration panel or set them up as DMZ hosts. I suppose you could setup a local DNS server and assign your hosts human-readable hostnames and resolve those IPs dynamically to jump this hurdle, but the ports must still be opened or the router firewall will not forward the traffic. And you'll need to add your local DNS server to the whichever host is initiating the connection's name server list. And.. the DNS server still needs to know what the IP of the hosts expecting connections are, so if they change, this needs to be updated somehow. For TCP: On the SAME subnet, you can use SSDP: https://pypi.python.org/pypi/ssdp/1.0.1 SSDP is a protocol of UPNP that uses UDP multicast, which essentially sends UDP packets to a special ip:port that your router will broadcast to all connected clients, such that all hosts will receive datagrams. The hosts can then send their IPs back to the server and you'll be able to create TCP connections. For UDP: I'm not sure what you want, UDP already has a facility (multicast) for sending data to any arbitrary host. As for code: Please do your own work and research, this isn't a free code writing service. To get you started, you can check out the python api code examples: https://wiki.python.org/moin/UdpCommunication#Multicasting.3F
has comment: http://stackoverflow.com/comment/85736140
has comment: http://stackoverflow.com/comment/85735470
type: Answer

http://stackoverflow.com/a/49380482
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85770251
has body: One simple way to do it is to specify a list of possible emojis. emoji_list = [";-)", ":)"] And then remove occurrences of those strings in your string. # A dictionary with your emojis or any combination of characters you want to get rid of. emoji_list = [";-)", ":)"] # Your input string string = 'ca va :) toi ;-) ?' # Split the string into a list of substrings. string_list = string.split() # Using list comprehension, create a new list that excludes the emoji_list items. clear_string = [string for string in string_list if string not in emoji_list] # ALTERNATIVE a cleaner way is to use higher-order function filter to filter out the emojis. clear_string = filter(lambda x: x not in emoji_list, string_list) # Join the list into a string again. output = " ".join(clear_string) print(output) You can make use of the list comprehension in python to create a list that excludes the substrings defined in emoji_list. Another way is to use the higher-order function filter to filter out those emojis. You are then left with a new list that excludes those substrings you defined in emoji_list and then you are simply joining the list to a string to get your desired result. Note: This is a very simple approach that can easily return a false positive (i.e a substring treated as emoji which in reality is not). These assumptions or cases are not covered by this solution.
has comment: http://stackoverflow.com/comment/85777697
type: Answer
answers question: http://stackoverflow.com/q/49380308
upvote count: 2

machine-learning
tags question: http://stackoverflow.com/q/49425056
tags question: http://stackoverflow.com/q/49391637
type: Tag
tags question: http://stackoverflow.com/q/49316297
tags question: http://stackoverflow.com/q/49429666
tags question: http://stackoverflow.com/q/49406381
tags question: http://stackoverflow.com/q/49375356
tags question: http://stackoverflow.com/q/49347226
tags question: http://stackoverflow.com/q/49374984
tags question: http://stackoverflow.com/q/49333266
tags question: http://stackoverflow.com/q/49305149
tags question: http://stackoverflow.com/q/49394652
tags question: http://stackoverflow.com/q/49355939
tags question: http://stackoverflow.com/q/49347878
tags question: http://stackoverflow.com/q/49285664
tags question: http://stackoverflow.com/q/49299761
tags question: http://stackoverflow.com/q/49411679
tags question: http://stackoverflow.com/q/49306552
tags question: http://stackoverflow.com/q/49288651
tags question: http://stackoverflow.com/q/49432583
tags question: http://stackoverflow.com/q/49402739
tags question: http://stackoverflow.com/q/49343748
tags question: http://stackoverflow.com/q/49354691
tags question: http://stackoverflow.com/q/49303232
tags question: http://stackoverflow.com/q/49419504
tags question: http://stackoverflow.com/q/49339890
tags question: http://stackoverflow.com/q/49394654
tags question: http://stackoverflow.com/q/49377483
tags question: http://stackoverflow.com/q/49307967
tags question: http://stackoverflow.com/q/49314455
tags question: http://stackoverflow.com/q/49396961
tags question: http://stackoverflow.com/q/49438167
tags question: http://stackoverflow.com/q/49285112
tags question: http://stackoverflow.com/q/49356541
tags question: http://stackoverflow.com/q/49328229
tags question: http://stackoverflow.com/q/49399847
tags question: http://stackoverflow.com/q/49404993
tags question: http://stackoverflow.com/q/49383613
tags question: http://stackoverflow.com/q/49337897
tags question: http://stackoverflow.com/q/49318813
tags question: http://stackoverflow.com/q/49369176
tags question: http://stackoverflow.com/q/49416716
tags question: http://stackoverflow.com/q/49283341
tags question: http://stackoverflow.com/q/49345578
tags question: http://stackoverflow.com/q/49390842
tags question: http://stackoverflow.com/q/49352804
tags question: http://stackoverflow.com/q/49397462
tags question: http://stackoverflow.com/q/49416912
tags question: http://stackoverflow.com/q/49368361
tags question: http://stackoverflow.com/q/49306075
tags question: http://stackoverflow.com/q/49360617
tags question: http://stackoverflow.com/q/49403678
tags question: http://stackoverflow.com/q/49293443
tags question: http://stackoverflow.com/q/49311863
tags question: http://stackoverflow.com/q/49334642
tags question: http://stackoverflow.com/q/49345671
tags question: http://stackoverflow.com/q/49403023
tags question: http://stackoverflow.com/q/49433936
tags question: http://stackoverflow.com/q/49345786
tags question: http://stackoverflow.com/q/49293015
tags question: http://stackoverflow.com/q/49346720
tags question: http://stackoverflow.com/q/49385147
tags question: http://stackoverflow.com/q/49296167
tags question: http://stackoverflow.com/q/49320188
tags question: http://stackoverflow.com/q/49433462
tags question: http://stackoverflow.com/q/49362616
tags question: http://stackoverflow.com/q/49394377
tags question: http://stackoverflow.com/q/49296099
tag name: machine-learning
tags question: http://stackoverflow.com/q/49357582
tags question: http://stackoverflow.com/q/49365837
tags question: http://stackoverflow.com/q/49436628
tags question: http://stackoverflow.com/q/49319961
tags question: http://stackoverflow.com/q/49429046
tags question: http://stackoverflow.com/q/49301185
tags question: http://stackoverflow.com/q/49372552
tags question: http://stackoverflow.com/q/49338432
tags question: http://stackoverflow.com/q/49342218
tags question: http://stackoverflow.com/q/49342820
tags question: http://stackoverflow.com/q/49431995

http://stackoverflow.com/a/49331413
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49331391
has comment: http://stackoverflow.com/comment/85664886
has body: syspath and "/tosext/help.tosext" must be joined together to form the path: hlp = open(syspath + "/tosext/help.tosext", "r") The first parameter of open is the path (a string), the second is the mode (another string), and the third is buffering (an integer). Normally, you do not want to use the third parameter.
type: Answer
accepted answer of: http://stackoverflow.com/q/49331391
downvote count: 0

http://stackoverflow.com/a/49400941
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: I found a nice answer based on pure python, unfortunately I do not find the source anymore. It first converts every char to an int, and then replaces the int with an one-hot array. It has unicity over the whole program, even over all programms if the alphabet is the same length and the same order. # Is the alphabet of all possible chars you want to convert alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" def convert_to_onehot(data): #Creates a dict, that maps to every char of alphabet an unique int based on position char_to_int = dict((c,i) for i,c in enumerate(alphabet)) encoded_data = [] #Replaces every char in data with the mapped int encoded_data.append([char_to_int[char] for char in data]) print(encoded_data) # Prints the int encoded array #This part now replaces the int by an one-hot array with size alphabet one_hot = [] for value in encoded_data: #At first, the whole array is initialized with 0 letter = [0 for _ in range(len(alphabet))] #Only at the number of the int, 1 is written letter[value] = 1 one_hot.append(letter) return one_hot print(convert_to_onehot("hello world"))
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49370940
answers question: http://stackoverflow.com/q/49370940

http://stackoverflow.com/a/49327295
score: 4
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85659642
accepted answer of: http://stackoverflow.com/q/49324572
has body: Assuming your application is running on GAE Standard: In theory there may be ways to share state between threads that run on the same instance. In Python, this could take the form of a module level variable. This might make sense for extremely specialized types of caching, but it isn't reliable or durable because instances come and go over time. It also introduces the idea of cold and warm instances, which will make performance metrics harder to interpret. There is not a way to share state between instances without using another system like Memcache or Datastore. It may seem like overkill for a small dataset, but those tools are probably what you're looking for.
answers question: http://stackoverflow.com/q/49324572
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85790705
has text: Turns out my usecase is a subcase of issue [#14451](https://github.com/tensorflow/tensorflow/issues/14451) - discussed here in https://stackoverflow.com/q/47236465/281545
type: Comment
comment on: http://stackoverflow.com/q/49358750
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86273569
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49631900
has text: I think I won't even try to port that to python. I'll use the code as-is in a small tool exe which takes the command as argument, so I can run it from my python code. Thanks. I'm going to test that soon enough.
score: 0

http://stackoverflow.com/q/49396243
type: AnsweredQuestion
score: 0
answer count: 2
has title: How to handle NoneType in any() statement?
has answer: http://stackoverflow.com/a/49396339
type: Question
accepted answer: http://stackoverflow.com/a/49396339
tagged with: arrays
tagged with: python
has body: I have an any() statement in python, and some of the elements in memo_field array are None. any(memo_field[1][0] in row[9] for memo_field in memo_fields) What is the best way to handle those NoneType elements in the array?
tagged with: any
has answer: http://stackoverflow.com/a/49396268
possible better answer: http://stackoverflow.com/a/49396268

http://stackoverflow.com/comment/85682801
has text: I don't think you will face problem with multiple processes trying to query the same database at the same time. BTW we need to know if that columns contains e-mail addresses or `int`. Sqlite is pretty fast and if you are retrieving just a column you shouldn't have resource problems. Give me a scenario example and the problem you have
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49341165
type: Comment

http://stackoverflow.com/comment/85702531
type: Comment
type: QuestionComment
has text: if its line delimited, no reason to use lookaround, just check for the delimiter (newline) or even better, use `$` and `^`
comment on: http://stackoverflow.com/q/49351273
score: 1

http://stackoverflow.com/comment/85585692
type: AnswerComment
comment on: http://stackoverflow.com/a/49291373
type: Comment
has text: it return None after executed this script
score: 0

http://stackoverflow.com/q/49371987
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85745177
favorite count: 0
type: Question
has body: I'm trying to apply what I call an override mapping to a dataframe. Essentially, I'd like the default value to be used from wkydf HistTeamNm except where my mapping table mpdf has a different value. I've used similar logic before and it worked fine. I've come up with the following: wkydf['ManHistTeam']=wkydf['HistTeamNm'] wkydf.loc[wkydf.UsrIDWkYr.isin(mpdf.UsrIDWkYr), ['ManHistTeam']]=mpdf'ManHistTeam' wkydf['InManMap']='N' wkydf.loc[wkydf.UsrIDWkYr.isin(mpdf.UsrIDWkYr),['InManMap']]='Y' So wkydf.loc[wkydf.UsrIDWkYr.isin(mpdf.UsrIDWkYr), ['ManHistTeam']]=mpdf'ManHistTeam' is currently giving my blanks but in the correct rows, so I'm fairly certain the logic identifying the row to override is working. Also, when I change the mpdf'ManHistTeam' to a static Y, I get Y where I'm expecting. I've also exported the mapping table and the strings are in the expected column. I can't figure out why the logic is returning blanks instead of the string from the mapping table.
score: 0
downvote count: 1
tagged with: python
has title: Boolean Screen Not Returning String
has comment: http://stackoverflow.com/comment/85745971
answer count: 0
linked to: http://stackoverflow.com/q/20109391

http://stackoverflow.com/a/49357236
upvote count: 1
type: Answer
has body: Yes, you can, but the concept is not called "stages" but batches and it is the most common method to train neural networks. You just need to make a generator function that loads batches of your data one at a time and use model.fit_generator to start training it.
downvote count: 0
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49354178
accepted answer of: http://stackoverflow.com/q/49354178

http://stackoverflow.com/comment/85678210
has text: You can simply use indexing as in numpy: `test_labels2[:, 0]` for example will give you the first column. Did this fix your problem?
comment on: http://stackoverflow.com/q/49304817
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49406282
has body: I am using the InterpolatedUnivariateSpline function from the scipy.interpolate library. I know that there exists a function the evaluate the derivative of the resulting spline. What I am interested in is the derivative of the log of the spline. Is there a way to calculate this directly?
accepted answer: http://stackoverflow.com/a/49416206
tagged with: python
tagged with: spline
has comment: http://stackoverflow.com/comment/85813507
has answer: http://stackoverflow.com/a/49416206
has comment: http://stackoverflow.com/comment/85849135
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42602553
has comment: http://stackoverflow.com/comment/85813744
has comment: http://stackoverflow.com/comment/85830953
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has title: Derivative of manipulated spline

http://stackoverflow.com/q/49323899
has comment: http://stackoverflow.com/comment/85649629
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: timestamp
type: Question
has comment: http://stackoverflow.com/comment/85649471
tagged with: timezone
type: UnansweredQuestion
tagged with: android
tagged with: datetime
has answer: http://stackoverflow.com/a/49324280
tagged with: python
has answer: http://stackoverflow.com/a/49324880
has title: How to get a datetime object from a timestamp using the GMT delta in python?
has body: I'm currently collecting timestamp's using an android application which for some users stored the timezone as for example "GMT+03:00" browsing online I found this is not a proper timezone and because of that when trying to build a datetime object in python using from datetime import datetime from dateutil import tz import pandas as pd filename="data.csv" data=pd.read_csv(filename) [ datetime.fromtimestamp(data['timestamp'].iloc[i], tz=tz.gettz(data['timezone'].iloc[i])) for i in range(data.shape[0]) ] does not work well. For example using that datetime object as index to create a Pandas dataframe in order to use the rolling window feature does not work. Any idea how to transform the "GMT+03:00" into a proper timezone or some way to incorporate that information to build correctly a datetime object? update: Here is a sample of data['timestamps']: [1520719558.0, 1520719558.0, 1520719558.0, 1520719558.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719562.0, 1520719562.0] and a sample of data['timezone']: ['GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00']
answer count: 2

http://stackoverflow.com/comment/85668704
has text: Hi Alvas, I have added more to perspective. you may check Edit 3 if you will. That might add more insight.
type: AnswerComment
comment on: http://stackoverflow.com/a/49296457
score: 0
type: Comment

http://stackoverflow.com/comment/96911130
has text: It's because is a character ascii and in that way shows sublime text. The original code is `code` ser.write('') `code`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/55068046
score: 0

http://stackoverflow.com/comment/85797935
type: Comment
type: QuestionComment
has text: @Jean-FrançoisFabre that worked! Thanks a lot :)
comment on: http://stackoverflow.com/q/49381574
score: 0

http://stackoverflow.com/a/49290555
accepted answer of: http://stackoverflow.com/q/49290266
has body: One way may be similar to approach in other answer: import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() data = np.random.rand(1000) N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1) for i in range(0,3): patches[i].set_facecolor('b') for i in range(3,5): patches[i].set_facecolor('r') for i in range(5, len(patches)): patches[i].set_facecolor('black') plt.show() Result:
answers question: http://stackoverflow.com/q/49290266
type: Answer
upvote count: 42
score: 41
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/91092663
comment on: http://stackoverflow.com/a/49312093
has text: I'm not using any virtual environment (now I feel stupid for not doing it). My Python version is 3.5.2. I just cloned the repo & launched the setup with python3 & everything seemed fine.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85793586
type: Comment
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/49395788
has text: You can compose any two transformations by multiplying the matrices. You should be able to figure out how to translate it to origin, rotate it, then translate it back, right? Then multiply those three together to get the rotate-in-place. (And if you don't know how to decompose your existing rotation-and-origin, that's fine too—if you translate to origin, then translate-and-rotate, then translate back, that has the same result you want.)

http://stackoverflow.com/comment/85810739
score: 0
has text: We need more information: at a *minimum*, include your data types (e.g. `int`, `str`, `float`?), whether ordering is a requirement, any output requirement (e.g. nested `dict`, `pd.DataFrame`, `dict` of `pd.Series`, etc.).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49404061

http://stackoverflow.com/a/49415517
has body: Maybe this will help you... from collections import defaultdict def query_to_dict(student_results): result = defaultdict(list) for obj in student_results: instance = inspect(obj) for key, x in instance.attrs.items(): result[key].append(x.value) return result output = query_to_dict(students)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49414667
upvote count: 1
score: 1

http://stackoverflow.com/q/49287489
accepted answer: http://stackoverflow.com/a/49287568
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49287568
type: Question
downvote count: 0
tagged with: pickle
upvote count: 1
tagged with: python
has body: This answer explains how you would unpickle multiple items in a file. However, I'm sending pickled objects across the network. If two pickled objects are sent in rapid succession, they could end up read into the same buffer. How do I replicate the behavior in the linked answer with bytes objects? Is there a well-defined terminator I can split on, or a way to "advance" the bytes object? Ex: test = pickle.dumps("hello") test += pickle.dumps("world") print(pickle.loads(test)) # Prints "hello" -- how do I get "world"?
has comment: http://stackoverflow.com/comment/85613595
has comment: http://stackoverflow.com/comment/85578720
answer count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20716812
score: 1
has title: How do I unpickle multiple pickled items in a single bytes object?

http://stackoverflow.com/a/49325042
has comment: http://stackoverflow.com/comment/85652909
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85652722
score: 2
has body: Base on you code df.merge(df.groupby(['C', 'D']).apply(lambda row: row['B'] - row['A']).sum(level=[0,1]).reset_index()) Out[292]: A B C D 0 0 2017-10-01 2017-10-11 M 2017-10 11 days 1 2017-10-02 2017-10-03 M 2017-10 11 days 2 2017-11-01 2017-11-04 B 2017-11 4 days 3 2017-11-08 2017-11-09 B 2017-11 4 days 4 2018-01-01 2018-01-03 A 2018-01 2 days
type: Answer
has comment: http://stackoverflow.com/comment/113680086
has comment: http://stackoverflow.com/comment/85652605
accepted answer of: http://stackoverflow.com/q/49324988
has comment: http://stackoverflow.com/comment/113679737
has comment: http://stackoverflow.com/comment/85652788
has comment: http://stackoverflow.com/comment/85652861
upvote count: 2
answers question: http://stackoverflow.com/q/49324988

http://stackoverflow.com/comment/85678746
comment on: http://stackoverflow.com/q/49338135
type: Comment
score: 0
type: QuestionComment
has text: For full compatibility (under Windows) you can interact directly with an Excel object via `win32com`, e.g.`excel = win32com.gencache.EnsureDispatch('Excel.Application')`

http://stackoverflow.com/q/49371847
has title: Deoptim optimizer for python
has body: I have been looking for a multi-core optimizer for Python thats equivalent to DEopt. Been messing around with https://github.com/hyperopt/hyperopt but mutli-core support is very lacking. Does anyone know of any good alternatives that support using multiple cores?
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49595807
tagged with: optimization
score: 2
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/56762645
downvote count: 0

http://stackoverflow.com/comment/85716881
has text: So, do you want to check whether the text consists only alphabets and numbers?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49358461
score: 0

http://stackoverflow.com/comment/125340833
type: QuestionComment
comment on: http://stackoverflow.com/q/49380572
score: 0
has text: @doak Looking at this years after my original comment, I think I was looking at the case of changing a pathname from `/a/b/c/file.ext` to `/a/b/c/file_foo.ext`. The `with_suffix` method would seem to fit the bill perfectly to strip off the extension and add a new ending to the name, but for some reason they chose to artificially limit the method and throw an error instead.
type: Comment

http://stackoverflow.com/comment/85779014
type: QuestionComment
has text: What does `arabic_reshaper` do, and what happens when you omit that line, or just print the data before and after that operation? There might also be some hidden right-to-left mark in the text that's ignored by either python's `print`, or that `arabic_reshaper`, or the word-cloud generator. Have you tried reversing the strings "manually" using `s[::-1]`?
type: Comment
comment on: http://stackoverflow.com/q/49384111
score: 0

http://stackoverflow.com/comment/85875216
comment on: http://stackoverflow.com/a/49431983
has text: In the case where the user does not give prompt. for example if we eliminate the last line of prompts. The result will be falsified. I'm going to have 7 lines instead of 10 lines
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49369472
has body: I am trying to implement this paper for sound classification: https://raw.githubusercontent.com/karoldvl/paper-2015-esc-convnet/master/Poster/MLSP2015-poster-page-1.gif It is mentioned in the paper that 0.001 L2 weight decay was added for each layer. But, I can't figure out how to do so in Tensorflow. I found a similar question (How to define weight decay for individual layers in TensorFlow?) that uses tf.nn.l2_loss, but it is not clear how can I use this approach for my network. Also, it does not have the parameter of 0.001 in tf.nn.l2_loss. My Network: net = tf.layers.conv2d(inputs=x, filters=80, kernel_size=[57, 6], strides=[1, 1], padding="same", activation=tf.nn.relu) print(net) net = tf.layers.max_pooling2d(inputs=net, pool_size=[4, 3], strides=[1, 3]) print(net) net = tf.layers.dropout(inputs=net, rate=keep_prob) print(net) net = tf.layers.conv2d(inputs=net, filters=80, kernel_size=[1, 3], strides=[1, 1], padding="same", activation=tf.nn.relu) print(net) net = tf.layers.max_pooling2d(inputs=net, pool_size=[1, 3], strides=[1, 3]) print(net) net = tf.layers.flatten(net) print(net) # Dense Layer net = tf.layers.dense(inputs=net, units=5000, activation=tf.nn.relu) print(net) net = tf.layers.dropout(inputs=net, rate=keep_prob) print(net) net = tf.layers.dense(inputs=net, units=5000, activation=tf.nn.relu) print(net) net = tf.layers.dropout(inputs=net, rate=keep_prob) print(net) logits = tf.layers.dense(inputs=net, units=num_classes) print("logits: ", logits) Output: Tensor("Model/conv2d/Relu:0", shape=(?, 530, 129, 80), dtype=float32) Tensor("Model/max_pooling2d/MaxPool:0", shape=(?, 527, 43, 80), dtype=float32) Tensor("Model/dropout/Identity:0", shape=(?, 527, 43, 80), dtype=float32) Tensor("Model/conv2d_2/Relu:0", shape=(?, 527, 43, 80), dtype=float32) Tensor("Model/max_pooling2d_2/MaxPool:0", shape=(?, 527, 14, 80), dtype=float32) Tensor("Model/flatten/Reshape:0", shape=(?, 590240), dtype=float32) Tensor("Model/dense/Relu:0", shape=(?, 5000), dtype=float32) Ten…
upvote count: 1
tagged with: tensorflow
favorite count: 0
has title: How to add 0.001 L2 weight decay for each layer in CNN?
type: Question
has answer: http://stackoverflow.com/a/49369610
linked to: http://stackoverflow.com/q/36570904
tagged with: neural-network
tagged with: python
accepted answer: http://stackoverflow.com/a/49369610
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: deep-learning
score: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49390825
accepted answer: http://stackoverflow.com/a/49404748
tagged with: python
has title: Using mongoengine with multiprocessing - how do you close mongoengine connections?
score: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49404748
has body: No matter what I try I keep hitting the "MongoClient opened before fork" warning regarding not forking active mongo connections when trying to use multiprocessing on a mongoengine db. The standard mongo advice seems to be to only connect to the db from within the child processes but I think what I'm doing should be functionally equivalent because I'm closing the database prior to using multiprocessing however I still hit the problem. Related questions either without a minimal example or with inapplicable solutions are here, here, and specifically for the case of flask/celery and here Minimal example to reproduce the problem: from mongoengine import connect, Document, StringField, ListField, ReferenceField from pathos.multiprocessing import ProcessingPool class Base(Document): key = StringField(primary_key=True) name = StringField() parent = ReferenceField('Parent', required=True) class Parent(Document): key = StringField(primary_key=True) name = StringField() bases = ListField(ReferenceField('Base')) def remove_base(key): db = connect('mydb') mongo_b = Base.objects().get(key=key) mongo_b.parent.update(pull__bases=mongo_b) mongo_b.delete() ### setup db = connect('mydb', connect=False) Base(key='b1', name='test', parent='p1').save() Base(key='b2', name='test', parent='p1').save() Base(key='b3', name='test2', parent='p1').save() p=Parent(key='p1', name='parent').save() p.update(add_to_set__bases='b1') p.update(add_to_set__bases='b2') p.update(add_to_set__bases='b3') ### find objects we want to delete my_base_objects = Base.objects(name='test') keys = [b.key for b in my_base_objects] del my_base_objects # close db to avoid problems?! db.close() del db # parallel map removing base objects and references from the db # warning generated here pp = ProcessingPool(2) pp.map(remove_base, keys)
linked to: http://stackoverflow.com/q/41905472
tagged with: mongoengine
linked to: http://stackoverflow.com/q/45530741
favorite count: 0
tagged with: multiprocessing
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/58030157
possible better answer: http://stackoverflow.com/a/58030157
tagged with: mongodb
linked to: http://stackoverflow.com/q/44133435

http://stackoverflow.com/comment/85608684
has text: Can you minimise the example to only the attributes relevant to the question? We shouldn't need to wade through dozens of unrelated things to understand your issue.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49303319

http://stackoverflow.com/q/49428469
has comment: http://stackoverflow.com/comment/85860574
has comment: http://stackoverflow.com/comment/85859039
has answer: http://stackoverflow.com/a/52292939
has answer: http://stackoverflow.com/a/62509894
type: Question
answer count: 4
linked to: http://stackoverflow.com/q/51397109
upvote count: 23
has title: Pruning Decision Trees
has comment: http://stackoverflow.com/comment/85858333
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85858293
has comment: http://stackoverflow.com/comment/85859299
accepted answer: http://stackoverflow.com/a/49496027
possible better answer: http://stackoverflow.com/a/49428780
has comment: http://stackoverflow.com/comment/85862906
has comment: http://stackoverflow.com/comment/85871592
has comment: http://stackoverflow.com/comment/85859086
downvote count: 0
has answer: http://stackoverflow.com/a/49496027
has body: Below is a snippet of the decision tree as it is pretty huge. How to make the tree stop growing when the lowest value in a node is under 5. Here is the code to produce the decision tree. On SciKit - Decission Tree we can see the only way to do so is by min_impurity_decrease but I am not sure how it specifically works. import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, shuffle=False) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) y_train = df['Class'] X_train = df.drop('Class',axis = 1) dt = DecisionTreeClassifier( random_state=42) dt.fit(X_train, y_train) from IPython.display import display, Image import pydotplus from sklearn import tree from sklearn.tree import _tree from sklearn import tree import collections import drawtree import os os.environ["PATH"] += os.pathsep + 'C:\\Anaconda3\\Library\\bin\\graphviz' dot_data = tree.export_graphviz(dt, out_file = 'thisIsTheImagetree.dot', feature_names=X_train.columns, filled = True , rounded = True , special_characters = True) graph = pydotplus.graph_from_dot_file('thisIsTheImagetree.dot') thisIsTheImage = Image(graph.create_png()) display(thisIsTheImage) #print(dt.tree_.feature) from subprocess import check_call check_call(['dot','-Tpng','thisIsTheImagetree.dot','-o','thisIsTheImagetree.png']) Update I think min_impurity_decrease can in a way help reach the goal. As tweaking min_impurity_decrease does actually prune the tree. Can anyone kindly explain min_impurity_decrease. I am trying to understand the equation in scikit learn but I am not sure what is the value of right_impurity and left_impurity. N = 256 N_t = 256 impurity = ?? N_t_R = 242 N_t_L = 14 right_…
has answer: http://stackoverflow.com/a/49428780
score: 23
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85858964
favorite count: 0
has comment: http://stackoverflow.com/comment/85860749
tagged with: python

http://stackoverflow.com/q/49436833
downvote count: 0
has answer: http://stackoverflow.com/a/49442363
has answer: http://stackoverflow.com/a/49437018
tagged with: django
has comment: http://stackoverflow.com/comment/112081050
favorite count: 0
has answer: http://stackoverflow.com/a/62825410
has comment: http://stackoverflow.com/comment/126862554
answer count: 3
has title: Difference between @cached_property and @lru_cache decorator
tagged with: python
upvote count: 26
has comment: http://stackoverflow.com/comment/101641771
score: 26
type: Question
type: UnansweredQuestion
has body: I am new to Django. Would be really helpful if someone can tell the difference between @cached_property and @lru_cache decorator in Django. Also when should I use which decorator in Django. Use cases would be really helpful. Thanks.

http://stackoverflow.com/comment/85878563
has text: See: [Use of “global” keyword in Python](https://stackoverflow.com/questions/4693120).
type: Comment
comment on: http://stackoverflow.com/q/49433979
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85624227
type: QuestionComment
has text: Perhaps reading the [mcve] page would help you understand what to post.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49311182

http://stackoverflow.com/comment/85679825
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49324752
has text: I was reviewing each answer as when using my actual data, jpp's answer results in 1600 results whereas IMCoins gives 1800 though I am yet to test with your improvements.

http://stackoverflow.com/comment/85873877
has text: You need to start you regex with `r'...'`, I assume. But a full error traceback would help here.
comment on: http://stackoverflow.com/q/49435907
score: 0
type: Comment
type: QuestionComment

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/49318813
tags question: http://stackoverflow.com/q/49323857
tag name: decision-tree
tags question: http://stackoverflow.com/q/49289187

http://stackoverflow.com/q/49334585
has answer: http://stackoverflow.com/a/49343596
has body: My question is pretty straight, Can I pass multiple types values pair while doing conditional formatting like: worksheet.conditional_format(first row, first col, last row, last col, {"type": ["no_blanks", "blanks"], "format": abc}) while doing this I'm getting the below error: TypeError: unhashable type: 'list'
has title: xlsxwriter conditional format
answer count: 1
accepted answer: http://stackoverflow.com/a/49343596
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85671446
has comment: http://stackoverflow.com/comment/85671533
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/85671431
downvote count: 3
has comment: http://stackoverflow.com/comment/85671636
has comment: http://stackoverflow.com/comment/85671595
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/85672928
tagged with: python

http://stackoverflow.com/q/49367706
has body: In this example, I show two different methods for creating a list of strings using Cython. One uses an array of char pointers (and the strcpy C function) and the other by simply appending elements to a list. I then pass each of these lists into the set function and see that performance is drastically different. Question - What can I do to create the list using character pointers to have equal performance? A simple function to create lists in Cython from libc.string cimport strcpy def make_lists(): cdef: char c_list[100000][3] Py_ssize_t i list py_list = [] for i in range(100000): strcpy(c_list[i], 'AB') c_list[i][2] = b'\0' py_list.append(b'AB') return c_list, py_list Here, c_list is just an array of 3-length characters. Cython will return this object as a Python list. py_list is just a normal Python list. We are filling both lists with just a single sequence of bytes, 'AB'. Create the lists c_list, py_list = make_lists() Print out some of the contents &gt;&gt;&gt; c_list[:10] [b'AB', b'AB', b'AB', b'AB', b'AB', b'AB', b'AB', b'AB', b'AB', b'AB'] Show both lists are equal &gt;&gt;&gt; c_list == py_list True Time operations - this is insane to me! 3x difference %timeit set(c_list) 2.85 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit set(py_list) 1.02 ms ± 26 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Unicode and pure python Interestingly, the performance difference vanishes if I decode each value to unicode, though it is slower than the original set(py_list). If I create a unicode list in pure Python then I am back to the original performance. c_list_unicode = [v.decode() for v in c_list] py_list_unicode = [v.decode() for v in py_list] py_list_py = ['AB' for _ in range(len(py_list))] %timeit set(c_list_unicode) 1.63 ms ± 56.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit set(py_list_unicode) 1.7 ms ± 35.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit set(py_list_py) 987 µs ± 45.4 µs per …
tagged with: python
type: UnansweredQuestion
tagged with: cython
has comment: http://stackoverflow.com/comment/85737314
has title: Taking a Set of a List created using C in Cython is much slower than pure Python - Why?
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85737903
downvote count: 0
has comment: http://stackoverflow.com/comment/85737576
has comment: http://stackoverflow.com/comment/85741289
has comment: http://stackoverflow.com/comment/85741193
has answer: http://stackoverflow.com/a/49370266
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49387275
downvote count: 0
has comment: http://stackoverflow.com/comment/85775825
has comment: http://stackoverflow.com/comment/85775790
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49387205
has body: Not sure about asfreq but reindex works wonderfully: df.set_index('date').reindex( pd.date_range( df.date.min(), df.date.max() + pd.Timedelta('1H'), freq='15T', closed='left' ), method='ffill' ) num 2018-01-01 00:00:00 5 2018-01-01 00:15:00 5 2018-01-01 00:30:00 5 2018-01-01 00:45:00 5 2018-01-01 01:00:00 5 2018-01-01 01:15:00 5 2018-01-01 01:30:00 5 2018-01-01 01:45:00 5
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49387205
type: AcceptedAnswer

http://stackoverflow.com/q/49354159
has comment: http://stackoverflow.com/comment/85708972
score: 0
has comment: http://stackoverflow.com/comment/85708684
has comment: http://stackoverflow.com/comment/85708760
tagged with: python
has comment: http://stackoverflow.com/comment/85719474
has comment: http://stackoverflow.com/comment/85727308
has comment: http://stackoverflow.com/comment/85708806
has comment: http://stackoverflow.com/comment/85709385
tagged with: http://stackoverflow.com/tag/zip
answer count: 0
has comment: http://stackoverflow.com/comment/85708782
has title: Python unzip a file larger than memory - OSError: [Errno 28] No space left on device
type: UnansweredQuestion
has body: I'm trying to unzip a 8gb csv file with a machine 8gb RAM. This is my implementation, using python 3.6: def extract_to(zippath, dest): with zipfile.ZipFile(zippath, mode='r') as z: for member in z.namelist(): filename = Path(member).basename() # skip directories if not filename: continue source = z.open(member) target = open(dest / filename, "wb") with source, target: shutil.copyfileobj(source, target) Unfortunately, it produces the following error: Traceback (most recent call last): File "download_data.py", line 31, in extract_to shutil.copyfileobj(source, target) File "/home/user/anaconda3/lib/python3.6/shutil.py", line 82, in copyfileobj fdst.write(buf) OSError: [Errno 28] No space left on device During handling of the above exception, another exception occurred: Traceback (most recent call last): File "download_data.py", line 56, in &lt;module&gt; main() File "download_data.py", line 49, in main download_and_extract_zip(train, RAW_DATA_DIR) File "download_data.py", line 37, in download_and_extract_zip extract_to(tmppath, dest) File "download_data.py", line 31, in extract_to shutil.copyfileobj(source, target) OSError: [Errno 28] No space left on device How can I handle this situation? Thanks.
linked to: http://stackoverflow.com/q/6998083
type: Question
has comment: http://stackoverflow.com/comment/85709287
has comment: http://stackoverflow.com/comment/85708658
has comment: http://stackoverflow.com/comment/120396195

http://stackoverflow.com/q/49311983
tagged with: module
has title: python module is not found after successfully installed using $ pip3 install --user
tagged with: bash
has body: I tried to install Selenium on my mac using pip3 install selenium, but it created an error of "Permission denied". So I tried pip3 install --user selenium, and it did install perfectly. However, the paths are probably different as my PyCharm interpreter can't find the Selenium module. $ pip3 install selenium Requirement already satisfied: selenium in ./Library/Python/3.6/lib/python/site-packages The problem is, the path doesn't even exist in my mac, I can only find /Library/Python/2.7/. Thus, I cannot just drag the module into the correct site-package. The correct path should be /usr/local/lib/python3.6/site-packages/ How do I change the order of the path? And should I change it and reinstall selenium again? Thanks.
tagged with: installation
score: 0
answer count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/85625969
has comment: http://stackoverflow.com/comment/85625763
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/49311592
score: 0
tagged with: apache-spark
has body: I am new to spark. I am trying to read a file from my master instance but I am getting this error. After research I found out either you need to load data to hdfs or copy across clusters. I am unable to find the commands for doing either of these. --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) in () ----> 1 ncols = rdd.first().features.size # number of columns (no class) of the dataset /home/ec2-user/spark/python/pyspark/rdd.pyc in first(self) 1359 ValueError: RDD is empty 1360 """ -> 1361 rs = self.take(1) 1362 if rs: 1363 return rs[0] /home/ec2-user/spark/python/pyspark/rdd.pyc in take(self, num) 1311 """ 1312 items = [] -> 1313 totalParts = self.getNumPartitions() 1314 partsScanned = 0 1315 /home/ec2-user/spark/python/pyspark/rdd.pyc in getNumPartitions(self) 2438 2439 def getNumPartitions(self): -> 2440 return self._prev_jrdd.partitions().size() 2441 2442 @property /home/ec2-user/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in call(self, *args) 1131 answer = self.gateway_client.send_command(command) 1132 return_value = get_return_value( -> 1133 answer, self.gateway_client, self.target_id, self.name) 1134 1135 for temp_arg in temp_args: /home/ec2-user/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() /home/ec2-user/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 317 raise Py4JJavaError( 318 "An error occurred while calling {0}{1}{2}.\n". --> 319 format(target_id, ".", name), value) 320 else: 321 raise Py4JError( Py4JJavaError: An error occurred while calling o122.partitions. : org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/ec2-user/PR_DATA_35.csv at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.jav…
has title: How to add your files across cluster on pyspark AWS
has answer: http://stackoverflow.com/a/49311725
type: Question
type: UnansweredQuestion
tagged with: pyspark
tagged with: amazon-ec2
answer count: 1
tagged with: python

filter
tags question: http://stackoverflow.com/q/49300902
tags question: http://stackoverflow.com/q/49372995
type: Tag
tags question: http://stackoverflow.com/q/49291740
tags question: http://stackoverflow.com/q/49340657
tag name: filter
tags question: http://stackoverflow.com/q/49384756
tags question: http://stackoverflow.com/q/49305060

http://stackoverflow.com/comment/85704553
comment on: http://stackoverflow.com/q/49352209
type: QuestionComment
has text: Selenium may help.
score: 0
type: Comment

http://stackoverflow.com/a/49371681
upvote count: 1
answers question: http://stackoverflow.com/q/49358306
has comment: http://stackoverflow.com/comment/85744522
has comment: http://stackoverflow.com/comment/85789130
has comment: http://stackoverflow.com/comment/85834841
type: Answer
has comment: http://stackoverflow.com/comment/85789210
has comment: http://stackoverflow.com/comment/85790744
has comment: http://stackoverflow.com/comment/85790456
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49358306
downvote count: 0
has comment: http://stackoverflow.com/comment/85789437
has body: It's not deterministic because you are creating the assign operations with no control dependencies, so they execute in any order. To execute the assignments in the way you want their ops need to have control dependencies when they're created. Something like a = tf.get_variable('a', initializer=tf.constant(0.0)) with tf.control_dependencies([tf.assign(a, a + 2)]): with tf.control_dependencies([tf.assign(a, a * 2)]): with tf.control_dependencies([tf.assign(a, a * 2)]): op = tf.Print(a, [a]) What your code is doing is building up a set of two control dependencies and adding those dependencies to the tf.Print op.
has comment: http://stackoverflow.com/comment/85788769

http://stackoverflow.com/comment/85820707
type: AnswerComment
has text: downgrading cryptography to version 2.1.4 worked for me.
comment on: http://stackoverflow.com/a/49395069
score: 1
type: Comment

http://stackoverflow.com/a/49372104
answers question: http://stackoverflow.com/q/49371868
has body: Using pandas: import pandas as pd df = pd.read_csv('file.csv',sep=',') # sep can be \s+ if multiple spaces jsonstr = df.set_index('Key')['Value'].to_dict() print(jsonstr) Prints {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85682219
score: 0
has text: This is exactly what I needed! Are there any other ways to solve the problem?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49341013

http://stackoverflow.com/a/49337898
answers question: http://stackoverflow.com/q/49337680
score: 0
has comment: http://stackoverflow.com/comment/85696596
has body: here is a corrected version of your chatbot: import time import random guess = input('guess how old I am: ') random_guess = random.randint(1,1000) time.sleep(0.4) print ('nope, I\'m {} actually'.format(random_guess)) time.sleep(0.88) if random_guess &lt;= guess: print('(so rude...)') else: print('aw thanks') I'm just going to note down the things that were wrong and some good practices so that you can follow it since you are learning python (I just learnt it as well): In the if statement you were comparing randint &lt;= guess which is not possible because randint is not saved as variable anywhere. The 1st time you used random.randint(1, 1000) it was statically added only to be used in the print statement. So what I did here is save the random.randint(1,1000) (as you can see randint is a method inside the random module of python) into a variable called random_guess for comparison. It returns a random integer as stated in random.randint. Coming to the print statement since your random_guess will be of type int, using formatted string will be a nice and pretty option. Always use import statement at the top of the file so that it'll be a one stop place for altering imports. Take a look at this input() method as well, I have passed in a string which automatically prints out the string passed instead of a separate print statement I also removed the for loop since it was looping once anyways (I know you need to call it many times, anywho..) Edit: Oh, and you missed a colon in the if statement! I hope this cleared your doubts.
type: Answer

http://stackoverflow.com/q/49422329
score: 1
upvote count: 1
answer count: 1
has title: Real average on all values of a dataframe using rolling with pandas
favorite count: 0
type: Question
has body: If I have a df like this: a001 a002 1 1 NaN 7 NaN NaN NaN 3 NaN NaN 2 2 NaN 6 And if I want to make the calculation of the mean on window of 2 rows, I can use this: df['rolling_mean'] = df.mean(axis=1).rolling(window=2, min_periods=1).mean() which returns: a001 a002 rolling_mean 0 1.0 1.0 1.0 1 NaN 7.0 4.0 2 NaN NaN 7.0 3 NaN 3.0 3.0 4 NaN NaN 3.0 5 2.0 2.0 2.0 6 NaN 6.0 4.0 That is an average on a window of 2 rows, using the average of the elements of the single rows. So for example the rolling_mean in row1 (4) is an average between the average of the row0 (1+1)/2 = 1 and the value of row1 (7): (1+7)/2 = 4 If I want instead an average of these 3 values in the first 2 rows I should have as result: (1+1+7)/3 = 3. To obtain it I've used this: df2 = df.copy() df['sum'] = df2.sum(axis=1).rolling(window=1, min_periods=1).mean() df['count'] = df2.count(axis=1).rolling(window=1, min_periods=1).mean() df['last_2'] = df['sum'].rolling(window=2, min_periods=1).sum() / df['count'].rolling(window=2, min_periods=1).sum() That returns my desired output: a001 a002 sum count last_2 0 1.0 1.0 2.0 2.0 1.000000 1 NaN 7.0 7.0 1.0 3.000000 2 NaN NaN NaN 0.0 7.000000 3 NaN 3.0 3.0 1.0 3.000000 4 NaN NaN NaN 0.0 3.000000 5 2.0 2.0 4.0 2.0 2.000000 6 NaN 6.0 6.0 1.0 3.333333 My question is: is there a more elegant and pythonic way to do this? Thanks
has answer: http://stackoverflow.com/a/49422798
accepted answer: http://stackoverflow.com/a/49422798
tagged with: rolling-computation
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/120834650
comment on: http://stackoverflow.com/q/49348999
has text: @thatotherguy thank you for the information you have given, I will try to read that first
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49379847
answer count: 0
has comment: http://stackoverflow.com/comment/85760366
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35324893
tagged with: python
has title: Time optimization, how to replace round
has comment: http://stackoverflow.com/comment/85760297
has comment: http://stackoverflow.com/comment/85776735
score: 0
tagged with: performance
has comment: http://stackoverflow.com/comment/85776575
tagged with: rounding
has comment: http://stackoverflow.com/comment/85776828
has comment: http://stackoverflow.com/comment/85760517
has comment: http://stackoverflow.com/comment/85761900
has comment: http://stackoverflow.com/comment/85760341
linked to: http://stackoverflow.com/q/2242593
has comment: http://stackoverflow.com/comment/85760404
has comment: http://stackoverflow.com/comment/85760522
has body: After making a profiling of my program, I noticed that the round() function is called slightly too much. ncalls tottime percall cumtime percall filename:lineno(function) 12615015 69.616 0.000 69.616 0.000 {built-in method builtins.round} Basically, my program is doing too many iterations, and I'm using the round() method a lot because I have float numbers like 0.3 that comes out often. Moreover, python doesn't output exactly 0.3 but rather 0.29999...9997 (coding problem of float numbers). However, I need quite often to use if / else statements with comparison, and it took me a while to find out that the wrong output of my program came from these approximation errors, and thus the decision making was wrong because python wasn't in the right if / elif / else. Question is, how can I replace this round() to avoid both the precision problem and the time-consuming rounding? Thanks! EDIT in regards to the tolerance comment: I don't get the hang of how to do it with a tolerance instead of a round(). Partial code: d = round(abs(number_1 - number_2), 3) if number_1 &lt;= number_2 and d &lt; 0.3: do_this() continue My problem is when d is suppose to equal 0.3 because I will sometimes get 0.2999...99997 and sometimes 0.30000...0000005 (for instance). I don't see how to implement the tolerance, 0.3-d &lt; tolerance is good if I would like to check for equality, but not for inferior. Any suggestion?
type: Question
linked to: http://stackoverflow.com/q/49380594
has comment: http://stackoverflow.com/comment/85769603

http://stackoverflow.com/q/49435026
has body: I have a pandas dataframe like this **First_name Last_name Policy_number** David Gilbert IOTA123455 Fredrick Manuel IOTA367522 Donald Trump IOTA337823 Cathy Jackso IOTA892352 And I have a variable like this in my python program: some_value = "Trump" The "some_value" can take any value from any column from the above pandas dataframe. My query has to find in which column that some_value is, and return the record. Say for ex, if some_value = "Trump", my output should be: **First_name Last_name Policy_number** Donald Trump IOTA337823 Or if some_value = "IOTA123455", my output should be: **First_name Last_name Policy_number** David Gilbert IOTA123455 To achieve this, i have used the below code: df.loc[(df['First_Name'].isin(some_value)) | df['Last_Name'].isin(some_values)] | df['Policy_Number'].isin(some_values)] However i got the error as: TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str] Is there any other way to solve this problem? Please help out.
type: Question
has title: Extracting a record from pandas dataframe based on multiple conditions
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/19960077
tagged with: python
has comment: http://stackoverflow.com/comment/85871906
has comment: http://stackoverflow.com/comment/85872188
tagged with: pandas
answer count: 0
score: 0
linked to: http://stackoverflow.com/q/19960077

http://stackoverflow.com/a/49315336
answers question: http://stackoverflow.com/q/49315286
type: Answer
has body: You need &amp; for bitwise AND, but better is use between: df1 = df[(df.reports &gt;= 10) &amp; (df.reports &lt;= 31)] Or: df1 = df[df.reports.between(10,31)] print (df1) month of entry name reports 0 20171002 Jason 14 1 20171206 Molly 24 2 20171208 Tina 31 3 20171018 Jake 22 8 20171115 David 14 9 20171030 Jack 10 Detail: print ((df.reports &gt;= 10) &amp; (df.reports &lt;= 31)) 0 True 1 True 2 True 3 True 4 False 5 False 6 False 7 False 8 True 9 True 10 False Name: reports, dtype: bool
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49315286

http://stackoverflow.com/q/49320312
upvote count: 1
has comment: http://stackoverflow.com/comment/85643995
has answer: http://stackoverflow.com/a/49320378
has answer: http://stackoverflow.com/a/49321881
has comment: http://stackoverflow.com/comment/85641490
possible better answer: http://stackoverflow.com/a/49320514
favorite count: 0
type: Question
has title: Check if a dict key is in a list (tuple) of dict
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49320514
tagged with: python
tagged with: dictionary
has body: I'm using the following example to check if an item is in a list: var = 'a' var_list = ('a','b','c') if var in var_list: do_something() But in my case, what I have is a dictionary and a list of dictionaries: var = {'name': 'John', 'age': 35, 'city': 'Orlando'} var_list = ( {'name': 'John', 'age': 36, 'city': 'Orlando'} , \ {'name': 'Alex', 'age': 22, 'city': 'New York'} , \ {'name': 'Celes', 'age': 24, 'city': 'Vector'} ) if var['name'] in var_list: do_something() I need to only check the key 'name' in the comparasion, otherwise if I do var in var_list the key age will be different and will result in not getting inside the if condition. Is it possible to compare only the name key? Of course, I can iterate and check item by item, but if there is a function or something that will reduce the execution time, it will be great.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85646428
answer count: 3
score: 1
accepted answer: http://stackoverflow.com/a/49320378
downvote count: 0

http://stackoverflow.com/comment/85733571
score: 0
comment on: http://stackoverflow.com/a/49366265
type: Comment
type: AnswerComment
has text: If i try your second idea i get the following errror `AttributeError: 'int' object has no attribute 'upper'` which points to `if(sheet.cell(row+1,1).value is None`

http://stackoverflow.com/comment/85728603
has text: For starters, what package exactly are you using? https://pypi.python.org/pypi/rpm…? Probably not.
comment on: http://stackoverflow.com/q/49363997
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85688222
type: AnswerComment
comment on: http://stackoverflow.com/a/49343969
score: 0
has text: Thank you so much this has been very helpful. The part about shortening the length explained a lot.
type: Comment

http://stackoverflow.com/comment/85576826
type: Comment
type: QuestionComment
has text: for the first example, I cannot reproduce the issue (and I'm relieved). I get `[[3, 2, 'a'], [2, 3, 'b'], [2, 1, 'c']]`. `choice` returns a different list each time. Can you create a shorter [mcve] with expected output and real output?
score: 0
comment on: http://stackoverflow.com/q/49286723

http://stackoverflow.com/a/49389137
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49389054
type: Answer
has comment: http://stackoverflow.com/comment/85779776
has body: This will do the job: len([x for x in list_of_dict if x["rel_item"] == None])
downvote count: 0

http://stackoverflow.com/q/49293729
has comment: http://stackoverflow.com/comment/85713897
downvote count: 0
tagged with: flask
favorite count: 0
type: Question
has title: shadowd.flask_connector connector throwing 500 Internal server
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85713565
tagged with: python
has body: I'm trying to connect Shadowd (Shadow Daemon) WAF (Web Application Firewall) with Flask connector from this Documentation Even the normal "Hello world" program is throwing Internal server error. while I'm using the Flask Connector. MY CODE from flask import * from shadowd.flask_connector import InputFlask, OutputFlask, Connector app = Flask(__name__) @app.before_request def before_req(): input = InputFlask(request) output = OutputFlask() Connector().start(input, output) @app.route('/', methods=['GET','POST']) def index(): return " Working " if __name__ == '__main__': app.run() The above code throws Internal Server Error Traceback * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) [2018-03-15 12:33:36,668] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1610, in full_dispatch_request rv = self.preprocess_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1831, in preprocess_request rv = func() File "index.py", line 11, in before_req Connector().start(input, output) File "/usr/local/lib/python2.7/dist-packages/shadowd/connector.py", line 285, in start if config.get('debug'): File "/usr/local/lib/python2.7/dist-packages/shadowd/connector.py", line 55, in get return self.config.get(self.section, key) File "/usr/lib/python2.7/ConfigParser.py", line 607, in get raise NoSectionError(section) NoSectionError: No section: 'shadowd_python' 127.0.0.1 - - [15/Mar/2018 12:33:36] "GET / HTTP/1.1" 500 - However the If I remove the Flask Connector part the application works good. I don't fi…
tagged with: web-application-firewall
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85713867

message-queue
type: Tag
tags question: http://stackoverflow.com/q/49321939
tag name: message-queue

http://stackoverflow.com/a/49416786
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85844631
has comment: http://stackoverflow.com/comment/85835360
has comment: http://stackoverflow.com/comment/85841333
upvote count: 6
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49416698
downvote count: 0
answers question: http://stackoverflow.com/q/49416698
has body: Instead of explicitly assigning 'MyClass' I would like to use some construct to get the class name. You can use a class decorator combined with the __name__ attribute of class objects to accomplish this: def add_tag(cls): cls.ClassTag = cls.__name__ return cls @add_tag class Foo(object): pass print(Foo.ClassTag) # Foo In addition to the above, here are some side notes: As can be seen from the above example, classes are defined using the class keyword, not the def keyword. The def keyword is for defining functions. I recommend walking through the tutorial provided by Python, to get a grasp of Python basics. If you're not working on legacy code, or code that requires a Python 2 library, I highly recommend upgrading to Python 3. Along with the fact that the Python Foundation will stop supporting Python in 2020, Python 3 also fixes many quirks that Python 2 had, as well as provides new, useful features. If you're looking for more info on how to transition from Python 2 to 3, a good place to start would be here.

http://stackoverflow.com/comment/85602961
type: AnswerComment
has text: Thanks. Does the `tf.estimator` fully shield the low api. If so, I can understant the reason why it can only work in with the `tf.Iterator.make_one_shot_iterator()`
score: 0
comment on: http://stackoverflow.com/a/49295627
type: Comment

http://stackoverflow.com/comment/85894937
comment on: http://stackoverflow.com/a/49426118
has text: I converted dataset file from xls to csv and now it gives me unique values properly.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49383723
score: 1
has body: I am trying to implement a similar model to word2vec in tensorflow using the latest estimator API. The problem I am running into is when I try to evaluate the model. The model itself should be the basis for a recommender system. Now the evaluation metric I would like to use is the Hitrate metric, as follows: For each input compute the k neighbourhood. Determine if the expected label is in the k neighbourhood, if so it is a successful recommendation. Now I have setup the model like this: # Map Embeddings Ids to One Hot Tensors ref_embedding_ids = tf.feature_column.categorical_column_with_identity( key='Reference', num_buckets=params['dict_size'], default_value=0 ) # Map One Hot Tensors to Dense Embeddings ref_embeddings = tf.feature_column.embedding_column( ref_embedding_ids, dimension=params['embedding_size'] ) # Actually create the input to the model input_layer = tf.feature_column.input_layer(features, feature_columns=[ref_embeddings]) As it is done in the estimator API tutorial. Now as I understand this piece of code, the input_layer already only contains the embeddings that are referenced in the feature dictionary with the key Reference. Which is awesome since we do not need to keep all the embeddings in memory. But now if I want to compute the neighbourhood in the evaluation mode, I need to access the embedding vector of all the possible inputs to compute the similarities. However I do not have any reference to those, since the pipeline is setup that only the necessary parts are loaded. I already tried finding out the name of the variable that holds the embeddings and explicitly loading that with tf.get_variable but that did not work either. So my question is how would I compute the neighbourhood for a given embedding id? Also after being able to compute the neighbourhood I would need to use a metric to keep computing the metric for the whole evaluation set, since the function is called for each batch coming from the dataset. But I guess that is a different que…
tagged with: python
has answer: http://stackoverflow.com/a/51602496
has comment: http://stackoverflow.com/comment/90027181
type: UnansweredQuestion
downvote count: 0
has title: Tensorflow Estimator API embedding_column compute neighbourhood
answer count: 1
tagged with: word2vec
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-estimator

floating-point-conversion
tags question: http://stackoverflow.com/q/49292456
tag name: floating-point-conversion
type: Tag

http://stackoverflow.com/q/49375601
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49375636
type: Question
score: 0
tagged with: python
has body: updated: tried the code and still got the same error: import tensorflow as tf x = tf.placeholder(dtype, shape=shape, name=name) And then this error shows up. TypeError: ‘NoneType’ object is not callable dtype, shape, name
has comment: http://stackoverflow.com/comment/85752396
type: UnansweredQuestion
answer count: 1
has title: ‘NoneType’ object is not callable
has comment: http://stackoverflow.com/comment/85752288

http://stackoverflow.com/a/55867408
answers question: http://stackoverflow.com/q/49394737
type: Answer
has body: Try this: First you can save the file using pandas to_csv functionality later on you can download that file using google colab files functionality. from google.colab import files df.to_csv('filename.csv') files.download('filename.csv')
has comment: http://stackoverflow.com/comment/118836870
score: 52
upvote count: 52
downvote count: 0

http://stackoverflow.com/a/49421808
has body: "inspired" by the above comments, I think the following seems to be an answer to my question. (Assuming that you have only \1 to \9). At least, this solution was not intuitive and obvious to me (as Python likes to be). More elegant constructs are welcome. import re mystr = 'abc123def456ghi' user_input1 = r'(\d+).+?(\d+)' user_input2 = r'\2+"999"+\1' user_input2 = re.sub(r'\\(\d)',r'm.group(\1)',user_input2,flags=re.S) m = re.search(user_input1,mystr) if m: newstr = eval(user_input2) print (newstr)
answers question: http://stackoverflow.com/q/49415176
has comment: http://stackoverflow.com/comment/85941355
has comment: http://stackoverflow.com/comment/85927994
score: 0
has comment: http://stackoverflow.com/comment/85941150
type: Answer

http://stackoverflow.com/comment/85865147
comment on: http://stackoverflow.com/q/49430747
type: QuestionComment
type: Comment
has text: So I tried compressing before writing the pickle's dump on file, but since compression algorithms are more than linear and IO, while slow, is linear it turns out that we save a lot of disk space, but it is slower by a factor of 1.5 to 2 depending on the compression level.
score: 0

http://stackoverflow.com/q/49323857
type: AnsweredQuestion
has body: According to here, sklearn can not handle categorical variables. And use one-hot encoding to deal with these features are suggested. However, I do not understand how can one-hot encoding help? For example, country=USA or China or England is transformed into country=USA is true or false, the new feature 'country==USA' is still categorical after all (can only take 0 or 1). That does not change anything. Sklearn still treats 0 or 1 as numerical values. For a real example here, I transformed data: human,warm-blooded,hair,yes,no,no,yes,no,mammal python,cold-blooded,scales,no,no,no,no,yes,reptile salmon,cold-blooded,scales,no,yes,no,no,no,fish whale,warm-blooded,hair,yes,yes,no,no,no,mammal frog,cold-blooded,none,no,semi,no,yes,yes,amphibian komodo dragon,cold-blooded,scales,no,no,no,yes,no,reptile bat,warm-blooded,hair,yes,no,yes,yes,yes,mammal pigeon,warm-blooded,feathers,no,no,yes,yes,no,bird cat,warm-blooded,fur,yes,no,no,yes,no,mammal leopard shark,cold-blooded,scales,yes,yes,no,no,no,fish turtle,cold-blooded,scales,no,semi,no,yes,no,reptile penguin,warm-blooded,feathers,no,semi,no,yes,no,bird porcupine,warm-blooded,quills,yes,no,no,yes,yes,mammal eel,cold-blooded,scales,no,yes,no,no,no,fish salamander,cold-blooded,none,no,semi,no,yes,yes,amphibian gila monster,cold-blooded,scales,no,no,no,yes,yes, into [[1. 0. 1. 0. 0. 0. 1. 0. 1. 0. 1. 1. 0. 0. 0. 1. 0. 0. 0.] [1. 0. 1. 0. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 1. 1. 0. 1. 0. 1. 0. 1. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 1. 0. 1. 0. 1. 1. 0. 1. 0. 0. 0. 1. 0. 0. 0.] [1. 0. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 1. 0. 0. 0. 1. 0. 0.] [1. 0. 1. 0. 0. 1. 0. 1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 1.] [0. 1. 1. 0. 0. 0. 1. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0.] [0. 1. 1. 0. 0. 0. 1. 1. 0. 0. 1. 1. 0. 1. 0. 0. 0. 0. 0.] [1. 0. 1. 0. 0. 0. 1. 0. 1. 0. 1. 1. 0. 0. 1. 0. 0. 0. 0.] [1. 0. 0. 0. 1. 1. 0. 0. 1. 1. 0. 1. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 1. 0. 1. 0. 1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 1. 0. 0. 1. 1. 0…
has answer: http://stackoverflow.com/a/49331876
tagged with: python
score: -1
favorite count: 0
linked to: http://stackoverflow.com/q/47586562
has comment: http://stackoverflow.com/comment/85656439
upvote count: 0
answer count: 1
has title: In sklearn, how can one-hot encoding help when building decision tree with categorical features?
tagged with: scikit-learn
tagged with: decision-tree
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49331876

http://stackoverflow.com/comment/85773340
comment on: http://stackoverflow.com/q/49386034
score: 0
has text: No, it is 3.6.4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85765709
has text: Just append each row after another. ex: INPUT --> [[1,2,3],[0,9,8]] CONVERT --> [1,2,3,0,9,8]
comment on: http://stackoverflow.com/a/49381931
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49298342
linked to: http://stackoverflow.com/q/22567306
tagged with: python
tagged with: curl
upvote count: 4
has body: I'm trying to upload a zipfile to a Server using Python requests. The upload works fine. However the uploaded file cannot be opened using Windows Explorer or ark. I suppose there's some problem with mime-type or content-Length. Oddly, uploading the file using curl, does not seem to cause the same problem. Here is my python code for the request: s = requests.Session() headers = {'Content-Type': 'application/zip'} zip = open('file.zip', 'rb') files = {'file': ('file.zip', zip, 'application/zip')} fc = {'Content-Disposition': 'attachment; filename=file.zip'} headers.update(fc) r = requests.Request('POST', url, files=files, headers=headers, auth=(user, password)) prepared = r.prepare() resp = s.send(prepared) This is the curl code, which works flawlessly: curl -X POST \ -ik \ -u user:password \ --data-binary '@file.zip' \ -H 'Content-Type: application/zip' \ -H "Content-Disposition: attachment; filename=file.zip" \ url Uploading the file works in both, the Server also seems to recognize the content-type. However the file is rendered invalid when re-downloading. The zifile is readable before sending via requests or after sending with normal curl, using --data-binary. Opening the downloaded zifile with unip or file-roller works either way. EDIT: I was uploading two files successively. Oddly the error was fixed when uploading the exact same files in reverse order. This has NOT been a python problem. When trying with standard curl I must have accidentally reversed the order, which is why it has been working. I can not explain this behavior nor do I have a fix for it. In conclusion: Uploading the bigger file first did the trick. All of the above seems to be applicable in curl, pycurl and python requests, so I assume it's some kind of bug in one of the curl libraries.
has comment: http://stackoverflow.com/comment/85598901
answer count: 0
has comment: http://stackoverflow.com/comment/85598703
type: UnansweredQuestion
downvote count: 0
tagged with: python-requests
score: 4
favorite count: 0
type: Question
has title: Python requests zip upload makes zipfile unreadable in Windows

http://stackoverflow.com/q/49422913
accepted answer: http://stackoverflow.com/a/49474250
downvote count: 1
has comment: http://stackoverflow.com/comment/85847186
favorite count: 0
has comment: http://stackoverflow.com/comment/85846505
has answer: http://stackoverflow.com/a/49474250
has title: Flask returns 404 when trying to supply GET parameters to root '/' url
type: Question
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/49473261
has body: Here is my route: @app.route('/'). In it I use request.args.get('page') for pagination. But the problem I am having is, if I go to my browser and visit localhost:5000/?page=2 flask returns a 404. What is the reason for this? It works fine on localhost:5000 but I want to supply a page. How do I do this? EDIT: Here is my route: from flaskblog import app from flaskblog.models import Post # Flask-SQLAlchemy @app.route('/') def blog_index(): page_num = int(request.args.get('page', 1)) post_data = Post.query.paginate(per_page=10, page=page_num).items return render_template('index.html', posts=post_data) And for the data I have a single post.
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49473261
upvote count: 1

http://stackoverflow.com/a/49397141
has comment: http://stackoverflow.com/comment/85843779
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85837241
answers question: http://stackoverflow.com/q/49397015
has body: It looks like you already have a UserData object with the user Luciano , try checking if thats the case. It will be helpful if can post what all entries you have in your db for User and UserData table.
accepted answer of: http://stackoverflow.com/q/49397015
has comment: http://stackoverflow.com/comment/85854428
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85811412

http://stackoverflow.com/comment/85814877
score: 0
comment on: http://stackoverflow.com/q/49406653
type: Comment
has text: Sorry I wasnt shouting, I just placed it there to highlight it.
type: QuestionComment

http://stackoverflow.com/comment/85564685
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49281051
score: 0
has text: Removing, as in remove it from the string completely or substitute them with lowercase letters?

http://stackoverflow.com/comment/85650008
type: Comment
score: 2
type: AnswerComment
has text: "This should not cause any problems" - this will cause problems
comment on: http://stackoverflow.com/a/49320401

http://stackoverflow.com/comment/85805994
score: 0
has text: Updated the question with the part that is showing the error! :-)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49402097

http://stackoverflow.com/comment/85688461
score: 0
type: Comment
type: AnswerComment
has text: I appreciate a lot your answer, but none of them fix my problem. The first test gave me 31356 (or 10,452 if I divide that result by 3) instead of 10,900. The second test just gave me 0 everytime I ran it.
comment on: http://stackoverflow.com/a/49343402

http://stackoverflow.com/a/49342392
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49342018
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49342018
type: Answer
has body: There is no general solution to this problem. Matplotlib cannot decide to show part of an object more in front than another part of it. See e.g. the FAQ, or other questions, like How to obscure a line behind a surface plot in matplotlib? One may of course split up the object in several parts if necessary. Here, however, it seems sufficient to add the functions up. surf1 = ax.plot_surface(X, Y, Z0+Z1+Z2, cmap=plt.cm.coolwarm, linewidth=0, antialiased=False) ax.contour(X, Y, Z0+Z1+Z2, zdir='z', offset=-0.5)

http://stackoverflow.com/comment/85564866
has text: @Blender it is an ImageField
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49280168

http://stackoverflow.com/comment/117626803
has text: This is bad design. Base class does not know what animals would inherit from it.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49436763

http://stackoverflow.com/comment/85680394
type: QuestionComment
has text: Your edited code does not make use of the suggested solution from the linked question, so it's clear that it does not look as intended. The question about the legend is unrelated and has also been asked already [been asked](https://stackoverflow.com/questions/38131062/attributeerror-unknown-property-legend-in-seaborn).
comment on: http://stackoverflow.com/q/49336474
score: 0
type: Comment

http://stackoverflow.com/comment/97939622
type: Comment
type: AnswerComment
score: 1
has text: I am glad it worked out for you, in my case I made the change by mistake, I had forgotten what I did. but once I found the answer and updated it, I haven’t had to worry about it.
comment on: http://stackoverflow.com/a/49442035

http://stackoverflow.com/a/49344731
has body: You need to pass the attributes as a dictionary. There are three ways in which you can get the data you want. import requests from bs4 import BeautifulSoup r = requests.get('https://www.arsenal.com/fixtures') soup = BeautifulSoup(r.text, 'lxml') matches = soup.find_all('article', {'role': 'article'}) print(len(matches)) # 16 Or, this is also the same: matches = soup.find_all('article', role='article') But, both these methods give some extra article tags that don't have the Arsernal fixtures. So, if you want to find them using /fixture/arsenal you can use CSS selectors. (Using find_all won't work, as you need a partial match) matches = soup.select('article[about^=/fixture/arsenal]') print(len(matches)) # 13 Also, have a look at the keyword arguments. It'll help you get what you want.
answers question: http://stackoverflow.com/q/49337956
type: Answer
score: 0

http://stackoverflow.com/q/49381679
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85846633
has comment: http://stackoverflow.com/comment/85802779
tagged with: dbscan
has body: I tried doing DBSCAN clustering using word2vec weighted tfidf vectors and used different thresholds of epsilon and minpts for DBSCAN. I also tried optics clustering method with different minpts, however it didn't yield any output at all. #Import libraries from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem import WordNetLemmatizer from unidecode import unidecode # $ pip install unidecode import gensim import csv import nltk from sklearn.feature_extraction import text import pandas as pd import numpy as np from collections import defaultdict from string import lower #read data dat = pd.read_csv('D:\\data_800k.csv',encoding='latin',nrows=500000).Certi.tolist() wnl = WordNetLemmatizer() #nltk.download('punkt') my_stop_words = text.ENGLISH_STOP_WORDSunion(['education','certification','certificate','certified']) def tokenize_stop(row): az = [] for j in nltk.word_tokenize(lower(unidecode(row))): if j not in my_stop_words: az.extend([j]) return az def preprocess(dat): return [tokenize_stop(row) for row in dat] X = preprocess(dat) #word2vec model = gensim.models.Word2Vec(X, size=100) w2v = dict(zip(model.wv.index2word, model.wv.syn0)) # tfidf = TfidfVectorizer(analyzer=lambda x: x) tfidf.fit(X) max_idf = max(tfidf.idf_) #train model def fit(X): tfidf = TfidfVectorizer(analyzer=lambda x: x) tfidf.fit(X) # if a word was never seen - it must be at least as infrequent # as any of the known words - so the default idf is the max of # known idf's max_idf = max(tfidf.idf_) return defaultdict( lambda: max_idf, [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()]) #actual training// word2weight = fit(X) #multiply word2vec with tfidf def transform_word2vec_tfidf(X,word2vec,word2weight): return np.array([ np.mean([word2vec[w] * word2weight[w] for w in words if w in word2vec] or [np.zeros(dim)], axis=0) for words in X ]) export_data_w2v_Tfidf = transform_word2vec_tfidf(X,w2v,word2weight) np.savetxt('D:\Azim\data_500k_w2v_tfidf.csv',export_data_w2v_Tfidf,deli…
has comment: http://stackoverflow.com/comment/85843098
has comment: http://stackoverflow.com/comment/85839286
tagged with: python
has title: Document clustering: DBSCAN and optics clustering not giving me any clusters
has comment: http://stackoverflow.com/comment/85838468
has comment: http://stackoverflow.com/comment/85831080
has comment: http://stackoverflow.com/comment/85794885
has comment: http://stackoverflow.com/comment/85794437
tagged with: elki
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85802673
score: 0
tagged with: cluster-analysis
answer count: 1
has comment: http://stackoverflow.com/comment/85868104
upvote count: 1
has answer: http://stackoverflow.com/a/49433644
has comment: http://stackoverflow.com/comment/85864120
linked to: http://stackoverflow.com/q/49380258

http://stackoverflow.com/q/49332765
has title: How to capitalize the first letter of a word from a list that is preceded by a word ending in punctuation? Python
has body: I am writing a quick program in Python that translates from English to pig latin. I have finished the pig latin part where the output is a string of translated words. The punctuation works properly and is included with each word: input= This is a sentence. Now it is in pig latin. output= ['isthay','isay','away','entencesay.','ownay','itay','isay','inay','igpay','atinlay.'] I can join these using ' '.join(...) but I am looking for a way to capitalize the first letter of the words that follow words ending in '.:?!' as well as the very first letter. I have tried many different things as well as similar questions on this website but I haven't found exactly what I'm looking for. I am very inexperienced with this so any answers would help. Thank you. Note. I am not looking to capilatise the first letter of every word!
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85667436
has comment: http://stackoverflow.com/comment/85667437
tagged with: python
linked to: http://stackoverflow.com/q/39969202
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/39969202
has comment: http://stackoverflow.com/comment/85667423

http://stackoverflow.com/q/49331782
score: 2
linked to: http://stackoverflow.com/q/1933451
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/49332214
has title: Python 3: How to check if a string can be a valid variable?
has answer: http://stackoverflow.com/a/49331917
favorite count: 0
tagged with: python-3.x
type: Question
type: UnansweredQuestion
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/49331792
has body: I have a string and want to check if it can be used as a valid variable without getting a syntax error. For example def variableName(string): #if string is valid variable name: #return True #else: #return False input &gt;&gt;&gt; variableName("validVariable") output &gt;&gt;&gt; True input &gt;&gt;&gt; variableName("992variable") output &gt;&gt;&gt; False I would not like to use the .isidentifier(). I want to make a function of my own.

http://stackoverflow.com/comment/85715799
comment on: http://stackoverflow.com/q/49357552
has text: What? So how does this not work? What is the question? And why are you using `numpy`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49387673
type: Answer
score: 0
has body: In Python Pandas you could use PD.melt and specify the columns you want to keep the same. The others will get pivoted. For more info: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html
answers question: http://stackoverflow.com/q/49387281

http://stackoverflow.com/q/49322210
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49339123
tagged with: oracle11g
favorite count: 0
type: Question
tagged with: oracle-database
tagged with: python
tagged with: python-3.6
has title: Connecting to Oracle Database with cx_oracle gives DPI-1047 on Windows
score: 2
type: AnsweredQuestion
has body: import pandas as pd import sqlalchemy engine = sqlalchemy.create_engine('oracle://XXX:XXX@XXX:XXX/?service_name=XXX') sql = 'select * from XXX where rownum &lt; 10' df = pd.read_sql(sql,con=engine) DatabaseError: (cx_Oracle.DatabaseError) DPI-1047: 64-bit Oracle Client library cannot be loaded: "C:\oracle\11.2.0\bin\oci.dll is not the correct architecture". See https://oracle.github.io/odpi/doc/installation.html#windows for help I am trying to connect to an Oracle database using Python but I am receiving the above error. I know that: I have set the path to look at the correct location - it is shown in the error. Python is 64 bit. The bin folder location contains both a 32 bit (ociw32.dll) and a 64 bit (oci.dll) file. Yet the error still tells me the architecture is wrong. Any help on this would be great - I can't figure out where the issue might be!
upvote count: 2
linked to: http://stackoverflow.com/q/495244
accepted answer: http://stackoverflow.com/a/49339123
tagged with: cx-oracle

http://stackoverflow.com/q/49346825
type: Question
linked to: http://stackoverflow.com/q/31671101
has comment: http://stackoverflow.com/comment/85731901
has answer: http://stackoverflow.com/a/49347420
has comment: http://stackoverflow.com/comment/85723741
tagged with: python
has comment: http://stackoverflow.com/comment/85730793
tagged with: abaqus
has body: I'm trying to get the element density from the abaqus output database. I know you can request a field output for the volume using 'EVOL', is something similar possible for the density? I'm afraid it's not because of this: Getting element mass in Abaqus postprocessor What would be the most efficient way to get the density? Look for every element in which section set it is?
has comment: http://stackoverflow.com/comment/85731111
has comment: http://stackoverflow.com/comment/85736598
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49347420
has answer: http://stackoverflow.com/a/49367901
answer count: 2
has comment: http://stackoverflow.com/comment/85720994
score: 1
linked to: http://stackoverflow.com/q/49250071
has title: Getting element density from abaqus output database using python scripting
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85703355
has comment: http://stackoverflow.com/comment/85734343
accepted answer: http://stackoverflow.com/a/49367901
favorite count: 0

http://stackoverflow.com/comment/85851778
comment on: http://stackoverflow.com/q/49413803
type: Comment
score: 0
type: QuestionComment
has text: @DanielPryden It happens every time I download it using `urllib.request`. But when I download it manually and read it, everything is fine (look at the Update 2).

http://stackoverflow.com/comment/85845680
comment on: http://stackoverflow.com/a/49398702
type: AnswerComment
has text: @KeyurPotdar yes i can use the first method and works, it wont work dynamically, since the page i am scraping changes according to particular parameter called global_id. plus for each tab it produces new url in XHR , so any how i have to perform clicks.
score: 0
type: Comment

http://stackoverflow.com/q/49424131
has body: I'm trying to get the coordinates from a scanned QR-code using the pyzbar module. If I use the following code below to do this: test = decode(img) print(test) I get the following result: [Decoded(data=b'Part4', type='QRCODE', rect=Rect(left=172, top=332, width=75, height=76))] The problem however, is that I do not know how to just extract the rect part of this string. I'm using spyder, and if I go to the variable explorer to try and see how the variable is built-up, I get the following error: AttributeError("Can't get attribute 'Rect' on ",) Anyone know what could be it?
score: 1
has comment: http://stackoverflow.com/comment/85849712
downvote count: 0
upvote count: 1
has title: Get coordinates from pyzbar decode
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61815969
tagged with: python
possible better answer: http://stackoverflow.com/a/61815969
accepted answer: http://stackoverflow.com/a/49424231
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49424231
answer count: 2

http://stackoverflow.com/q/49371500
downvote count: 0
upvote count: 1
tagged with: python
has title: Tkinter module on repl.it "no display name or $DISPLAY
answer count: 1
has comment: http://stackoverflow.com/comment/85744142
linked to: http://stackoverflow.com/q/44436064
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91845851
score: 1
duplicate of: http://stackoverflow.com/q/44436064
favorite count: 0
accepted answer: http://stackoverflow.com/a/49371801
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/49371801
has body: this is my code which I am running on a Python 3 on Repl.it, unfortunately when I try and use the Tkinter module to create a window, it can't seem to find a display environment. Why is this and is there a fix for it? import tkinter window = tinter.Tk() And the error is "_tkinter.TclError: no display name and no $DISPLAY environment variable" Thanks in advance for your help

http://stackoverflow.com/a/49332866
has body: Im not clear on whatg you're trying to do with the while loop. Also you could check that the value is a valid rgb value as per below: colorListString = '123,245,230' colorMatrix = [] colorList =colorListString.split(",") if len(colorList)==3: for i in range(3): val = int(colorList[i]) if val &lt;= 255 and val &gt;= 0: colorList[i] = val colorMatrix +=[colorList] print(colorMatrix)
type: Answer
has comment: http://stackoverflow.com/comment/85667587
score: 0
answers question: http://stackoverflow.com/q/49332809

http://stackoverflow.com/a/49401796
answers question: http://stackoverflow.com/q/49401465
downvote count: 0
has comment: http://stackoverflow.com/comment/85826446
score: 9
upvote count: 9
has body: class ContestProblemInline(admin.TabularInline): model = ProblemsInContest def formfield_for_foreignkey(self, db_field, request=None, **kwargs): field = super(RoomInline, self).formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == 'your_field_name': if request._obj_ is not None: field.queryset = field.queryset.filter(your_field_name = request._obj_) else: field.queryset = field.queryset.none() return field class ContestAdmin(admin.ModelAdmin): inlines = (ContestProblemInline,) def get_form(self, request, obj=None, **kwargs): # just save obj reference for future processing in Inline request._obj_ = obj return super(ContestAdmin, self).get_form(request, obj, **kwargs)
has comment: http://stackoverflow.com/comment/85805617
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49401465

http://stackoverflow.com/q/49342471
accepted answer: http://stackoverflow.com/a/49342560
has comment: http://stackoverflow.com/comment/85685132
type: Question
has comment: http://stackoverflow.com/comment/85685171
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85685148
linked to: http://stackoverflow.com/q/9752958
has comment: http://stackoverflow.com/comment/85685157
score: 0
has body: i have two inputs that i would like to use within another function, is it possible to make them global somehow? here are the two inputs that i would like to use def UserInput(): while True: if ChooseMove in self.pieces(): KingRow = int(input("Choose Row: ")) KingColumn = int(input("Choose Column: ")) here is where i would like to use both variables of the inputs def KingMoves(self, rows, columns): FinalMove = [] FinalMove.append(((KingRow - 1),(KingColumn))) FinalMove.append(((KingRow + 1),(KingColumn))) FinalMove.append(((KingRow),(KingColumn + 1))) return FinalMove
linked to: http://stackoverflow.com/q/4693120
answer count: 1
has comment: http://stackoverflow.com/comment/85685133
tagged with: python
has comment: http://stackoverflow.com/comment/85685137
has comment: http://stackoverflow.com/comment/85685872
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85685141
tagged with: list
has comment: http://stackoverflow.com/comment/85685225
has title: is it possible to make user input global to be used somewhere else?
has comment: http://stackoverflow.com/comment/85685163
has comment: http://stackoverflow.com/comment/85685121
has answer: http://stackoverflow.com/a/49342560

http://stackoverflow.com/q/49354262
has comment: http://stackoverflow.com/comment/85708871
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85829662
tagged with: python
has comment: http://stackoverflow.com/comment/85708876
has title: Converting a string representation of a json/dict to something usable with python request
tagged with: dictionary
has body: I finally had to give up and ask for help. I am retrieving a document (with requests) that has a json type of format (but is not well formatted - no double quotes) and trying to extract the data as a normal dict. Here is what I have: this works and will get you the output from which I am trying to extract the data. def test(): url = "http://www.sgx.com/JsonRead/JsonstData" payload = {} payload['qryId'] = 'RSTIc' payload['timeout'] = 60 header = {'User-Agent' : 'Mozilla/5.0 (compatible; MSIE 10.0; Linux i686; Trident/2.0)', 'Content-Type': 'text/html; charset=utf-8'} req = requests.get(url, headers = header, params = payload) print(req.url) prelim = req.content.decode('utf-8') print(type(prelim)) print(prelim) test() What I would like to have after that is: (assuming a properly functioning dict) for stock in prelim['items']: print(stock['N']) Which should give me a list of all the stocks names. I have tried most json functions: prelim.json(), loads., load., dump., dumps., parse. None seems to work because the data is not formatted properly. I also tried ast.literal_eval() without success. I tried some examples on Stack Overflow to convert that string in a proper dict but no luck. I don't seem to be able to convert that string to make it behave as a proper dictionary. If you can point me in the right direction that would be much appreciated. Good samaritains have asked for an example of the data. The data coming from the above request is a bit longer but I removed a few 'items' so people can see the general look of the retrieved data. {}&amp;&amp; {identifier:'ID', label:'As at 19-03-2018 8:38 AM',items:[{ID:0,N:'AscendasReit',SIP:'',NC:'A17U',R:'',I:'',M:'',LT:0,C:0,VL:97.600,BV:485.300,B:'2.670',S:'2.670',SV:1009.100,O:0,H:0,L:0,V:259811.200,SC:'9',PV:2.660,P:0,P_:'X',V_:''}, {ID:1,N:'CapitaComTrust',SIP:'',NC:'C61U',R:'',I:'',M:'',LT:0,C:0,VL:126.349,BV:1467.300,B:'1.800',S:'1.800',SV:620.900,O:0,H:0,L:0,V:228691.690,SC:'9',PV:1.810,P:0,P_:'X',V_:''}, {ID:2,N:'Capi…
has comment: http://stackoverflow.com/comment/85709124
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49354746
tagged with: python-requests

http://stackoverflow.com/a/49385415
score: 0
type: Answer
has body: import datetime today = datetime.date.today() first_day = datetime.date(year=today.year, month=1, day=1) diff = today - first_day print(diff) 78 days, 0:00:00
answers question: http://stackoverflow.com/q/49385108

http://stackoverflow.com/q/49406058
type: Question
linked to: http://stackoverflow.com/q/44030707
has answer: http://stackoverflow.com/a/61637486
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85813098
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/74636067
score: 14
upvote count: 14
tagged with: python-2.7
has answer: http://stackoverflow.com/a/58665742
has body: I'm trying to create tables in my database (postgresql 9.6) and when I launch my python script to do so, it returns me an error of the following type: "Section postgresql not found in the $FILEDIR/database.ini file" It seems like the parser cannot read the section, but I don't understand why. This is my config method: def config(filename='$FILEDIR/database.ini', section='postgresql'): parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db Database.ini: [postgresql] host=localhost database=mydatabase user=myuser password=mypassword I've tried the answers in this following thread but it does not help me at all. Anyone knows the cause? I'm using python 2.7 and I've executed "pip install config" and "pip install configparser" for dependencies.
downvote count: 0
has title: Section postgresql not found in the database.ini file
has answer: http://stackoverflow.com/a/69660681
has comment: http://stackoverflow.com/comment/85813414
tagged with: configparser
favorite count: 0

http://stackoverflow.com/comment/85787905
has text: Can you use NumPy?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49393125

http://stackoverflow.com/comment/85761066
has text: @DeepSpace code updated, thanks a lot!
comment on: http://stackoverflow.com/q/49379890
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49323903
has comment: http://stackoverflow.com/comment/85660529
has comment: http://stackoverflow.com/comment/85651049
has comment: http://stackoverflow.com/comment/85660446
has comment: http://stackoverflow.com/comment/85649528
upvote count: 2
has comment: http://stackoverflow.com/comment/85651495
has comment: http://stackoverflow.com/comment/85649284
downvote count: 0
type: Answer
has body: From your comment: my problem is to create a new window and print there the strings, I tried tk.Toplevel() but I don't know how to make the new window in which display the strings This is a simple example but should help. I have a button on the root window that links to a function called new_window(). This function will create a top level window containing a text box widget. We then use the with open statement to write the data to the text box. import tkinter as tk root = tk.Tk() def new_window(): top = tk.Toplevel(root) my_text_box = tk.Text(top) my_text_box.pack() with open(project_dir + 'logs/wash.log') as f: for line in f.readlines(): if not line.startswith('BSSID ') and \ not line.startswith('------------'): my_text_box.insert("end", line) open_new_window = tk.Button(root, text="Open Toplevel", command=new_window) open_new_window.pack() root.mainloop()
answers question: http://stackoverflow.com/q/49323582
score: 2
accepted answer of: http://stackoverflow.com/q/49323582
type: AcceptedAnswer

http://stackoverflow.com/q/49385578
linked to: http://stackoverflow.com/q/14087598
has title: pip3 install mysql ERROR
has comment: http://stackoverflow.com/comment/85772165
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49385711
has body: I get this error pi@teambaboy:~ $ pip3 install mysql Collecting mysql Downloading https://www.piwheels.org/simple/mysql/mysql-0.0.1-py3-none-any.whl Collecting MySQL-python (from mysql) Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-k38v3y9c/MySQL-python/setup.py", line 13, in &lt;module&gt; from setup_posix import get_config File "/tmp/pip-build-k38v3y9c/MySQL-python/setup_posix.py", line 2, in &lt;module&gt; from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-k38v3y9c/MySQL-python/
score: 0
tagged with: mysql
answer count: 1
has comment: http://stackoverflow.com/comment/85772211
type: Question

http://stackoverflow.com/comment/85642725
has text: forgot to add that ciphertext_2 = "4710"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49320891
score: 0

http://stackoverflow.com/comment/85653839
has text: Hi, welcome to stack overflow. You're storing of every position the projectile has crossed. You end up with a very long list of positions, much longer than the number of angles. I think you want to just store the maximum position reached by each projectile, and then see which angle that corresponds to, right?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49325937
type: Comment

http://stackoverflow.com/q/49373647
tagged with: parameters
has title: How to create a file using parameters in Python?
type: AnsweredQuestion
score: 0
has body: I'm currently creating a file transfer client-server. What I need to do is to make the client create a file using parameters (if I'm not wrong, this is the same thing as an argument). So, what I'm looking for is to run python server.py and then python client.py file.txt This is the server code: # -*- coding: utf-8 -*- import socket from threading import Thread class threaded_server(Thread): def __init__(self,ip,port,sock): Thread.__init__(self) self.ip = ip self.port = port self.sock = sock print " Nova conexão de "+ip+":"+str(port) # rodando a thread, leitura da mensagem def run(self): arquivo = open('entrada.txt','rb') while True: temp = arquivo.read(msg) while (temp): self.sock.send(temp) temp = arquivo.read(msg) if not temp: self.sock.close() break host = socket.gethostname() port = 5001 msg = 1024 # não funcionou na declaração _def_init sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((host, porta)) threads = [] # servidor fica aguardando novas conexoes while True: sock.listen(4) print "Aguardando..." (conn, (ip,port)) = sock.accept() print 'Conexão de: ', (ip,port) newthread = threaded_server(ip,port,conn) newthread.start() threads.append(newthread) for t in threads: t.join() This is the client code: # -*- coding: utf-8 -*- import socket host = socket.gethostname () port = 5001 msg = 2048 tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) destino = (host, porta) tcp.connect(destino) with open('saida.txt', 'wb') as arquivo: print 'Arquivo aberto' while True: dados = tcp.recv(msg) if not dados: arquivo.close() break arquivo.write(dados) tcp.close() print('Fim da Conexão') What I'm looking for is to make the client create the file that it will be sent to the server. Sorry for the code in portugese. If someone needs more clarification, just ask.
has comment: http://stackoverflow.com/comment/85749325
answer count: 1
tagged with: file
type: Question
linked to: http://stackoverflow.com/q/20063
tagged with: client-server
has answer: http://stackoverflow.com/a/49373995
accepted answer: http://stackoverflow.com/a/49373995
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/85748654

http://stackoverflow.com/comment/86596506
type: Comment
score: 0
type: AnswerComment
has text: I have added an update including the new recipe with the suggested changes. Unfortunately installing conda in /usr/local/conda makes no difference, and it fails with the same error.
comment on: http://stackoverflow.com/a/49642742

http://stackoverflow.com/comment/85593247
type: QuestionComment
has text: 6. Do you know what `len(fres.findall(tToken))` is trying to do? Do you know where does the `.findall()` come from? And what does `len()` do?
comment on: http://stackoverflow.com/q/49293348
type: Comment
score: 0

http://stackoverflow.com/comment/85626917
type: Comment
has text: @juanpa.arrivillaga. i see your point now. Using set operations will actually help make it more portable then
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49312361

http://stackoverflow.com/comment/85719151
has text: That's strange. works fine for me. can you try again?
type: AnswerComment
comment on: http://stackoverflow.com/a/49351304
type: Comment
score: 0

http://stackoverflow.com/q/49368119
answer count: 0
has body: I'm trying to link 'owner' field of my model to an AbstractUser. I need it to be done automatically, the only think i'm able to do by myself is to allow user logged in to choice between every existing user with, what's not what i want. I would like to not have a field to manipulate, but a outcome serializer with id or username of User that added the model. I'm trying to find solutions for a few days, I've tried already combine ForeignKey, PrimaryKeys, OneToOneField, HiddenField, get_user, perform_create, but I'm for sure doing something wrong, and i'm almost lost with it. The last thing i tried is to def_perform in views like DRF QuickStart tutorial say, but without results. I add some code sample to be more understandable: There is my AbstractUser model: from django.db import models from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): username = models.CharField(max_length=20, unique=True) ... i added it to AUTH_USER_MODEL = in the settings. And there is other model which i want to link with User: from django.db import models from users.models.user import UserProfile class MyPhoto(models.Model): owner = models.ForeignKey(UserProfile, related_name='photos', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='Images') serializer.py class MyPhotoSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = MyPhoto fields = ('pk', 'image', 'owner') def create(self, validated_data): photo = MyPhoto.objects.create( image=validated_data['image'] ) photo.save() return photo views.py class UpdateMyPhotoViewSet(viewsets.ModelViewSet): queryset = MyPhoto.objects.all() serializer_class = MyPhotoSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(created_by=self.request.user) and for now i can't see the owner field results. Thanks in advance.
type: UnansweredQuestion
tagged with: django
tagged with: django-rest-framework
type: Question
has comment: http://stackoverflow.com/comment/85754934
score: 0
has comment: http://stackoverflow.com/comment/85783571
tagged with: python
has title: Django rest framework auto-populate filed with user.id/username

http://stackoverflow.com/q/49342882
tagged with: django-rest-framework
answer count: 1
has title: Django Rest framework: I want my GET response to be a JSON object of links to all files in my media directory on my local machine. How do i do this?
type: Question
has comment: http://stackoverflow.com/comment/85686566
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85687119
has body: My Project structure: myproject --* --* --media --* --* I want to allow users to access to my media directory: I want them to be able to read and download all files in my media directory and I want them to be able to write files to my media directory. How can I accomplish this using Django rest framework? Assume that there are 2 files in my media directory: I want to return the following JSON object as a response to a GET request: { file1: link_to_example1.txt } { file2: link_to_example2.txt } How do I do this -- what should my app's model.py, views.py and maybe serializers.py look like?
score: 0
has answer: http://stackoverflow.com/a/49344230
tagged with: django

http://stackoverflow.com/a/49515044
has comment: http://stackoverflow.com/comment/86181690
answers question: http://stackoverflow.com/q/49376208
score: 2
has body: I was having exactly the same problem yesterday. I ended up using numpy.linalg.lstsq and I think it works. # find tranformation matrix M so that: source_matrix∙M = target_matrix based #on top n most frequent terms in the target corpus n=500 # the choice of n depends on the size of your vocabulary M=np.linalg.lstsq(source_mtrx[:n],target_mtrx[:n])[0] print M.shape # returns (100,100) # apply this tranformation to source matrix: new_mtrx= np.array([np.dot(i, M) for i in source_mtrx]) Also check out this paper Lexical Comparison Between Wikipedia and Twitter Corpora by Using Word Embeddings. They are based on the paper that you mentioned and they follow the same method but they explain the implementation with more details. For example, they suggest that in order to find the transformation matrix M we only use the vectors of the top n most frequent terms, and then, after we apply the transformation to the source matrix, we calculate the similarity for the remaining terms. Please let me know if u find another solution for calculating M based on SGD.
has comment: http://stackoverflow.com/comment/86134748
upvote count: 2
has comment: http://stackoverflow.com/comment/86209014
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86134850

http://stackoverflow.com/comment/85815616
comment on: http://stackoverflow.com/q/49407218
type: QuestionComment
has text: this is the most unefficient factor decomposing code I ever saw. I suggest that you check codereview.stackexchange.com to find working examples (or even here)
type: Comment
score: 4

http://stackoverflow.com/q/49420039
accepted answer: http://stackoverflow.com/a/49459782
has comment: http://stackoverflow.com/comment/85846344
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49459782
score: 1
has body: Is it possible to efficiently store big ints in MySQL? Not big as in bigint, more like 1000th Catalan number or so, and there are at least hundreds of them. More likely, thousands. The speed of storing and loading values is a priority. The numbers are created using gmpy2, Python's GMP wrapper. So it'd be nice if the stored numbers were accessible in the same format, but if not, I can always write a converter.
has comment: http://stackoverflow.com/comment/85891584
has comment: http://stackoverflow.com/comment/85846478
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/85845293
type: Question
has comment: http://stackoverflow.com/comment/85842261
has title: Storing really huge ints in MySQL
tagged with: gmp
downvote count: 0
answer count: 1
upvote count: 1
tagged with: gmpy

http://stackoverflow.com/comment/85582445
has text: Not printed? Where do you try printing?
score: 0
comment on: http://stackoverflow.com/q/49287794
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49346604
has body: I have a DataFrame, df, in pandas with series df.A and df.B and am trying to create a third series, df.C that is dependent on A and B as well as the previous result. That is: C[0]=A[0] C[n]=A[n] + B[n]*C[n-1] what is the most efficient way of doing this? Ideally, I wouldn't have to fall back to a for loop. Edit This is the desired output for C given A and B. Now just need to figure out how... import pandas as pd a = [ 2, 3,-8,-2, 1] b = [ 1, 1, 4, 2, 1] c = [ 2, 5,12,22,23] df = pd.DataFrame({'A': a, 'B': b, 'C': c}) df
has comment: http://stackoverflow.com/comment/85694756
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49346947
score: 5
possible better answer: http://stackoverflow.com/a/49346868
has comment: http://stackoverflow.com/comment/85693219
has answer: http://stackoverflow.com/a/49346947
upvote count: 5
has answer: http://stackoverflow.com/a/49346868
has title: Recurrence relation in Pandas
tagged with: python
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85693510
tagged with: pandas

http://stackoverflow.com/q/49338135
favorite count: 0
type: Question
tagged with: xlutils
has title: How to go about copying a subsection of "xlsx" file into a new sheet?
has body: So here is the challenge I am facing. I want to copy a certain range of rows and columns from one sheet in a workbook into a new sheet. Seems pretty easy enough right? Here's the catch: The entire process has to be done using python and the copying process should preserve the formatting. i.e. any and all formatting in the original range has to be there in the new sheet. (So that effectively rules out reading and writing one cell at a time) I have bee trying to rack my brains on it, but cant seem to figure out a simple elegant solution. Can anyone point me in the right direction? Or perhaps towards some documentation that might help?
has comment: http://stackoverflow.com/comment/85679098
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49340294
tagged with: python
has comment: http://stackoverflow.com/comment/85679389
has comment: http://stackoverflow.com/comment/85679048
score: 2
has comment: http://stackoverflow.com/comment/85678746
has comment: http://stackoverflow.com/comment/85679408
tagged with: xlwt
tagged with: xlrd
tagged with: openpyxl
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49405337
type: Question
type: UnansweredQuestion
has body: I've done plenty of searching however there is a lot of confusing snippets out there that are very similar. I've attempted to use the DesiredCapabilities, ChromeOptions, Options and a series of arguments but nothing is working :( It fails to set a proxy. For example (ChromeOptions) chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy=https://' + proxy_ip_and_port) chrome_options.add_argument('--proxy-auth=' + proxy_user_and_pass) chrome_options.add_argument('--proxy-type=https') browser = webdriver.Chrome("C:\drivers\chromedriver.exe") Another example (Options) options = Options() options.add_argument('--proxy=https://' + proxy_ip_and_port) options.add_argument('--proxy-auth=' + proxy_user_and_pass) options.add_argument('--proxy-type=https') browser = webdriver.Chrome("C:\drivers\chromedriver.exe", chrome_options=options) I've also used --proxy-server instead of --proxy-auth, --proxy-type... etc even in the format of: '--proxy-server=http://' + proxy_user_and_pass + '@' + proxy_ip_and_port Another example (DesiredCapabilities) from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities capabilities = dict(DesiredCapabilities.CHROME) capabilities['proxy'] = {'proxyType': 'MANUAL', 'httpProxy': proxy_ip_and_port, 'ftpProxy': proxy_ip_and_port, 'sslProxy': proxy_ip_and_port, 'noProxy': '', 'class': "org.openqa.selenium.Proxy", 'autodetect': False} capabilities['proxy']['socksUsername'] = proxy_user capabilities['proxy']['socksPassword'] = proxy_pass browser = webdriver.Chrome(executable_path="C:\drivers\chromedriver.exe", desired_capabilities=capabilities) I've tried in Firefox too but the same issue happens, it uses the browser with my normal IP.
tagged with: selenium-firefoxdriver
has comment: http://stackoverflow.com/comment/85824975
tagged with: python
has comment: http://stackoverflow.com/comment/85859960
upvote count: 2
tagged with: selenium-chromedriver
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/78143627
downvote count: 0
tagged with: http-proxy
tagged with: selenium
has title: Selenium Chrome & Firefox WebDriver: Set HTTPS proxy in Python
favorite count: 0
has answer: http://stackoverflow.com/a/63099891

http://stackoverflow.com/q/49426546
score: 4
tagged with: list
has answer: http://stackoverflow.com/a/49426880
possible better answer: http://stackoverflow.com/a/49426695
accepted answer: http://stackoverflow.com/a/49427254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49427254
has answer: http://stackoverflow.com/a/49426861
downvote count: 0
has answer: http://stackoverflow.com/a/49426695
has title: Map elements to list of unique indexes
tagged with: unique
favorite count: 0
answer count: 4
has body: Suppose I have a list of elements: my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] and I want to convert this list to a list of indexes of unique elements. So CatA is assigned to index 0, CatB to index 1 and CatC to index 2. My desired result would be: result = [0, 1, 2, 0, 0, 2] Currently I'm doing this by creating a dictionary that assigns to each element it's unique id and then using a list comprehension to create the final list of indexes: unique_classes = np.unique(my_list) conversion_dict = dict(unique_classes, range(len(unique_classes)) result = [conversion_dict[i] for i in my_list] My question is: Is there an easier and straightforward way of doing this? I am thinking about having a big list of categories so it needs to be efficient but preventing me to manually create the unique list, the dictionary and the list comprehension.
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85855317
upvote count: 4

http://stackoverflow.com/comment/85565564
score: 0
type: Comment
type: QuestionComment
has text: I really wish teachers would come up with an assignment where a while loop is the obvious right answer, instead of giving an assignment where a for loop is much better and then artificially telling people to do it with a while. If they’re trying to teach/test how to transform one into the other, then fine, but usually they’re just teaching/testing how to use a while loop in the first place, and a problem like this just teaches people that while loops are stupid and programming is tedious.
comment on: http://stackoverflow.com/q/49281051

http://stackoverflow.com/q/49320891
has comment: http://stackoverflow.com/comment/85642932
has body: I am new to Python &amp; I am trying to learn how to XOR hex encoded ciphertexts against one another &amp; then derive the ASCII value of this. I have tried some of the functions as outlined in previous posts on this subject - such as bytearray.fromhex, binascii.unhexlify, decode("hex") and they have all generated different errors (obviously due to my lack of understanding). Some of these errors were due to my python version (python 3). Let me give a simple example, say I have a hex encoded string ciphertext_1 ("4A17") and a hex endoded string ciphertext_2. I want to XOR these two strings and derive their ASCII value. The closest that I have come to a solution is with the following code: result=hex(int(ciphertext_1, 16) ^ int(ciphertext_2, 16)) print(result) This prints me a result of: 0xd07 (This is a hex string is my understanding??) I then try to convert this to its ASCII value. At the moment, I am trying: binascii.unhexliy(result) However this gives me an error: "binascii.Error: Odd-length string" I have tried the different functions as outlined above, as well as trying to solve this specific error (strip function gives another error) - however I have been unsuccessful. I realise my knowledge and understanding of the subject are lacking, so i am hoping someone might be able to advise me? Full example: #!/usr/bin/env python import binascii ciphertext_1="4A17" ciphertext_2="4710" result=hex(int(ciphertext_1, 16) ^ int(ciphertext_2, 16)) print(result) print(binascii.unhexliy(result))
has comment: http://stackoverflow.com/comment/85644958
linked to: http://stackoverflow.com/q/29408173
has answer: http://stackoverflow.com/a/49321416
accepted answer: http://stackoverflow.com/a/49321151
has comment: http://stackoverflow.com/comment/85642920
tagged with: python
has title: Hex string convert to ASCII after XOR
tagged with: ascii
tagged with: hex
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85642725
possible better answer: http://stackoverflow.com/a/49321416
linked to: http://stackoverflow.com/q/5649407
tagged with: string
has answer: http://stackoverflow.com/a/49321151
has comment: http://stackoverflow.com/comment/85642726
tagged with: xor
type: Question

http://stackoverflow.com/comment/85687005
has text: Possible duplicate of [Selenium Webdriver: Element Not Visible Exception](https://stackoverflow.com/questions/28820820/selenium-webdriver-element-not-visible-exception)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49342876

http://stackoverflow.com/q/49390221
score: 0
has comment: http://stackoverflow.com/comment/85792053
linked to: http://stackoverflow.com/q/49370552
answer count: 0
has comment: http://stackoverflow.com/comment/85783257
has body: My app.yaml file is as follows: runtime: python env: flex entrypoint: gunicorn -b :8443 main:app threadsafe: true runtime_config: python_version: 2 So, when I run this python script in GAE (of course, having deleted the previous webhook), the webhook doesn't get set up. I couldn't figure out what did I do wrong. import sys import os import time from flask import Flask, request import telegram # CONFIG TOKEN = '&lt;token&gt;' HOST = 'example.appspot.com' # Same FQDN used when generating SSL Cert PORT = 8443 CERT = "certificate.pem" CERT_KEY = "key.pem" bot = telegram.Bot(TOKEN) app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!' @app.route('/' + TOKEN, methods=['POST','GET']) def webhook(): update = telegram.Update.de_json( request.get_json(force = True), bot ) chat_id = update.message.chat.id bot.sendMessage(chat_id = chat_id, text = 'Hello, there') return 'OK' def setwebhook(): bot.setWebhook(url = "https://%s:%s/%s" % (HOST, PORT, TOKEN), certificate = open(CERT, 'rb')) if __name__ == '__main__': context = (CERT, CERT_KEY) setwebhook() time.sleep(5) app.run(host = '0.0.0.0', port = PORT, ssl_context = context, debug = True) I thought there might be an issue with SSL certificates, but if I just do this without running the python code, everything works out fine: curl -F "url=https://example.appspot.com:8443/&lt;token&gt;" -F "certificate=@certificate.pem" https://api.telegram.org/bot&lt;token&gt;/setWebhook
has title: Telegram bot API setWebhook not working with Google App Engine
type: Question
type: UnansweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/85782509
tagged with: python
tagged with: telegram-bot

http://stackoverflow.com/q/49356624
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49356803
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/49356803
has body: I'm getting two values from my dataframe .i.e. ('Passed',Failed'). Based on these values trying to build a pie chart. I like to display both values in legend even though the values are not present in my dataframe. Dataframe values are 'passed','failed' colors = ['green','red'] ax_3 = df_spark["Missing_records_check"].value_counts().sort_index(ascending=False).plt( kind='pie', y="Missing_records_check", figsize=(10, 10), legend=True, autopct='%1.1f%%', startangle=90, shadow=False, colors=['green','red'])
tagged with: matplotlib
has title: matplotlib legend display issue
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1
type: Question

http://stackoverflow.com/comment/85632546
score: 0
has text: Docs for `list.copy()`: Return a shallow copy of the list. Equivalent to `a[:]`]https://docs.python.org/3/tutorial/datastructures.html)
type: Comment
comment on: http://stackoverflow.com/a/49315354
type: AnswerComment

http://stackoverflow.com/q/49342660
downvote count: 0
tagged with: pip
tagged with: windows-10
has answer: http://stackoverflow.com/a/49342899
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29909330
type: UnansweredQuestion
tagged with: python
has title: Installing twisted on Windows 10 64 bit under python 2.7
has body: Does anyone know how to do this. I have googled and the best that I could come up with was to do: pip install autobahn[twisted] when I do that I get this error in the command window C:\Users\&lt;User Name&gt;\Desktop&gt;pip install autobahn[twisted] Collecting autobahn[twisted] c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. SNIMissingWarning c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Downloading autobahn-18.3.1-py2.py3-none-any.whl (283kB) 100% |################################| 286kB 1.0MB/s Collecting txaio&gt;=2.7.0 (from autobahn[twisted]) c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available.…
has comment: http://stackoverflow.com/comment/85708411
score: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85693445
upvote count: 2
tagged with: twisted
answer count: 1

http://stackoverflow.com/comment/129348267
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49284243
has text: https://docs.python.org/3/library/os.html#os.listdir listdir() doesn't include . or .. This code ignores the presence of hidden files, e.g. .gitignore, which is inconsistent with what I would call an empty directory.

http://stackoverflow.com/a/49331977
upvote count: 1
has body: So, as long as your data is well behaved, you could group your numbers into deques using a defaultdict: In [14]: from collections import defaultdict, deque In [15]: grouper = defaultdict(deque) In [16]: for a,b in L: ...: grouper[b].append(a) ...: Then simply: In [17]: grouper Out[17]: defaultdict(collections.deque, {'AMIE': deque([2]), 'JACK': deque([3]), 'JAYCE': deque([1, 5]), 'STEVE': deque([4])}) In [18]: [[grouper[x].popleft(), x] for x in sortedNames] Out[18]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']] I realize it is an ugly wart to use pop inside a list comprehension... Here's an approach using only dict and list: In [19]: grouper = {} ...: for a,b in L: ...: grouper.setdefault(b, []).append(a) ...: In [20]: grouper = {k:v[::-1] for k, v in grouper.items()} In [21]: [[grouper[x].pop(), x] for x in sortedNames] Out[21]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']] Both approaches are O(N). Edit I just realized that what you really want is instead of generating a list of sorted names, just sort L using a key directly: In [26]: L Out[26]: [[1, 'JAYCE'], [2, 'AMIE'], [3, 'JACK'], [4, 'STEVE'], [5, 'JAYCE']] In [27]: from operator import itemgetter In [28]: sorted(L, key=itemgetter(1)) Out[28]: [[2, 'AMIE'], [3, 'JACK'], [1, 'JAYCE'], [5, 'JAYCE'], [4, 'STEVE']]
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49331933
downvote count: 0

http://stackoverflow.com/comment/85813414
type: Comment
type: QuestionComment
has text: OMG. Simple as that, how can I not have thought about that. Thank you so much!
score: 0
comment on: http://stackoverflow.com/q/49406058

http://stackoverflow.com/comment/85814262
has text: Thank you! But Is it faster than the code in the question?
comment on: http://stackoverflow.com/a/49406419
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/120740297
type: QuestionComment
comment on: http://stackoverflow.com/q/49352930
has text: @abarnert I need exactly that use case (sharing python scripts to other Windows users that don't have Python installed), but I can't find any "portable virtualenv". Do you know any?
score: 0
type: Comment

http://stackoverflow.com/a/49455816
score: 0
answers question: http://stackoverflow.com/q/49392658
has body: I was able to solve this issue by using the following at the top of my batch file: set PYTHONPATH=Libraries
type: Answer

http://stackoverflow.com/q/49299609
tagged with: python
accepted answer: http://stackoverflow.com/a/54236136
downvote count: 1
has answer: http://stackoverflow.com/a/54236136
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49309258
tagged with: deep-learning
answer count: 3
has answer: http://stackoverflow.com/a/49598792
has answer: http://stackoverflow.com/a/49309258
score: 1
tagged with: seq2seq
tagged with: recurrent-neural-network
favorite count: 0
type: Question
has body: I want to tie weights of the embedding layer and the next_word prediction layer of the decoder. The embedding dimension is set to 300 and the hidden size of the decoder is set to 600. Vocabulary size of the target language in NMT is 50000, so embedding weight dimension is 50000 x 300 and weight of the linear layer which predicts the next word is 50000 x 600. So, how can I tie them? What will be the best approach to achieve weight tying in this scenario?
tagged with: pytorch
upvote count: 2
has title: Tying weights in neural machine translation

http://stackoverflow.com/comment/105640122
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49314256
has text: @SarfraazAhmed - Do you think `b = df.iloc[:3, 0].sum()` vs `b = df.iloc[0:3, 0].sum()` ? I think it is same ;)

http://stackoverflow.com/q/49320412
has comment: http://stackoverflow.com/comment/85643764
has comment: http://stackoverflow.com/comment/85642530
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85643891
has comment: http://stackoverflow.com/comment/85642355
answer count: 1
upvote count: 1
downvote count: 1
tagged with: parallel-processing
score: 0
has comment: http://stackoverflow.com/comment/85642306
has answer: http://stackoverflow.com/a/67619181
tagged with: opencl
has comment: http://stackoverflow.com/comment/85642149
has comment: http://stackoverflow.com/comment/85686994
has body: I am currently working on a project in java, that should run python tasks(small machine learning tasks) on several GPUs. Java should take a task and try to parallel it. I know I could use OpenCL\CUDA to do tasks on GPUs, and I could use several libraries to run Python code in Java. The only way I see now is writing Python code using PyCUDA and just run it from Java. But I don't sure if it's possible to parallel Python code on GPUs through Java. Cause just running script isn't the same as choosing particularly vector and matrix operations and run them on GPUs effectively. Is there any libraries to do that or is it impossible?
tagged with: java
has comment: http://stackoverflow.com/comment/85643959
tagged with: python
favorite count: 0
has title: Run Python code on GPUs from Java
type: Question

http://stackoverflow.com/a/49353443
has body: As @Wen said, pandas.Merge is the way I would approach this. For your problem it would look something like this df1 = pd.DataFrame([ ['a', '1:10'], ['a', '1:12'], ['b', '1:13'], ['c', '1:14'], ['d', '1:15'], ], columns=['id', 'time']) df2 = pd.DataFrame([ ['a', '1:11'], ['a', '1:13'], ['c', '1:14'], ], columns=['id', 'time']) df3 = df1.merge(df2, on='id', how='left') df3 after merge will look like this id time_x time_y 0 a 1:10 1:11 1 a 1:10 1:13 2 a 1:12 1:11 3 a 1:12 1:13 4 b 1:13 NaN 5 c 1:14 1:14 6 d 1:15 NaN pandas.merge works like SQL joins and for your example you would choose how='left' which is equivalent to a left-outer SQL join. We'll need to drop the rows that get duplicated to achieve your desired output. You can do this with pandas.drop_duplicates. The reset_index will just start the index count from zero again, it is optional. df4 = df3.drop_duplicates(subset=['id', 'time_x']).reset_index(drop=True) This will yield id time_x time_y 0 a 1:10 1:11 1 a 1:12 1:11 2 b 1:13 NaN 3 c 1:14 1:14 4 d 1:15 NaN
answers question: http://stackoverflow.com/q/49327771
type: Answer
score: 0

http://stackoverflow.com/a/49413754
type: Answer
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49342573
upvote count: 1
has body: Here is a method that I have found really useful when writing games in PyGame: if event.type == pygame.KEYDOWN if event.key == (pygame.K_RIGHT and pygame.K_LEFT): while True: # Infinite loop that will be broken when the user press the space bar again event = pygame.event.wait() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: # decid how to unpause? break #Exit infinite loop An interesting tid-bit I only recently discovered is that pygame.key.get_pressed() returns a tuple of 1s and 0s representing all of the keys on the keyboard, and these can be used as booleans or indexed to get the effective "value" of a key. Some great tuts at http://programarcadegames.com/

http://stackoverflow.com/comment/85751412
comment on: http://stackoverflow.com/a/49372952
type: Comment
has text: I am doing what you are suggesting here in my code. Things do not work. Could that be either because I'm using `Process` or because I'm using this in a class and import numpy separately in that class?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85706826
comment on: http://stackoverflow.com/q/49353242
score: 0
type: Comment
type: QuestionComment
has text: Did you check the browser's console for errors? In Chrome, for example, press F12 and click on "Console".

http://stackoverflow.com/comment/85643400
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49321095
type: QuestionComment
has text: [You shouldn't really have multiple instances of Tk](https://stackoverflow.com/q/48045401/7032856).

http://stackoverflow.com/a/51079959
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49395819
score: 2
has body: Had the same problem and fixed it by re-installing numpy with mkl (Intel's math kernel library) https://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy Download the right .whl for your machine. For me it was numpy‑1.14.5+mkl‑cp36‑cp36m‑win_amd64.whl (python 3.6, windows, 64-bit) and then install using pip. pip install numpy‑1.14.5+mkl‑cp36‑cp36m‑win_amd64.whl
type: Answer

http://stackoverflow.com/comment/85844939
has text: thanks for the update. This is similar to approach I am using. All comments and answers point to either external database or QSettings. I will try these alternatives to check it suitability.
comment on: http://stackoverflow.com/a/49407693
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49281173
type: Answer
has comment: http://stackoverflow.com/comment/85565063
score: 2
answers question: http://stackoverflow.com/q/49281051
has body: You have a few options here: 1) If you simply want to convert all upper-case letters to lower-case, then .lower() is the simplest approach. s = 'ThiS iS A PyTHon StrinG witH SomE CAPitaL LettErs' Gives: this is a python string with some capital letters 2) If you want to completely remove them, then re.sub() is a simple approach. import re print(re.sub(r'[A-Z]', '', s)) Gives: hi i yon trin wit om ita ettrs 3) For a list of strings, you could use a list comprehension: #Option1 [i.lower() for i in s]) #Option2 import re [re.sub(r'[A-Z]', '', i) for i in s]) #Option3 (as mentioned by @JohnColeman) [''.join([j for j in i if not j.isupper()]) for i in s]
downvote count: 0
has comment: http://stackoverflow.com/comment/85567256
has comment: http://stackoverflow.com/comment/85565017
upvote count: 2

http://stackoverflow.com/q/49329183
accepted answer: http://stackoverflow.com/a/49329249
has answer: http://stackoverflow.com/a/49329249
answer count: 1
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/20625582
has title: SettingWithCopyWarning with .loc
tagged with: copy
type: Question
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: This code produces the SettingWithCopyWarning as follows: raw_corpus.loc[:,'constructed_recipe']=raw_corpus.loc[:,'trigger_channel_cat'] + " " + raw_corpus.loc[:,'trigger_channel_clean'] + " " + raw_corpus.loc[:,'trigger_name_clean'] + " " + raw_corpus.loc[:,'action_name_clean'] +" " + raw_corpus.loc[:,'action_channel_clean'] +" " + raw_corpus.loc[:,'action_channel_cat'] /Users/dlhoffman/anaconda3/envs/gensim-py35/lib/python3.5/site-packages/pandas/core/indexing.py:537: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s This code produces a different warning: raw_corpus['constructed_recipe']=raw_corpus['trigger_channel_cat'] + " " + raw_corpus['trigger_channel_clean'] + " " + raw_corpus['trigger_name_clean'] + " " + raw_corpus['action_name_clean'] +" " + raw_corpus['action_channel_clean'] +" " + raw_corpus['action_channel_cat'] /Users/dlhoffman/anaconda3/envs/gensim-py35/lib/python3.5/site-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """ Both pieces of code do what I want, but the error is annoying and it's my understanding that this is not a good error. I've read up on the documentation and also people's suggestions here, but can't figure out what I am doing wrong.
tagged with: warnings
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85660434
favorite count: 0
linked to: http://stackoverflow.com/q/20625582

http://stackoverflow.com/a/78857035
answers question: http://stackoverflow.com/q/49419682
has body: For the follow-up question to the bit array approach: assuming you're using bit operations and not a python list of booleans, you can find a free ID in O(log n) using a binary search. In each iteration mask the bit array with a sequence of ones in the interval you're examining and compare the result to the mask. If they're unequal you've found a sequence containing a free ID.
type: Answer
score: 0

http://stackoverflow.com/a/49630915
answers question: http://stackoverflow.com/q/49384696
score: 1
type: AcceptedAnswer
has body: In case some other bit of your code expected your score arrays to maintain their size. I wouldn't expect this to be common. In most cases you just take a mean of the result.
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49384696

http://stackoverflow.com/comment/85659781
type: QuestionComment
score: 0
has text: because in python 5 is an object and variables don't "store" objects they just "refer" to them. b = 5 means b is neither holding a copy of 5 nor 5 itself rather that b now refers to the object 5.
type: Comment
comment on: http://stackoverflow.com/q/49328869

http://stackoverflow.com/a/54170237
type: Answer
score: 4
has body: I had the same problem. You must make the keys in the dictionary config in quotes and then everything will work fine. P.S: Do not forget to put in quotes and other keys. For example: config = { "apiKey": "xxxxxxxxxxxxxxxxx", "authDomain": "lab-marks.firebaseapp.com", "databaseURL": "https://lab-marks.firebaseio.com", "projectId": "lab-marks", "storageBucket": "lab-marks.appspot.com", "messagingSenderId": "9983241061112" }
answers question: http://stackoverflow.com/q/49280929
downvote count: 0
upvote count: 4

http://stackoverflow.com/q/49291593
linked to: http://stackoverflow.com/q/35491274
answer count: 2
accepted answer: http://stackoverflow.com/a/49291743
has answer: http://stackoverflow.com/a/49291746
has title: Best way to tidy DataFrame with list in column
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49291743
has comment: http://stackoverflow.com/comment/85585966
has comment: http://stackoverflow.com/comment/85585963
has body: I have an untidy DataFrame of Tweet objects. There are two columns that contain lists: hashtags and expanded_urls. I'm trying to follow tidy data principles by keeping only 1 value at a row/column index. EDIT: This question was marked as a duplicate of this answer, which simply splits the list into more columns. That doesn't work for me because there could be a variable number of hashtags in 1 tweet. Here's a sample of my tweet DataFrame: ----------------------------------------------------------- tweet_id | hashtags | expanded_urls ----------------------------------------------------------- 123 | ['lol','bff'] | ['fakeurl.com'] 124 | [] | ['url1.io', 'url2.expanded.co'] There's two possible ways I could go about tidying this data. 1: Simply add new rows to the DataFrame with almost all row contents copied over: --------------------------------------------- tweet_id | hashtag | expanded_url --------------------------------------------- 123 | 'lol' | 'fakeurl.com' 123 | 'bff' | 'fakeurl.com' 124 | '' | 'url1.io' 124 | '' | 'url2.expanded.io' I don't think this would be very efficient, especially because there would be many insert/append operations. However, having a single DataFrame to pass into a single scikit-learn model would make things very simple. 2: Create 2 new DataFrames: The first would be hashtags with their corresponding tweet_ids: ------------------ tweet_id | hashtag ------------------ 123 | `lol` 123 | `bff` The other would be urls with their corresponding tweet_ids: ------------------ tweet_id | url ------------------ 123 | `fakeurl.com` 124 | `url1.io` 124 | `url2.expanded.co` This seems cleaner, but I'm not entirely sure how I would modify the original DataFrame; would I just drop the corresponding columns and keep 3 separate tables? Is there a good way of merging these 3 DataFrames into 1, or would I have to do a separate lookup every time I wanted to know which hashtags are associated with a tweet?
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49291746
tagged with: pandas
upvote count: 3
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85682236
has text: You probably sohuld use a better data format. If `id`s are unique, put the OrderedDicts in a dict.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49340714

pipeline
type: Tag
tags question: http://stackoverflow.com/q/49399851
tags question: http://stackoverflow.com/q/49390202
tag name: pipeline
tags question: http://stackoverflow.com/q/49336063

http://stackoverflow.com/a/78236591
type: Answer
upvote count: 2
score: 2
has body: The watchmedo/watchdog command that gets closest to nodemons behaviour might be: watchmedo auto-restart \ --patterns="*.py" \ --recursive \ --no-restart-on-command-exit \ --debounce-interval 0.1 \ foo/bar.py as shell-command didn't initially start the process, but auto-restart did. --debounce-interval was required to avoid OSError: [Errno 26] Text file busy errors when files are changed. Make sure the python file (bar.py in this example) has the correct shebang: #!/usr/bin/env python3. Using env in the shebang makes it work with poetry and the likes.
downvote count: 0
answers question: http://stackoverflow.com/q/49355010

httpconnection
tag name: httpconnection
tags question: http://stackoverflow.com/q/49402097
type: Tag

http://stackoverflow.com/q/49411957
has body: is there a preexisting function to serialize a set of integers in a efficient and compact form using the 'bitmap' data structure? I am aware of pickle. but it seems it serializes to a verbose string. I need something that will use as little space as possible
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85825699
accepted answer: http://stackoverflow.com/a/49414809
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49414809
score: 0
has comment: http://stackoverflow.com/comment/85826192
answer count: 1
has title: In python efficiently serialize set of integers

http://stackoverflow.com/comment/85572822
type: Comment
has text: Use `os.startfile()` just with the file, without the application.
type: QuestionComment
comment on: http://stackoverflow.com/q/49284933
score: 0

http://stackoverflow.com/a/49324873
has body: restrict_xpaths defines a section of the html file, no the actual links, so //a is exactly what you DON'T need to put there.
type: Answer
answers question: http://stackoverflow.com/q/49324798
has comment: http://stackoverflow.com/comment/85665310
score: 0

http://stackoverflow.com/comment/85710161
has text: No. That is not at all what I meant.
type: Comment
comment on: http://stackoverflow.com/q/49354814
type: QuestionComment
score: 0

http://stackoverflow.com/a/49317156
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85645332
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85644774
has comment: http://stackoverflow.com/comment/85636528
has comment: http://stackoverflow.com/comment/85636944
accepted answer of: http://stackoverflow.com/q/49316812
has comment: http://stackoverflow.com/comment/85719430
has body: I think need reindex by new index created by split Date to MultiIndex and map with join: df = df.set_index('Date') idx =(pd.MultiIndex.from_product(df.index.str.split(',', expand=True).levels) .map(','.join)) df = df.reindex(idx, fill_value=0).rename_axis('Date').reset_index() print (df.head()) Date Churn Churnrate customerID 0 2008,01 726.0 0.542398 2763 1 2008,02 345.0 0.257751 1351 2 2008,03 0.0 0.000000 0 3 2008,04 0.0 0.000000 0 4 2008,05 0.0 0.000000 0 EDIT: Solution with define all Months by range(1,13) df = df.set_index('Months') years = df.index.str.split('/', expand=True).levels[0] idx = (pd.MultiIndex.from_product([years, pd.Series(range(1, 13)).astype(str).str.zfill(2)]) .map('/'.join)) df = df.reindex(idx, fill_value=0).rename_axis('Date').reset_index() print (df) Date Retention_Rate Customer_Count 0 2008/01 0.145916 133 1 2008/02 0.924663 762 2 2008/03 0.074544 67 3 2008/04 0.000000 0 4 2008/05 0.000000 0 5 2008/06 0.000000 0 6 2008/07 0.000000 0 7 2008/08 0.000000 0 8 2008/09 0.000000 0 9 2008/10 0.000000 0 10 2008/11 0.000000 0 11 2008/12 0.000000 0 12 2014/01 0.000000 0 13 2014/02 0.000000 0 14 2014/03 0.000000 0 15 2014/04 0.000000 0 16 2014/05 0.000000 0 17 2014/06 0.000000 0 18 2014/07 0.058684 45 19 2014/08 0.069786 61 20 2014/09 0.076130 64 21 2014/10 0.061856 60 22 2014/11 0.082474 69 23 2014/12 0.000000 0 If need replace the missing year and the corresponding columns with zeros: print (df) Year Churn_Count Churn_Rate Customer_Count 2008 1071.0 0.800149 4114 2012 0.0 0.000000 6 2013 233.0 0.174075 824 2014 101.0 0.075458 410 Then use: df1 = (df.set_index('Year') .reindex(range(2008, 2015), fill_value=0) .reset_index()) print (df1) Year Churn_Count Churn_Rate Customer_Count 0 2008 1071.0 0.800149 4114 1 2009 0.0 0.000000 0 2 2010 0.0 0.000000 0 3 2011 0.0 0.000000 0 4 2012 0.0 0.000000 6 5 2013 233.0 0.174075 824 6 2014 101.0 0.075458 410 More dynamic solution for reindex by min and max year: df1 = df.set_index('Year') df1 = (df1.reindex(range(…
has comment: http://stackoverflow.com/comment/85636563
has comment: http://stackoverflow.com/comment/85715223
type: Answer
answers question: http://stackoverflow.com/q/49316812
has comment: http://stackoverflow.com/comment/85667352
has comment: http://stackoverflow.com/comment/85826479
has comment: http://stackoverflow.com/comment/85636602
has comment: http://stackoverflow.com/comment/85644722
has comment: http://stackoverflow.com/comment/85719071
has comment: http://stackoverflow.com/comment/85720533
has comment: http://stackoverflow.com/comment/85719020
has comment: http://stackoverflow.com/comment/85715467
has comment: http://stackoverflow.com/comment/85645287
has comment: http://stackoverflow.com/comment/85715508

http://stackoverflow.com/comment/85690112
comment on: http://stackoverflow.com/q/49345012
has text: What do `type(self.imgData[0])` and `np.shape(self.imgData[0])` return?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49327363
has title: Improving MySQLdb load data infile performance
has comment: http://stackoverflow.com/comment/86005369
has comment: http://stackoverflow.com/comment/85657053
has comment: http://stackoverflow.com/comment/86046720
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86047247
has comment: http://stackoverflow.com/comment/86005406
tagged with: mysql-python
has comment: http://stackoverflow.com/comment/86005472
has comment: http://stackoverflow.com/comment/85661101
tagged with: python
has comment: http://stackoverflow.com/comment/86013058
has answer: http://stackoverflow.com/a/49330027
has comment: http://stackoverflow.com/comment/86005341
type: AnsweredQuestion
tagged with: innodb
has body: I have a table that's roughly defined as follows in InnoDB: create table `my_table` ( `time` int(10) unsigned not null, `key1` int(10) unsigned not null, `key3` char(3) unsigned not null, `key2` char(2) unsigned not null, `value1` float default null, `value2` float default null, primary key (`key1`, `key2`, `key3`, `time`), key (`key3`, `key2`, `key1`, `time`) ) engine=InnoDB default character set ascii partition by range(time) ( partition start values less than (0), partition from20180101 values less than (unix_timestamp('2018-02-01')), partition from20180201 values less than (unix_timestamp('2018-03-01')), ..., partition future values less than MAX_VALUE ) Yes, the column order doesn't match the key order. In Python I'm populating a DataFrame with 500,000 rows (this is probably not the most efficient way to do this, but serves as a sample for what the data may look like): import random import pandas as pd key2_values = ["aaa", "bbb", ..., "ttt"] # 20 distinct values key3_values = ["aa", "ab", "ac", ..., "az", "bb", "bc", ..., "by"] # 50 distinct values df = pd.DataFrame([], columns=["key1", "key2", "key3", "value2", "value1"]) idx = 0 for x in range(0, 500): for y in range(0, 20): for z in range(0, 50): df.loc[idx] = [x, key2_values[y], key3_values[z], random.random(), random.random()] idx += 1 df.set_index(["key1", "key2", "key3"], inplace=True) (In reality this DataFrame is populated from several API calls and a lot of math, but the end result is the same: a huge DataFrame with ~500,000 rows and keys matching the InnoDB table) To import this DataFrame into the table, I'm currently doing the following: import time import MySQLdb conn = MySQLdb.connect(local_infile=1, **connection_params) cur = conn.cursor() # Disable data integrity checks -- I know the data is good cur.execute("SET foreign_key_checks=0;") cur.execute("SET unique_checks=0;") # Append current time to the DataFrame df["time"] = time.time() df.set_index(["time"], append=True, inplace=True) # Sort dat…
downvote count: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85660954
has comment: http://stackoverflow.com/comment/86032634
has comment: http://stackoverflow.com/comment/85657242
favorite count: 0
accepted answer: http://stackoverflow.com/a/49330027
type: Question

http://stackoverflow.com/a/49423857
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49423429
downvote count: 0
answers question: http://stackoverflow.com/q/49423429
type: Answer
score: 4
has body: You can use getattr: &gt;&gt;&gt; getattr(spam, 'test.this') True Alternatively, you can get the value from the object's __dict__. Use vars to get spam's dict: &gt;&gt;&gt; vars(spam)['test.this'] True
upvote count: 4

http://stackoverflow.com/comment/85652132
has text: Show some actual code, what you expect, and what you get, otherwise we can only guess
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49325329

http://stackoverflow.com/a/49324811
accepted answer of: http://stackoverflow.com/q/49324021
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49324021
has body: You're missing a few of the basics of python. First of all, if you find you're writing many functions that do the same thing, you can and should just write that as one function. Second, and this is where your issue is arising, you aren't returning any data in your functions. It is printing out your results, as print doesn't need to be returned to work, but when you try to write those functions to a csv, since they aren't returning anything, it's just writing that function. These edits to your code address my above points: time.sleep(5) data = [] def get_data(id) time.sleep(1) element=driver.find_element_by_id(id) print("Space: Lower Hall","\nTemperature: ", element.text) temperature = element.text when_updated=driver.find_element_by_name("_lastUpdated") timestamp=when_updated.get_attribute("value") print("Timestamp:", timestamp) print("") #space out on cmd line return temperature, when_updated, timestamp data.append(get_data("root.content.BoundLabel12")) data.append(get_data("root.content.BoundLabel1")) data.append(get_data("root.content.BoundLabel33")) time.sleep(60) with open('writer.csv', 'a') as file: writer = csv.writer(file) for d in data: writer.writerows(d) nos=1 # Number of samples freq=25 # Sampling frequency print("\nTemperature &amp; timestamp, sampled every", freq, "seconds:") while True: #for i in range(nos): ts=driver.find_element_by_name("_lastUpdated").get_attribute("value") #print("\nTemperature: ", element.text, "read at:", ts) time.sleep(freq) driver.switch_to_default_content() print ("Done.") I would recommend giving this a read if you're new to python: https://www.tutorialspoint.com/python/python_functions.htm
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85824628
type: QuestionComment
score: 0
has text: Yeah, my bad. Became little lazy :D
comment on: http://stackoverflow.com/q/49411406
type: Comment

http://stackoverflow.com/q/49296665
has answer: http://stackoverflow.com/a/56970568
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49297283
answer count: 5
linked to: http://stackoverflow.com/q/42138681
has comment: http://stackoverflow.com/comment/85596233
has body: I have an unknown number n of variables that can range from 0 to 1 with some known step s, with the condition that they sum up to 1. I want to create a matrix of all combinations. For example, if n=3 and s=0.33333 then the grid will be (The order is not important): 0.00, 0.00, 1.00 0.00, 0.33, 0.67 0.00, 0.67, 0.33 0.00, 1.00, 0.00 0.33, 0.00, 0.67 0.33, 0.33, 0.33 0.33, 0.67, 0.00 0.67, 0.00, 0.33 0.67, 0.33, 0.00 1.00, 0.00, 0.00 How can I do that for an arbitrary n?
has answer: http://stackoverflow.com/a/49297497
tagged with: python
has title: n dimensional grid in Python / numpy
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49297090
possible better answer: http://stackoverflow.com/a/49298319
accepted answer: http://stackoverflow.com/a/49297090
has comment: http://stackoverflow.com/comment/85604578
has answer: http://stackoverflow.com/a/49298319

http://stackoverflow.com/q/49434777
tagged with: python
has comment: http://stackoverflow.com/comment/85871415
downvote count: 1
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/49435034
answer count: 5
has answer: http://stackoverflow.com/a/49439925
has answer: http://stackoverflow.com/a/49435145
has comment: http://stackoverflow.com/comment/85871660
has body: This code is supposed to iterate over the list of lists and return the entire list that contains the smallest value. I have already identified that it keeps returning the list at index[0], but I cannot figure out why. Any help, or even hints, would be greatly appreciated. def list_with_min(list_of_lists): m = 0 for i in range(len(list_of_lists)-1): list_i = list_of_lists[m] min_list = min(list_of_lists[m]) if min_list &lt; list_i[0]: m = i answer = list_of_lists[m] return answer print(list_with_min([[9, 10, 15], [1, 8, 4], [-3, 7, 8]])) # [9, 10, 15]--------&gt; should be [-3, 7, 8] print(list_with_min([[5], [9], [6], [2], [7], [10], [72]])) # [5]----------------&gt; should be [2] print(list_with_min([[-2, 6, 9], [-9, 6, 9], [4, 8, 2], [5, -2]])) # [-2, 6, 9]---------&gt; should be [[-2, 6, 9], [5, -2]] (I assume two lists with the same minimum value should both be returned?)
has answer: http://stackoverflow.com/a/49434986
type: Question
has title: Finding a minimum value in a list of lists and returning that list
has answer: http://stackoverflow.com/a/49434996
upvote count: 3
has comment: http://stackoverflow.com/comment/85871551
type: UnansweredQuestion

http://stackoverflow.com/comment/85640874
score: 0
has text: hi, it's enough if it's the first one. I just remembered that it is enough to get lists of "similar" ones. But they should only not appear in 2 lists.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49319933

http://stackoverflow.com/comment/85706925
comment on: http://stackoverflow.com/q/49353337
type: Comment
has text: What's the error you're getting? Include the traceback in your question.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49344754
has body: Create a dict out of the label and something and then do the json.dumps() Simple example - import json label = 'productTypes' something = ["APPLE","BANANA"] print(json.dumps({label: something})) Output {"productTypes": ["APPLE", "BANANA"]} So in you case, declare a dict for label and something. Something like - for x in range(1,n) label = (df.columns[x]).strip() something = (df[df.columns[x]][i]) print (label) print (something) value = json.dumps({label: something})
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49344723
accepted answer of: http://stackoverflow.com/q/49344723
type: Answer

http://stackoverflow.com/q/49323237
accepted answer: http://stackoverflow.com/a/49384785
answer count: 1
tagged with: google-bigquery
type: Question
has title: Method to_gbq() in pandas-gbq library strips milliseconds and seconds part of datetime field
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm using version 0.3.1. The simplest way to reproduce: import pandas as pd, pandas_gbq data = {"date": datetime.datetime.now()} # 2018-03-16 16:09:03.230384 df = pd.DataFrame(data, index=[0] destination_table = 'test_tables.test_datetime' project_id = 'my-project-11111' private_key = 'path-to-key.json' pandas_gbq.to_gbq( df, destination_table, project_id, private_key=private_key ) When I go to check the values in the created table in Google BigQuery, the value doesn't keep seconds and milliseconds part of the DateTime: 2018-03-16 16:09:00.000 UTC The documentation doesn't say anything about this behavior, so I assume this is a bug. But maybe I'm missing something here?
tagged with: pandas
has answer: http://stackoverflow.com/a/49384785

http://stackoverflow.com/q/49305602
answer count: 0
type: UnansweredQuestion
has title: Inserting Empty value and number in a row postgresql
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85613899
tagged with: postgresql
has comment: http://stackoverflow.com/comment/85613681
score: 1
has body: I have a column, lets take A, A can be sometimes '5' which is a string number A can also be ' ' which is empty string I want to insert this kind of scenario data in my postgresql table I tried when a = '5' int(a or ' ') --- > It is getting inserted as 5 But When a = ' ' int(a or ' ') --- > Its not able insert empty string I know integer can't be empty. Also i tried to use COALESCE(NULLIF(a,' ')) --> it says coalesce is not defined. I want both the conditions to get satisfied to insert the data if its present , if not insert empty for the column in postgres Thanks in Advance.
tagged with: python
type: Question

http://stackoverflow.com/comment/85624806
score: 0
has text: And what Python version is `virtualenv` itself installed in, the system Python or a different Python installation? Where do the `lib/python2.7/` links point to?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49311329

http://stackoverflow.com/a/49350469
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85700883
upvote count: 1
has comment: http://stackoverflow.com/comment/85700675
accepted answer of: http://stackoverflow.com/q/49350370
has comment: http://stackoverflow.com/comment/85700990
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49350370
has comment: http://stackoverflow.com/comment/85748552
has comment: http://stackoverflow.com/comment/85700727
has body: If I understand correctly, something like this should work: file = r'Alpha.csv' meta = pd.read_csv(file, nrows=4, header=None) df = pd.read_csv(file, skiprows=4) uncommon = df.loc[(df['Temp'] &gt;= 100)] with open('Dummy.csv', 'w') as out: meta.to_csv(out, index=False, header=False) uncommon.to_csv(out, sep='\t', index=False) Explanation Read in your meta data into meta and actual data into data dataframes. Perform your manipulations on data and assign to uncommon. Write meta and uncommon separately to a csv file via Python's in-built open function. Alternative workflow But my preference would be to keep your data clean. Why not, for example, store a table separately with your metadata linking to filenames? Your current method will prevent you from doing any meaningful analysis with the Metadata.
has comment: http://stackoverflow.com/comment/85700926
has comment: http://stackoverflow.com/comment/85748528

http://stackoverflow.com/comment/85845663
score: 0
type: AnswerComment
has text: thank you and how can I get the src inside the img class ?
type: Comment
comment on: http://stackoverflow.com/a/49422303

http://stackoverflow.com/q/49396943
tagged with: dictionary
has answer: http://stackoverflow.com/a/49399169
upvote count: 2
type: AnsweredQuestion
tagged with: list
answer count: 3
has title: Grouping values in lists from dictionary to create new dictionary with group number for each value using Python?
score: 1
accepted answer: http://stackoverflow.com/a/49397534
has answer: http://stackoverflow.com/a/49417561
downvote count: 1
tagged with: grouping
has body: In the picture below are three groups of touching squares where each individual square is numbered. I have been able to use the spatial library ArcPy to construct the dictionary below which uses the square numbers as its keys and a list of numbers for the squares it touches as its values. For example, square 1 touches only square 4, square 4 touches squares 1 and 6, etc. dict = {1: [4], 2: [3, 5], 3: [2, 5], 4: [1, 6], 5: [2, 3], 6: [4, 8], 7: [9, 10], 8: [6, 11], 9: [7, 10], 10: [7, 9], 11: [8]} From the picture it is clear that there are three groups of touching squares, and so the result I am after is a new dictionary where the keys are the square numbers and the values are the touching group it belongs to. I'll name the touching groups using letters but these names can be anything so one possible solution would be: newDict = {9:"A",10:"A",7:"A",1:"B",4:"B",6:"B",8:"B",11:"B",5:"C",2:"C",3:"C"} Is there a Pythonic way to go from dict to newDict? I am using Python 2.7.14 for my testing.
favorite count: 0
has comment: http://stackoverflow.com/comment/85795874
possible better answer: http://stackoverflow.com/a/49399169
type: Question
has comment: http://stackoverflow.com/comment/85795898
has answer: http://stackoverflow.com/a/49397534
linked to: http://stackoverflow.com/q/17450521
tagged with: python

http://stackoverflow.com/q/49372995
score: 2
has body: I'm new with Pyhton and would like to filter a dictionary with keys composed by two values. Here my dict: {(0, 'DRYER'): [103.0, 131.0, 9.0, 1.24], (2, 'DRYER'): [106.0, 120.0, 5.0, 1.24], (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]} The keys are composed by two values (n,a) and I want to create a new dictionary where n=2, which results in: {(2, 'DRYER'): [106.0, 120.0, 5.0, 1.24], (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]} If anyone could help, I would be thankful!
type: AnsweredQuestion
answer count: 2
tagged with: filter
upvote count: 2
has title: Filter a dictionary using one of multiple keys
has comment: http://stackoverflow.com/comment/85747338
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/30636279
accepted answer: http://stackoverflow.com/a/49373052
has answer: http://stackoverflow.com/a/49373052
possible better answer: http://stackoverflow.com/a/49373143
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/30636279
has answer: http://stackoverflow.com/a/49373143

http://stackoverflow.com/a/49596258
downvote count: 1
answers question: http://stackoverflow.com/q/49373721
has comment: http://stackoverflow.com/comment/112795799
type: Answer
has comment: http://stackoverflow.com/comment/86204320
score: 2
has body: Check out Ray Tune! You can use it for multiprocessing and multi-machine executions of random search, grid search, and evolutionary methods. It also has implementations of popular algorithms such as HyperBand. Here's the docs page - ray.readthedocs.io/en/latest/tune.html As an example to run 4 parallel experiments at a time: import ray import ray.tune as tune def my_func(config, reporter): # add the reporter parameter import time, numpy as np i = 0 while True: reporter(timesteps_total=i, mean_accuracy=i ** config["alpha"]) i += 1 time.sleep(.01) tune.register_trainable("my_func", my_func) ray.init(num_cpus=4) tune.run_experiments({ "my_experiment": { "run": "my_func", "stop": { "mean_accuracy": 100 }, "config": { "alpha": tune.grid_search([0.2, 0.4, 0.6]), "beta": tune.grid_search([1, 2]) } } }) Disclaimer: I work on this project - let me know if you have any feedback!
upvote count: 3

http://stackoverflow.com/comment/85662259
has text: It seems to do the same operation, but it may not allow scalars in for the second and third arguments. They may need to be tensors of the same rank as the first argument. I've never used it.
type: Comment
comment on: http://stackoverflow.com/a/49329752
type: AnswerComment
score: 0

regex
tags question: http://stackoverflow.com/q/49415176
tags question: http://stackoverflow.com/q/49325509
tags question: http://stackoverflow.com/q/49342183
tags question: http://stackoverflow.com/q/49434760
tags question: http://stackoverflow.com/q/49305425
tags question: http://stackoverflow.com/q/49420276
tags question: http://stackoverflow.com/q/49394017
tags question: http://stackoverflow.com/q/49415900
tags question: http://stackoverflow.com/q/49371947
tags question: http://stackoverflow.com/q/49349079
tags question: http://stackoverflow.com/q/49332536
tags question: http://stackoverflow.com/q/49419221
tags question: http://stackoverflow.com/q/49399090
tags question: http://stackoverflow.com/q/49337738
tags question: http://stackoverflow.com/q/49430262
tags question: http://stackoverflow.com/q/49321785
tags question: http://stackoverflow.com/q/49439828
tags question: http://stackoverflow.com/q/49364578
tags question: http://stackoverflow.com/q/49305436
tags question: http://stackoverflow.com/q/49435907
tags question: http://stackoverflow.com/q/49369657
tags question: http://stackoverflow.com/q/49434120
tags question: http://stackoverflow.com/q/49406910
tags question: http://stackoverflow.com/q/49417978
tags question: http://stackoverflow.com/q/49341960
tags question: http://stackoverflow.com/q/49351273
tags question: http://stackoverflow.com/q/49425537
tags question: http://stackoverflow.com/q/49395883
tags question: http://stackoverflow.com/q/49298516
tag name: regex
tags question: http://stackoverflow.com/q/49318551
tags question: http://stackoverflow.com/q/49351190
tags question: http://stackoverflow.com/q/49381574
tags question: http://stackoverflow.com/q/49399374
tags question: http://stackoverflow.com/q/49320913
tags question: http://stackoverflow.com/q/49326885
tags question: http://stackoverflow.com/q/49401845
tags question: http://stackoverflow.com/q/49322577
tags question: http://stackoverflow.com/q/49364531
tags question: http://stackoverflow.com/q/49361612
tags question: http://stackoverflow.com/q/49386824
tags question: http://stackoverflow.com/q/49306166
tags question: http://stackoverflow.com/q/49393705
tags question: http://stackoverflow.com/q/49330438
tags question: http://stackoverflow.com/q/49395701
tags question: http://stackoverflow.com/q/49381154
tags question: http://stackoverflow.com/q/49337715
tags question: http://stackoverflow.com/q/49323896
tags question: http://stackoverflow.com/q/49376818
tags question: http://stackoverflow.com/q/49353595
tags question: http://stackoverflow.com/q/49359359
tags question: http://stackoverflow.com/q/49407810
tags question: http://stackoverflow.com/q/49382372
tags question: http://stackoverflow.com/q/49333206
tags question: http://stackoverflow.com/q/49322409
tags question: http://stackoverflow.com/q/49362719
tags question: http://stackoverflow.com/q/49333036
tags question: http://stackoverflow.com/q/49288580
tags question: http://stackoverflow.com/q/49384478
tags question: http://stackoverflow.com/q/49419797
tags question: http://stackoverflow.com/q/49412295
tags question: http://stackoverflow.com/q/49308813
tags question: http://stackoverflow.com/q/49301501
tags question: http://stackoverflow.com/q/49416476
tags question: http://stackoverflow.com/q/49323028
tags question: http://stackoverflow.com/q/49309012
tags question: http://stackoverflow.com/q/49313024
tags question: http://stackoverflow.com/q/49281748
tags question: http://stackoverflow.com/q/49308201
tags question: http://stackoverflow.com/q/49399686
tags question: http://stackoverflow.com/q/49308645
tags question: http://stackoverflow.com/q/49339739
tags question: http://stackoverflow.com/q/49396531
type: Tag
tags question: http://stackoverflow.com/q/49292068

http://stackoverflow.com/a/49332229
score: 1
has comment: http://stackoverflow.com/comment/85683768
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49290546
type: Answer
answers question: http://stackoverflow.com/q/49290546
has comment: http://stackoverflow.com/comment/85707061
has body: Looking over your dag I think you've implemented a non-idempotent process that airflow is not really configured for. Instead of truncating/updating the table that you're building, you should probably be leaving the tasks configured and updating only the start_date/end_date to enable and disable them for scheduling at the task level, or even run all of them every iteration and in your script check the table to just run a hello world if the job is disabled.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49347498
score: 0
has title: Clicking on a non-visible button is Selenium
has body: I'm trying to click on a button that is only visible when hovering over it. move_to_element doesn't seem to work and I get this error when trying to click ElementNotVisibleException: Message: element not visible My code is: full_screen_elem = driver.find_element_by_xpath( '//*[@id="grid"]/div[2]/div[1]/article/div[3]/a') hover = ActionChains(driver).move_to_element(full_screen_elem) hover.perform() full_screen_elem.click() I've also tried this: driver.execute_script('arguments[0].click();', full_screen_elem) But it also doesn't work. What else can I try?
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85696256
type: Question
has answer: http://stackoverflow.com/a/49348817
has comment: http://stackoverflow.com/comment/85694812
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver

http://stackoverflow.com/q/49419486
downvote count: 0
has answer: http://stackoverflow.com/a/70920368
has answer: http://stackoverflow.com/a/49419880
linked to: http://stackoverflow.com/q/9323749
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49419813
score: 2
has title: Recursive function to check dictionary is a subset of another dictionary
has body: I'd like to check whether a dictionary is a subset of another dictionary recursively. Let's assume both dictionaries having builtin types as items. I've seen there is already a very old thread Python: Check if one dictionary is a subset of another larger dictionary trying to solve something similar but not quite... Because none of the answers living there will serve for my purposes I've decided to post my own solution in there but it is still not fully complete, the below function is working ok for almost all cases but it fails miserably in cases when the subset has values that don't exist in the superset, ie: def is_subset(superset, subset): for key, value in superset.items(): if key not in subset: continue if isinstance(value, dict): if not is_subset(value, subset[key]): return False elif isinstance(value, str): if not subset[key] in value: return False elif isinstance(value, list): if not set(subset[key]) &lt;= set(value): return False elif isinstance(value, set): if not subset[key] &lt;= value: return False else: if not subset[key] == value: return False return True superset = {'question': 'mcve', 'metadata': {}} subset = {'question': 'mcve', 'metadata': {'author': 'BPL'}} print(is_subset(superset, subset)) The function returns True but it should return False. So, how would you fix it?
has comment: http://stackoverflow.com/comment/85841012
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49419880
favorite count: 0
has answer: http://stackoverflow.com/a/57675198
possible better answer: http://stackoverflow.com/a/57675198
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85841099
has answer: http://stackoverflow.com/a/77713542
answer count: 5

http://stackoverflow.com/a/49346236
has body: Try below XPath to get required output: //p[2]//a[not(parent::i)]
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49343677
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49343677

http://stackoverflow.com/comment/85709766
has text: what do you mean? In what case would with `[:]` be different to without `[:]`?
type: Comment
comment on: http://stackoverflow.com/a/49354696
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85856802
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49427151
score: 2
has text: Possible duplicate of [When does python compile the constant string letters, to combine the constant strings to one constant string](https://stackoverflow.com/questions/14493236/when-does-python-compile-the-constant-string-letters-to-combine-the-constant-st)

http://stackoverflow.com/comment/85838325
type: AnswerComment
has text: @abarnert: `xrange` added.
comment on: http://stackoverflow.com/a/49418230
type: Comment
score: 0

http://stackoverflow.com/a/49381333
answers question: http://stackoverflow.com/q/49381271
has body: Here is a simple exemple of how to specify and catch your request types. You can choose the access route for your function, as well as the methods usable with the route. Once inside your function, you can catch the request.method type, and handle your case from there. from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': do_the_login() elif request.method == 'GET': get_user_info() else: print("Unsupported request")
score: 0
type: Answer

http://stackoverflow.com/comment/85667325
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49316150
has text: self.extLeft = tuple(c[c[:, :, 0].argmin()][0])
type: Comment

http://stackoverflow.com/q/49312775
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have two DataFrames DF1 and DF2, and I want to aggregate the values of one column in DF1 under the date ranges of a column in DF2. Here is my reproducible example: DF1 ranges from 6/14/2013 to 7/13/2013, and is sorted descending in time. Its columns to be aggregated are a and b. Notice, there can be multiple records for the same date. list1 = [{'a': 5, 'date': '7/13/2013', 'b': 13}, {'a': 4, 'date': '7/12/2013', 'b': 14}, {'a': 7, 'date': '7/12/2013', 'b': 12}, {'a': 2, 'date': '7/10/2013', 'b': 18}, {'a': 9, 'date': '7/7/2013', 'b': 17}, {'a': 6, 'date': '7/5/2013', 'b': 20}, {'a': 8, 'date': '6/30/2013', 'b': 12}, {'a': 5, 'date': '6/29/2013', 'b': 13}, {'a': 3, 'date': '6/25/2013', 'b': 13}, {'a': 4, 'date': '6/23/2013', 'b': 10}, {'a': 1, 'date': '6/22/2013', 'b': 16}, {'a': 6, 'date': '6/20/2013', 'b': 19}, {'a': 7, 'date': '6/18/2013', 'b': 12}, {'a': 9, 'date': '6/16/2013', 'b': 15}] DF1 = pd.DataFrame(list1) DF2 contains the weekly date separators, for which the DF1 columns a and b should be aggregated. list2 = [{'datesep': '6/22/2013', 'c': 32}, {'datesep': '6/29/2013', 'c': 23}, {'datesep': '7/6/2013', 'c': 44}, {'datesep': '7/13/2013', 'c': 18}, {'datesep': '7/20/2013', 'c': 51}] DF2 = pd.DataFrame(list2) What I want to do is keep DF1.c as is, and aggregate DF1.a and DF1.b so that the values get summed at the DF2.datesep separator just above their DF1.date. That is, the values of DF1.a and DF1.b from 6/16/2013 to 6/22/2013 (both inclusive) should be aggregated at the closest next date separator, which is DF2.datesep=6/22/2013 row. 7/7/2013 to 7/13/2013 (both inclusive) should be aggregated at the closest next date separator, which is DF2.datesep=7/13/2013 row etc. Therefore the result should look like (column orders don't matter): c date a_sum b_sum 0 32 6/22/2013 23 62 1 23 6/29/2013 12 36 2 44 7/6/2013 14 32 3 18 7/13/2013 27 74 4 51 7/20/2013 - - I did this with a loop on list1 and list2, but is there a Pandas/Numpy solution that utilizes DF1 and DF2…
type: Question
tagged with: numpy
score: 0
accepted answer: http://stackoverflow.com/a/49313156
has title: Sum a Pandas DataFrame column under the ranges of another DataFrame
has answer: http://stackoverflow.com/a/49313156
answer count: 1

http://stackoverflow.com/q/49414434
tagged with: python
has comment: http://stackoverflow.com/comment/85830478
linked to: http://stackoverflow.com/q/32954481
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
score: -1
duplicate of: http://stackoverflow.com/q/32954481
type: Question
has title: Can I put an in-list statement and an if statement in one line in Python?
has answer: http://stackoverflow.com/a/49414482
tagged with: if-statement
has body: I'm trying to condense my code a bit and put if-else statements on single lines. When I try and do this for an if-else statement that includes an in-list statement, I get an error. temperature = 10 if 'hi' in ['hi','2'] else temperature = 1 File "&lt;ipython-input-2-af6c452397be&gt;", line 1 temperature = 10 if 'hi' in ['hi','2'] else temperature = 1 ^ SyntaxError: can't assign to conditional expression
type: UnansweredQuestion

http://stackoverflow.com/comment/85856420
type: AnswerComment
comment on: http://stackoverflow.com/a/49402161
type: Comment
has text: Ok, I did it I did not know this feature ;)
score: 0

http://stackoverflow.com/q/49367339
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/49367441
answer count: 4
has comment: http://stackoverflow.com/comment/85735542
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49367434
has title: Comparing two or more rows in a Pandas dataframe
has answer: http://stackoverflow.com/a/49367441
has body: I have a dataframe that looks like this: Reference | ID | Length ref101 |123456 | 10 ref101 |123789 | 5 ref202 |654321 | 20 ref202 |653212 | 40 I'm trying to determine which row for each row in the Reference column has the greatest length (based on the value in the Length column). For example, ref101 with ID 123456 is greater in length than ref101 with ID 123789. I've been playing around with .groupby(), but am getting nowhere. Is there a way of performing this sort of operation in Pandas?
favorite count: 0
has answer: http://stackoverflow.com/a/49367693
type: Question
has answer: http://stackoverflow.com/a/49367523
has answer: http://stackoverflow.com/a/49367434
tagged with: python

web-scraping
tags question: http://stackoverflow.com/q/49301649
tags question: http://stackoverflow.com/q/49387548
tags question: http://stackoverflow.com/q/49398568
tags question: http://stackoverflow.com/q/49403203
tags question: http://stackoverflow.com/q/49318015
tags question: http://stackoverflow.com/q/49307712
tags question: http://stackoverflow.com/q/49400067
tags question: http://stackoverflow.com/q/49375217
tags question: http://stackoverflow.com/q/49428951
tags question: http://stackoverflow.com/q/49305436
tags question: http://stackoverflow.com/q/49298271
tag name: web-scraping
tags question: http://stackoverflow.com/q/49311344
tags question: http://stackoverflow.com/q/49281520
tags question: http://stackoverflow.com/q/49378655
tags question: http://stackoverflow.com/q/49359903
tags question: http://stackoverflow.com/q/49407711
tags question: http://stackoverflow.com/q/49333881
tags question: http://stackoverflow.com/q/49389812
tags question: http://stackoverflow.com/q/49405424
tags question: http://stackoverflow.com/q/49434581
tags question: http://stackoverflow.com/q/49358679
tags question: http://stackoverflow.com/q/49402097
tags question: http://stackoverflow.com/q/49383023
tags question: http://stackoverflow.com/q/49286760
tags question: http://stackoverflow.com/q/49338793
type: Tag
tags question: http://stackoverflow.com/q/49367115
tags question: http://stackoverflow.com/q/49381342
tags question: http://stackoverflow.com/q/49429458
tags question: http://stackoverflow.com/q/49350210
tags question: http://stackoverflow.com/q/49290207
tags question: http://stackoverflow.com/q/49414367
tags question: http://stackoverflow.com/q/49436492
tags question: http://stackoverflow.com/q/49426387
tags question: http://stackoverflow.com/q/49319528
tags question: http://stackoverflow.com/q/49395251
tags question: http://stackoverflow.com/q/49301542
tags question: http://stackoverflow.com/q/49404344
tags question: http://stackoverflow.com/q/49303800
tags question: http://stackoverflow.com/q/49351946
tags question: http://stackoverflow.com/q/49341172
tags question: http://stackoverflow.com/q/49388091
tags question: http://stackoverflow.com/q/49285184
tags question: http://stackoverflow.com/q/49389636
tags question: http://stackoverflow.com/q/49322145
tags question: http://stackoverflow.com/q/49395395
tags question: http://stackoverflow.com/q/49300628
tags question: http://stackoverflow.com/q/49416500
tags question: http://stackoverflow.com/q/49340760
tags question: http://stackoverflow.com/q/49341670
tags question: http://stackoverflow.com/q/49324021
tags question: http://stackoverflow.com/q/49353954
tags question: http://stackoverflow.com/q/49310922
tags question: http://stackoverflow.com/q/49368348
tags question: http://stackoverflow.com/q/49417463
tags question: http://stackoverflow.com/q/49342383
tags question: http://stackoverflow.com/q/49392258
tags question: http://stackoverflow.com/q/49347627

h5py
tags question: http://stackoverflow.com/q/49438814
tags question: http://stackoverflow.com/q/49314261
tags question: http://stackoverflow.com/q/49304762
type: Tag
tags question: http://stackoverflow.com/q/49434842
tags question: http://stackoverflow.com/q/49386121
tag name: h5py

http://stackoverflow.com/q/49378182
has title: Python multiple print output need to store in multiple text file
tagged with: python
has answer: http://stackoverflow.com/a/49378237
accepted answer: http://stackoverflow.com/a/49378237
possible better answer: http://stackoverflow.com/a/49378359
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85758150
has comment: http://stackoverflow.com/comment/85757111
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85757003
has body: Using API, I am trying to fetch some incident data from a web portal. From portal I am getting multiple incident output. I have written a script to write a print output in a text file. My problem is, currently all incident output is getting stored in a single text file, I want to store this into multiple text file based on per incident. My current code is given below: orig_stdout = sys.stdout f = open ('alerts.txt', 'w') sys.stdout = f #print data for i in data['alert']: print "Alert ID: " + str(i['alertId']) print "Alarm Time: " + i['dateStart'] print "Test Name: " + i['testName'] print "URL: " + i['permalink'] print "Rule ID: " + str(i['ruleId']) print "Rule Name: " + i['ruleName'] print "Test ID: " + str(i['testId']) print "Test Name: " + i['testName'] print "\n" sys.stdout = orig_stdout f.close()
has answer: http://stackoverflow.com/a/49378359

http://stackoverflow.com/comment/85827216
type: QuestionComment
comment on: http://stackoverflow.com/q/49412694
has text: @BradSolomon yes, the non-numeric columns are the same for both. The actual data is from 2 different time periods. I am trying to calculate the percentage change.
score: 0
type: Comment

http://stackoverflow.com/q/49395819
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50898912
has answer: http://stackoverflow.com/a/50209726
answer count: 8
has comment: http://stackoverflow.com/comment/95257763
has answer: http://stackoverflow.com/a/55639550
has answer: http://stackoverflow.com/a/54742569
has body: I am currently using Python 3.5.5 on Anaconda and I am unable to import torch. It is giving me the following error in Spyder: Python 3.5.5 |Anaconda, Inc.| (default, Mar 12 2018, 17:44:09) [MSC v.1900 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. IPython 6.2.1 -- An enhanced Interactive Python. import torch Traceback (most recent call last): File "&lt;ipython-input-1-eb42ca6e4af3&gt;", line 1, in &lt;module&gt; import torch File "C:\Users\trish\Anaconda3\envs\virtual_platform\lib\site- packages\torch\__init__.py", line 76, in &lt;module&gt; from torch._C import * ImportError: DLL load failed: The specified module could not be found. Many suggestions on the internet say that the working directory should not be the same directory that the torch package is in, however I've manually set my working directory to C:/Users/trish/Downloads, and I am getting the same error. Also I've already tried the following: reinstalling Anaconda and all packages from scratch, and I've ensured there is no duplicate "torch" folder in my directory. Pls help! Thank you!
tagged with: python
has answer: http://stackoverflow.com/a/51142648
score: 15
linked to: http://stackoverflow.com/q/50612899
tagged with: torch
has answer: http://stackoverflow.com/a/53209284
type: AnsweredQuestion
upvote count: 15
possible better answer: http://stackoverflow.com/a/53209284
has answer: http://stackoverflow.com/a/51079959
has title: "import torch" giving error "from torch._C import *, DLL load failed: The specified module could not be found"
downvote count: 0
has answer: http://stackoverflow.com/a/58637037
accepted answer: http://stackoverflow.com/a/51142648

http://stackoverflow.com/q/49394628
type: Question
has title: Do you need to close files when opened and read to compare in an "if" statement?
has body: if open(file1).read() == open(file2).read(): print('match') Do I need to close these files after comparing them? I know I need to when doing the following, but is this different? target = open(file1)
has comment: http://stackoverflow.com/comment/85790976
tagged with: python
has comment: http://stackoverflow.com/comment/85791040
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49394663
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85790993
has answer: http://stackoverflow.com/a/49394711

http://stackoverflow.com/q/49355010
has comment: http://stackoverflow.com/comment/85710371
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85710496
score: 108
has title: How do i watch python source code files and restart when i save?
has comment: http://stackoverflow.com/comment/98424354
linked to: http://stackoverflow.com/q/3274334
has answer: http://stackoverflow.com/a/49435131
accepted answer: http://stackoverflow.com/a/49435131
has comment: http://stackoverflow.com/comment/85710413
answer count: 7
has body: When I save a python source code file, I want to re-run the script. Is there a command that works like this (sort of like nodemon for node)?
has answer: http://stackoverflow.com/a/55196033
tagged with: python
has comment: http://stackoverflow.com/comment/85710659
has comment: http://stackoverflow.com/comment/85710625
has answer: http://stackoverflow.com/a/78236591
favorite count: 0
has answer: http://stackoverflow.com/a/76660244
has answer: http://stackoverflow.com/a/54318365
possible better answer: http://stackoverflow.com/a/54318365
tagged with: nodemon
upvote count: 108
downvote count: 0
has answer: http://stackoverflow.com/a/63014698
has comment: http://stackoverflow.com/comment/85710631
has comment: http://stackoverflow.com/comment/85710438
has answer: http://stackoverflow.com/a/62816907
type: Question

http://stackoverflow.com/a/49304517
type: Answer
has body: EDIT: As my first answer was overly complicated and unelegant, I rewrote it to incorporate the solutions by ImportanceOfBeingErnest. I still keep the new version here, alongside the one by ImportanceOfBeingErnest, because I think the additional functionality might make it easier for other people to plot flow duration curves for their timeseries. If someone might have additional ideas see: Github Repository Features are: Changing the percentiles for a range flow duration curve Easy usage as standalone figure or subplot. If an subplot object is provided the flow duration curve is drawn in this one. When None is provided it creates one and returns it Seperate kwargs for the range curve and its comparison Changing the y-axis to logarithmic scale with a keyword Extended example to help understand its usage. The code is the following: # -*- coding: utf-8 -*- """ Created on Thu Mar 15 10:09:13 2018 @author: Florian Ulrich Jehn """ import matplotlib.pyplot as plt import pandas as pd import numpy as np def flow_duration_curve(x, comparison=None, axis=0, ax=None, plot=True, log=True, percentiles=(5, 95), decimal_places=1, fdc_kwargs=None, fdc_range_kwargs=None, fdc_comparison_kwargs=None): """ Calculates and plots a flow duration curve from x. All observations/simulations are ordered and the empirical probability is calculated. This is then plotted as a flow duration curve. When x has more than one dimension along axis, a range flow duration curve is plotted. This means that for every probability a min and max flow is determined. This is then plotted as a fill between. Additionally a comparison can be given to the function, which is plotted in the same ax. :param x: numpy array or pandas dataframe, discharge of measurements or simulations :param comparison: numpy array or pandas dataframe of discharge that should also be plotted in the same ax :param axis: int, axis along which x is iterated through :param ax: matplotlib subplot object, if not None, will plot in that instance…
accepted answer of: http://stackoverflow.com/q/49304516
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49304516
downvote count: 0

http://stackoverflow.com/comment/85691866
type: QuestionComment
has text: So, what makes you sure that the `image` that you pass into that function really is the bytes of a JPEG file? Where does it come from? (More specific than “a request body”...)
comment on: http://stackoverflow.com/q/49345303
score: 1
type: Comment

http://stackoverflow.com/comment/85721929
type: Comment
has text: You ran the command `python3` with no input, so it exited. Try to tell Docker that the command is interactive so that it keeps stdin open: `docker run -dit my-app`
type: AnswerComment
comment on: http://stackoverflow.com/a/49360068
score: 0

http://stackoverflow.com/a/52459115
score: 0
answers question: http://stackoverflow.com/q/49285746
has body: The following worked for me: weight1 = 1.5 weight2 = 1.5 bias = -2 Will update when I better understand why
type: Answer

http://stackoverflow.com/comment/85809556
score: 0
type: Comment
has text: Hmm... I'm not sure about this.. `div` is the current details. when you do click on new link you're waiting for new details appearance (staleness of old details). So it should be defined before click. Does my initial code not working? Did you get any exception?
type: AnswerComment
comment on: http://stackoverflow.com/a/49403539

http://stackoverflow.com/comment/85837585
has text: @abarnert Oh wait sorry - I think I misread what you wrote. I see how to do it for functions that I *write*, since I can build in the behavior by hand, but I was hoping to have it for functions I don't create (even if I have to specify them ahead of time [not ideal, but acceptable]).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49417747
type: QuestionComment

http://stackoverflow.com/comment/85795899
has text: @EcstasiaTisiphoni So, are you trying to run `rule bamdiagnostics` separately for Sample1 and Sample2? If not, could you list the intended shell command(s) for this rule?
comment on: http://stackoverflow.com/a/49391674
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49356663
upvote count: 4
has comment: http://stackoverflow.com/comment/85753978
has comment: http://stackoverflow.com/comment/85751961
downvote count: 0
answers question: http://stackoverflow.com/q/49355471
has comment: http://stackoverflow.com/comment/85753247
has body: The methods __getattr__ and __getattribute__ are only used for recovering attributes when you call then explicitly, by example when you do foo.bar. They are not used for implicit invocation. This behaviour is specified in the documentation Note: This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions. The reason for such an implementation is explained here. Bypassing the __getattribute__() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods In conclusion what you are trying to do, i.e. using __getattr__ to redirect implicit special method calls, has been voluntarily sacrificed in favor of speed. Inheritance The behaviour you are describing can be achieved by class inheritance. Although, passing in arguments to your class constructor will require the following fidling with the __new__ method. class NoAdd(int): def __new__(cls, x, *args, **kwargs): return super().__new__(cls, x) def __init__(self, x, *args, **kwargs): ... x = NoAdd(0) x + 5 # 5 x * 2 # 0 Metaclass Now, suppose you really need to catch implicit call to special methods. I see very little case where this could be useful, but it is a fun exercise. In this case we can rely on metaclass to fill in missing methods with the ones from member. class ProxyToMember(type): def __init__(cls, name, bases, name_space): super().__init__(name, bases, name_space) if hasattr(cls, 'member'): proxy_attrs = (attr for attr in dir(cls.member) if not hasattr(cls, attr)) def make_proxy(attr): attr_value = getattr(cls.member, attr) def proxy(_, *args, **kwargs): return attr_value(*args, **kwargs) if callable(attr_value): return proxy else: return property(lambda _: getattr(cls.member, attr)) for attr in proxy_attrs: setattr(cls, attr, make_proxy(attr)) class A(metaclass=ProxyToMember): member = 0 class B(metaclass=ProxyToMember…
has comment: http://stackoverflow.com/comment/85754428
has comment: http://stackoverflow.com/comment/85752834
has comment: http://stackoverflow.com/comment/85753237
type: Answer
has comment: http://stackoverflow.com/comment/85752124
has comment: http://stackoverflow.com/comment/85754231
score: 4
has comment: http://stackoverflow.com/comment/85754333
has comment: http://stackoverflow.com/comment/85754282
has comment: http://stackoverflow.com/comment/85754269

http://stackoverflow.com/a/49382099
score: 0
has comment: http://stackoverflow.com/comment/85776650
type: AcceptedAnswer
has body: As I understand your problem, you need to search a file for a specific pattern, and then pre-pend that match with the total number of matches found so far. Here is an example that uses re.sub and custom function, along with a global counter. You can incorporate this into your code: &gt;&gt;&gt; count = 1 &gt;&gt;&gt; s 'The happy and hungry hippo had a happy meal for lunch.' &gt;&gt;&gt; def f(m): ... global count ... value = '{}-{}'.format(count, m.group()) ... count = count + 1 ... return value ... &gt;&gt;&gt; re.sub(r'(h\w+y)', f, s) 'The 1-happy and 2-hungry hippo had a 3-happy meal for lunch.' You have to surround the regular expression in ( ) so that the match is captured and returned, in order to modify it.
answers question: http://stackoverflow.com/q/49376818
accepted answer of: http://stackoverflow.com/q/49376818
type: Answer

http://stackoverflow.com/comment/85745610
has text: Please check note in the question. Sorry I should have updated this initially.
comment on: http://stackoverflow.com/a/49372271
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85765448
has text: You must be using a different version of python. Try iterating as with dictionaries. See update of the answer.
comment on: http://stackoverflow.com/a/49363716
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49395588
type: AnsweredQuestion
score: 0
tagged with: django-socialauth
has body: I'm using the Django-Python Social Auth app and i'm trying to extend my pipeline so that when a user signs up using Facebook, they are simultaneously signed up to my Mailchimp mailing list (and sent an email to verify). This works fine if a user signs up using traditional input methods--but not via Social auth.and is returning this error: ValueError at /oauth/complete/facebook/ not enough values to unpack (expected 2, got 1) here is full stack trace: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\utils.py" in wrapper 49. return func(request, backend, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\views.py" in complete 33. *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\actions.py" in do_complete 41. user = backend.complete(user=user, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in complete 40. return self.auth_comp…
has comment: http://stackoverflow.com/comment/85793833
has comment: http://stackoverflow.com/comment/85793775
answer count: 3
has answer: http://stackoverflow.com/a/49429821
has title: Django Social Auth - Not Enough Values To Unpack When Trying To Send Email
tagged with: python-social-auth
has answer: http://stackoverflow.com/a/51072580
type: Question
accepted answer: http://stackoverflow.com/a/49397674
possible better answer: http://stackoverflow.com/a/49429821
has comment: http://stackoverflow.com/comment/85794063
has answer: http://stackoverflow.com/a/49397674
tagged with: django
tagged with: python

http://stackoverflow.com/a/49322727
answers question: http://stackoverflow.com/q/49322409
score: 0
has comment: http://stackoverflow.com/comment/85647031
has body: Regex: ^(?=(?:.*[a-z]){4})(?=.*[$@_])(?=.*[A-Z])[a-zA-Z$@_]{6}$ Details: ^ Asserts position at start of the string (?=) Positive Lookahead (?:.*[a-z]){4} Matches any character between zero and unlimited times followed by lowercase letter a-z exactly 4 times .*[@] Matches any character between zero and unlimited times followed by special chars $@_ .*[A-Z] Matches any character between zero and unlimited times followed by capital letter A-Z [a-zA-Z$@_]{6} Match a single character present in the list 6 times $ Asserts position at the end of the string
has comment: http://stackoverflow.com/comment/85648112
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85647925
has comment: http://stackoverflow.com/comment/85647348
accepted answer of: http://stackoverflow.com/q/49322409
has comment: http://stackoverflow.com/comment/85647128
has comment: http://stackoverflow.com/comment/85647219
has comment: http://stackoverflow.com/comment/85647623
type: Answer
has comment: http://stackoverflow.com/comment/85647514

http://stackoverflow.com/comment/85795146
type: QuestionComment
has text: I recommend providing an expected output **as a picture** to get a good answer.
score: 1
comment on: http://stackoverflow.com/q/49396180
type: Comment

http://stackoverflow.com/comment/85852683
score: 0
comment on: http://stackoverflow.com/q/49424554
has text: @MaxPowers : it was probably with `apt` because `which pip` returns `…/anaconda3/bin/pip` and `pip install python3-gammu` doesn't find python3-gammu!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85876281
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49437156
score: 0
has text: How it doesn't work and what's the problem exactly? do you get any error?

http://stackoverflow.com/comment/85813916
score: 0
has text: @abarnert it should only return `True` in the Python version(s) where it is raisable; you correctly pointed out in your answer where my tests were wrong.
comment on: http://stackoverflow.com/q/49397153
type: Comment
type: QuestionComment

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/49291521
tags question: http://stackoverflow.com/q/49312879
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/49395927
tags question: http://stackoverflow.com/q/49387220

http://stackoverflow.com/q/49340955
answer count: 1
favorite count: 0
type: Question
tagged with: popen
tagged with: python
has body: I would like to know if there is a way to recover the return code when the asynchronous process has been completed by a timeout. The constraints are that I want to recover this code in another class that is in another python file. In addition, I do not want to block my GUI ... In my MainView.py, my code this : if self.comboBox.currentText() == "HASHCAT" : self.process = Hashcat(MainWindow.hashcatPath, 100, 3, MainWindow.hashFilePath, MainWindow.dictPath, MainWindow.pathOutFile) self.process.run(2) And my Hashcat.py file look like this : def run(self,timeout): def target(): FNULL = open(os.devnull, 'w') if self.typeAttack == 0 : self.subprocess=\ subprocess.Popen([self.pathHashcat,"-m",str(self.algoHash),"-a",str(self.typeAttack),self.pathHashFile,self.pathDict, "-o",self.pathOutFile], stdout=FNULL, stderr=subprocess.STDOUT) if self.typeAttack == 3 : self.subprocess =\ subprocess.Popen( [self.pathHashcat, "-m", str(self.algoHash), "-a", str(self.typeAttack),self.pathHashFile,"-o",self.pathOutFile]) self.timer.start() self.subprocess.wait() self.timer.cancel() def timer_callback(): print('Terminating process (timed out)') self.subprocess.terminate() self.thread = threading.Thread(target=target) self.timer = threading.Timer(timeout, timer_callback) self.thread.start() print(self.timer.isAlive)
has title: Recover async subprocess return code completed by timeout
tagged with: subprocess
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49341666
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49341666

http://stackoverflow.com/q/49411495
duplicate of: http://stackoverflow.com/q/34817549
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85824684
has title: Python Read from SQL to pandas dataframes
type: Question
has comment: http://stackoverflow.com/comment/85832136
has comment: http://stackoverflow.com/comment/85832185
tagged with: apache-spark-sql
tagged with: pandas
tagged with: pyspark
linked to: http://stackoverflow.com/q/34817549
linked to: http://stackoverflow.com/q/12047193
tagged with: python
has comment: http://stackoverflow.com/comment/85832180
has body: I am using the below script to read data from MSSQL Server to Pyspark dataframes. DFFSA = spark.read.format("jdbc").option("url", jdbcURLDev).option("driver", MSSQLDriver ).option("dbtable", "FSA.dbo.FSA").option("user", "DevUser").option("password", "password").load(); This generates a Pyspark dataframe. How can I do so with pandas dataframe? I know I can convert the resulting dataframe into a pandas dataframe using the toPandas() function but this is taking a lot of time since I am reading millions of rows.

http://stackoverflow.com/q/49370591
has body: What are the advantages of saving file in .pkl format over .txt or .csv format in Python?
has comment: http://stackoverflow.com/comment/99863113
answer count: 2
has title: What are the advantages of .pkl file over .txt or csv file in python
has answer: http://stackoverflow.com/a/49370614
type: UnansweredQuestion
downvote count: 2
tagged with: pickle
score: 4
upvote count: 6
has comment: http://stackoverflow.com/comment/99863219
linked to: http://stackoverflow.com/q/48770542
linked to: http://stackoverflow.com/q/30253976
has comment: http://stackoverflow.com/comment/85763804
has comment: http://stackoverflow.com/comment/85745236
tagged with: python
has answer: http://stackoverflow.com/a/60810737
favorite count: 0
type: Question

http://stackoverflow.com/comment/85703672
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49349079
type: QuestionComment
has text: Thanks. Can you expand your definition of special characters? i.e. give examples.

http://stackoverflow.com/q/49439408
has body: I was trying to help someone add a colorbar for the vertical blue bar in the image below. We tried many variations of plt.colorbar(row_colors) (like above and below sns.clustermap()) and looked around online for 2 hours, but no luck. We just want to add a colorbar for the blues, please help! import pickle import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt feat_mat, freq, label = pickle.load(open('file.pkl', 'rb')) feat_mat_df = pd.DataFrame(feat_mat[4]) freq_df = pd.DataFrame(freq) freq_df_transposed = freq_df.transpose() my_palette = dict(zip(set(freq_df_transposed[int('4')]), sns.color_palette("PuBu", len(set(freq_df_transposed[int('4')])))))) row_colors = freq_df_transposed[int('4')].map(my_palette) sns.clustermap(feat_mat_df, metric="euclidean", standard_scale=1, method="complete", cmap="coolwarm", row_colors = row_colors) plt.show() This is where he based his code from: #405 Dendrogram with heatmap and coloured leaves
answer count: 1
type: Question
has title: Add Second Colorbar to a Seaborn Heatmap / Clustermap
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86372573
has answer: http://stackoverflow.com/a/49440668
tagged with: heatmap
tagged with: python-3.x
tagged with: colorbar
score: 0
tagged with: seaborn

http://stackoverflow.com/a/49413988
has body: If you include '\n' in a string, it will split the line there. For instance: print('This is the first line\nAnd this is the second line') Then the output would be: This is the first line And this is the second line
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49413525

http://stackoverflow.com/q/49326559
answer count: 1
has comment: http://stackoverflow.com/comment/85655104
tagged with: github
type: Question
has body: A collaborator of mine wrote a software package in Python 2.7, took advantage of it to run some tests and obtain some scientific results. We wrote together a paper about the methods he developed and the results he obtained. Everything worked out well so he recently put this package publically available on his GitHub webpage. Then I thought it would have been useful to have a Python 3.5 version of that package. Therefore I downloaded the original software and made the proper changes to have it working on Python 3.5. Now I don't know how to properly release this Python 3.5 package. I envision three possibilities: Should I put it on his original GitHub project repository? This option would lead to some confusion, because people would have to download both the Python 2.7 and the Python 3.5 code. Should I create a new repository only for my Python 3.5 package, in addition to the Python 2.7 one released by my collaborator? This option would lead to the existence of two running code repositories, and to some confusion as well, because people might not know which is the "official one" to use. Should I create a new repository only for my Python 3.5 package, and ask my collaborator to delete his Python 2.7 repository? This option would make our paper inconsistent, because it states that tests were done with Python 2.7. Do you envision any other option I did not include? Do you have any suggestion?
tagged with: version
tagged with: python
has comment: http://stackoverflow.com/comment/85655186
tagged with: python-3.x
tagged with: python-2.7
has title: What's the best way to release two versions of the same software package on GitHub?
score: 0
has answer: http://stackoverflow.com/a/49326823
type: UnansweredQuestion

http://stackoverflow.com/a/49347312
type: Answer
has body: I would use python's build in zip function documentation for item1, item2, item3 in zip(list1, list2, list3): if item1 == item2: print(item3) Hope it helps!
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49347045
accepted answer of: http://stackoverflow.com/q/49347045
has comment: http://stackoverflow.com/comment/85695897

http://stackoverflow.com/comment/85677911
comment on: http://stackoverflow.com/a/49336096
type: Comment
has text: And the reason why I do this is also - because I am trying to use "graph embeddings" instead of famous Word2Vec. But to use graph embedding, I need to determine the optimal embedding size. I positively expect that the number of axiomatic words would be a good estimator for the best embedding dimension.
score: 0
type: AnswerComment

http://stackoverflow.com/a/78607823
has body: It seems like only correct way to do it is to use regex. I've tested following example on two totally different zones, and it seems to work: zone = "ap-southeast-1-bkk-1a" zone2 = "us-east-1a" region_regex = r'(.*?-\d+)' match1 = re.match(region_regex, zone) match2 = re.match(region_regex, zone2) match1.group(1), match2.group(1) # ('ap-southeast-1', 'us-east-1') It won't make us-east1 from us-east1-b, of course. Don't know how AWS zones were named at the time you've asked the question, but now it is "us-east-1d"? If it is named this in Google Cloud,I guess you'll need some extra work to adapt the regex formula for your case and use both of them for each cloud separately. UPD: Maybe it's a little out of context, and "ap-southeast-1-bkk" seems to be a Local Zone. But the fact of this approach works for both AZ and Local AZ makes it a more universal option.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49383797

http://stackoverflow.com/comment/85934195
type: QuestionComment
comment on: http://stackoverflow.com/q/49331835
score: 0
type: Comment
has text: When I run it from command line no error spits out the application just closes.

http://stackoverflow.com/comment/86810465
score: 0
comment on: http://stackoverflow.com/q/49427766
type: Comment
type: QuestionComment
has text: Small update: I've asked similar question on OpenCV forum. Apparently there is no easy way to get those values. In my case I found a half-solution, as every UMat matrix is first numpy matrix (before transfer to GPU). So at this moment we have access to shape and we have to remember it in separate variable for further calculations. This helps me, but there are some cases when it is not possible to use this solution.

http://stackoverflow.com/q/49396485
favorite count: 0
type: Question
answer count: 2
has body: I am trying to implement some changes into a deployed Flask API. Am I able to edit files in the deployed API and have the changes take effect without having the restart the API build?
has answer: http://stackoverflow.com/a/49421270
has comment: http://stackoverflow.com/comment/85805773
has comment: http://stackoverflow.com/comment/85795658
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/67429490
tagged with: flask
tagged with: flask-sqlalchemy
score: 1
tagged with: flask-admin
tagged with: python
has comment: http://stackoverflow.com/comment/85797048
tagged with: flask-restful
has title: Editing a Flask API
has comment: http://stackoverflow.com/comment/85794802

http://stackoverflow.com/comment/128365464
type: Comment
comment on: http://stackoverflow.com/a/70285710
type: AnswerComment
has text: I'm afraid this won't capture all errors. I would rather catch *OSError* (both *NotADirectoryError* and *FileNotFoundError*) subclass that. Unfortunately, *os.scandir* doesn't guarantee that it will raise only *OSError*-s - however, it is implied in https://docs.python.org/3/library/os.html#os.walk docs, so that would be safe enough to catch *OSError*. And if you omitted your variable *success* and `return` in place, you could save several lines.
score: 0

http://stackoverflow.com/comment/85725716
score: 0
comment on: http://stackoverflow.com/a/49362574
has text: Hi user3237357! I have tried with the css selector but I still get an empty list.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85741659
type: AnswerComment
has text: @abarnert its a good point - I just updated the example to demonstrate how the whole construct could be accomplished using numpy
comment on: http://stackoverflow.com/a/49370152
type: Comment
score: 0

http://stackoverflow.com/q/49428050
score: 0
accepted answer: http://stackoverflow.com/a/49461170
possible better answer: http://stackoverflow.com/a/49428892
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49461170
has title: matplotlib overload plot function
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85858937
answer count: 2
has body: I don't know how exactly is called what I want to do. I'm also a new user of Python. Basically I have created a very simple class that is intended to represent measured quantities of the form and automatically do the error propagation. Here's the definition: from math import sqrt from math import log10 from math import fabs from math import floor from math import ceil from math import pi class magnitude: def __init__(self, val, err): self.val = val self.err = err def __str__(self): "Prints the magnitude in the format v.vvvv(v+-e) being 'v' the relevant digits of the magnitude value and '+-e' the most significant digit of the error." if self.err == 0 or self.val == 0: return str(self.val) if self.err &gt;= fabs(self.val): return '{:.0e} +- {:.0e}'.format(self.val, self.err) + ' (Infinite uncertainty!)' else: temp = '{:.' + str(ceil(log10(fabs(self.val*(1+pi*1e-3))) - ceil(log10(self.err*(1+pi*1e-3))) )) + 'e}' # Calculates number of digits for the representative part. The adition of 'pi*1e-3' is to add some noise and avoid error values of '1', '10', '100', ..., because they are not well printed. temp = temp.format(self.val) temp = temp[:-4] # Remove last 4 chars. return temp + '(+-' + str(int(self.err*10**(ceil(-log10(self.err))))) + ')' + '{:.0e}'.format(fabs(self.val))[1:] + ' ({:d} ppm)'.format(int(self.err/fabs(self.val)*1e6)) # -------------------- def __add__(self, other): if type(other) == int or type(other) == float: other = magnitude(other, 0) return magnitude(self.val + other.val, sqrt(self.err**2 + other.err**2)) def __radd__(self, other): if type(other) == int or type(other) == float: other = magnitude(other, 0) return magnitude(self.val + other.val, sqrt(self.err**2 + other.err**2)) # -------------------- def __sub__(self, other): if type(other) == int or type(other) == float: other = magnitude(other, 0) return magnitude(self.val - other.val, sqrt(self.err**2 + other.err**2)) def __rsub__(self, other): if type(other) == int or type(other) == float: other…
linked to: http://stackoverflow.com/q/10202938
has comment: http://stackoverflow.com/comment/85891168
has answer: http://stackoverflow.com/a/49428892
tagged with: python
has comment: http://stackoverflow.com/comment/85859443
has comment: http://stackoverflow.com/comment/85872066
type: AnsweredQuestion

http://stackoverflow.com/comment/85862729
type: AnswerComment
comment on: http://stackoverflow.com/a/49393386
has text: thanks.. i see unfamiliar code in your example. please explain this NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as tmp:
type: Comment
score: 0

http://stackoverflow.com/a/49297540
score: 3
answers question: http://stackoverflow.com/q/49296346
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/124961007
has comment: http://stackoverflow.com/comment/108912202
type: Answer
accepted answer of: http://stackoverflow.com/q/49296346
has body: It is perfectly possible to do this Create a bat file that you can reference in the windows task scheduler. Code as follows: cd C:\path to your notebook jupyter nbconvert --to notebook --execute NOTEBOOKTOEXECUTE.ipynb I needed to include the path, as the console would be run from the system path and thus unable to find the notebook.

http://stackoverflow.com/q/49354598
score: 0
answer count: 1
type: Question
has title: Can't convert numpy array values to float32
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49355076
tagged with: python
has body: I am trying to convert a numpy array of float64 to float32. The array is the concatenated version of two other arrays: hist and n_zero_rows: def someFunction(hist, imgs): samples = [] for img in imgs: n_zero = img != 0 n_zero_cols = n_zero.sum(0) / norm(n_zero.sum(0) + eps) n_zero_rows = n_zero.sum(1) / norm(n_zero.sum(1) + eps) features = np.concatenate((hist, n_zero_rows), axis=0) samples.append(features) return np.float32(samples) If I append the samples array with hist only, it works. But when I try to add the n_zero_rows, it raises an exception: ValueError: setting an array element with a sequence. I checked the types of both the arrays and both of them are numpy.ndarrays and both elements in those arrays are float64. EDIT: Oops! It can't really be tested. Here's more detail then: I made sure that my n_zero_rows array had the same amount dimensions as hist. Essentially, it is just checking the amount of non-zero pixels along every rows. You can try it yourself with any image. Here's the shape and type of both arrays: Shape of img: (128, 128) Shape of n_zero_rows: (128,) Shape of hist: (120,) type of n_zero_rows: &lt;type 'numpy.ndarray'&gt; type of hist: &lt;type 'numpy.ndarray'&gt; And just to make sure, here's n_zero_rows for the first img in the loop (NORMALIZED): [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.03518132 0.04073627 0.02777473 0.03703297 0.02777473 0.05925276 0.07406595 0.09258243 0.11850551 0.14998354 0.15739014 0.15553849 0.15924178 0.15553849 0.15553849 0.15739014 0.15924178 0.15924178 0.16109343 0.16109343 0.16109343 0.15739014 0.15924178 0.16109343 0.15924178 0.16109343 0.16109343 0.16109343 0.16109343 0.15924178 0.16109343 0.16109343 0.16664838 0.17035168 0.17035168 0.17220333 0.14628024 0.14257695 0.1444286 0.12591211 0.10369233 0.09813738 0.10184068 0.09813738 0.09998903 0.09628573 0.09998903 0.09443408 0.09813738 0.09998903 0.09258243 0.09813738 0.09998903 0.09998903 0.09813738 0.096…
has comment: http://stackoverflow.com/comment/85709586
tagged with: numpy
has comment: http://stackoverflow.com/comment/85733436

http://stackoverflow.com/comment/85664035
comment on: http://stackoverflow.com/q/49330698
score: 0
type: Comment
has text: @johnashu yes it is, the "\n" doesn't work in open i may use print but i can figure it how. People, stop trolling or just bulling you are useless as f.
type: QuestionComment

http://stackoverflow.com/q/49418929
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85839528
tagged with: string
favorite count: 0
tagged with: byte
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49419001
has answer: http://stackoverflow.com/a/49419002
has title: Python 3: Get Bytes from File
tagged with: python
type: Question
tagged with: python-3.x
answer count: 2
has body: I'm trying to get bytes from a png file in python 3, and print a string showing the bytes from the png file. However, it gives me this output: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00(\x00\x00\x00(\x08\x02\x00\x00\x00\x03\x9c/:\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x01XIDATXG\xe5\xcd\xb1m\x031\x14\x04\xd1\xebF\xad\xb8+\xd5\xe0\x8a\xe5`f\x19|,.\xa0\x0fL\xf4\xc0h\x08.\xafo\xf5&gt;\xc8/a;\xc2/a;\xc2/a;\xc2/a;\xc2/a\x0b\xebC\x1c\r+la}\x88\xa3a\x85-\x88\xbf?\xff=p4\xac\xb0\x05q\xacl\x1c8\x1aV\xd8\x828V6\x0e\x1c\r+lA\x1c+\x1b\x07\x8e\x86\x15\xb6 \x8e\x95\x8d\x03G\xc3\n[\x10\xeb\xca\xbd\xfa\xc4\xd1\xb0\xc2\x16\xc4\xbar\xaf&gt;q4\xac\xb0\x05\xb1\xae|\xde\xafz\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xe3\xbfu\xb8\xadO\x1c\r+lA\xac+\xf7\xea\x13G\xc3\n[\x10\xeb\xca\xbd\xfa\xc4\xd1\xb0\xc2\x16\xc4\xb1\xb2q\xe0hXa\x0b\xe2X\xd98p4\xac\xb0\x05q\xacl\x1c8\x1aV\xd8\x828V6\x0e\x1c\r+lA\x1c+\x1b\x07\x8e\x86\x15\xb6\xb0&gt;\xc4\xd1\xb0\xc2\x16\xd6\x878\x1aV\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0K\xd8\x8e\xf0\xcb/s]\x7f\xf8o$|7\xc4\xdf\xeb\x00\x00\x00\x00IEND\xaeB`\x82' instead of normal bytes (here are the bytes it should show): 89504E470D0A1A0A0000000D4948445200000028000000280802000000039C2F3A000000017352474200AECE1CE90000000467414D410000B18F0BFC6105000000097048597300000EC300000EC301C76FA86400000158494441545847E5CDB16D03311404D1EB46ADB82BD5E08AE56066197C2C2EA00F4CF4C068082EAF6FF53EC82F613BC22F613BC22F613BC22F613BC22F610BEB431C0D2B6C617D88A361852D88BF3FFF3D7034ACB00571AC6C1C381A56D8823856360E1C0D2B6C411C2B1B078E8615B6208E958D0347C30A5B10EBCABDFAC4D1B0C216C4BA72AF3E7134ACB005B1AE7CDEAF7AB8AD4F1C0D2B6C41AC2BE3BF75B8AD4F1C0D2B6C41AC2BE3BF75B8AD4F1C0D2B6C41AC2BE3BF75B8AD4F1C0D2…

http://stackoverflow.com/comment/130560385
comment on: http://stackoverflow.com/a/66166241
has text: @AbdulHaseeb it depends on which Linux distro you are using but usually a `sudo apt-get update` works.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49347733
has title: Python- extracting data from one running code to another
has comment: http://stackoverflow.com/comment/85695195
tagged with: python
has comment: http://stackoverflow.com/comment/85698142
has comment: http://stackoverflow.com/comment/85698247
has comment: http://stackoverflow.com/comment/85698196
score: 0
has body: I hope do describe my question accurate as possible: I have 2 remote Rpi machines running 2 different python codes. Machine of type A is controlling its GPIO pins and monitor its status using python code A. Machine of type B is monitoring several Type A's using python code B. My question is regrading code B : how can it get data of a running code ?
has comment: http://stackoverflow.com/comment/85695184
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49428067
has title: Allowing user/users to only view one table of DB with Django?
score: 0
linked to: http://stackoverflow.com/q/3068843
type: UnansweredQuestion
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49428480
has body: I am very new with Django and trying to learn from various sources on internet. My project folder structure goes like I am using sqlite.db and made 6 models that are linked to backend DB. One of the table i have is Execution_Results. class Execution_Results(models.Model): class Meta: permissions = ( ('view_results', 'User can view results'), ) verbose_name_plural = "Execution_Results" config_id = models.ForeignKey(Config_Details, on_delete=models.CASCADE) exec_time = models.DateTimeField() path = models.CharField(max_length=100) With Admin login i can only provide access to add, edit and delete for that particular or group of users. For my case i just want view access for users. And based on whatever config_id they choose i want to read data from other tables based on mapping and present it for user. I gave permissions = ( ('view_results', 'User can view results'), ) but i am not getting what next shall be done so that user can just view this table data.
type: Question
tagged with: python

http://stackoverflow.com/comment/85619991
has text: Is there a reason you're using `json.dumps`?
score: 2
comment on: http://stackoverflow.com/q/49308879
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49417272
has comment: http://stackoverflow.com/comment/86278721
accepted answer of: http://stackoverflow.com/q/49413769
has comment: http://stackoverflow.com/comment/86279745
answers question: http://stackoverflow.com/q/49413769
type: Answer
has body: After further thought, using object_hook or object_pairs_hook arguments would require reading the entire file into memory first—so to avoid doing that, instead here's something that reads the file incrementally, line-by-line. I had to modify your example JSON file to make it valid JSON (what you have in your question is a Python dictionary). Note that this code is format-specific in the sense that it assumes each JSON object in the array lies entirely on a single line—although it could be changed to handle multiline object definitions if necessary. So here's a sample test input file with valid JSON contents: [ {"thing1": "object1"}, {"thing2": "object2"}, {"thing3": "object3"}, {"thing4": "object4"}, {"thing5": "object5"}, {"thing6": "object6"} ] Code: from itertools import zip_longest import json from pathlib import Path def grouper(n, iterable, fillvalue=None): """ s -&gt; (s0, s1...sn-1), (sn, sn+1...s2n-1), (s2n, s2n+1...s3n-1), ... """ return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue) def read_json_objects(fp): """ Read objects from file containing an array of JSON objects. """ next(fp) # Skip first line. for line in (line.strip() for line in fp): if line[0] == ']': # Last line? break yield json.loads(line.rstrip(',')) def json_chunk(json_file_path, object_count): with open(json_file_path) as fp: for group in grouper(object_count, read_json_objects(fp)): yield(tuple(obj for obj in group if obj is not None)) if __name__ == '__main__': json_file_path = Path(__file__).parent / 'raw_data.json' for array in json_chunk(json_file_path, 5): print(array) Output from processing test file: ({'thing1': 'object1'}, {'thing2': 'object2'}, {'thing3': 'object3'}, {'thing4': 'object4'}, {'thing5': 'object5'}) ({'thing6': 'object6'},)
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85588229
type: Comment
comment on: http://stackoverflow.com/q/49292783
type: QuestionComment
has text: I'm sorry but I don't understand what you mean?
score: 0

http://stackoverflow.com/q/49386746
has body: I've been trying to do some auto generation / jit of functions using numba. You can call other jit functions from within a jit function, so it's easy to hard code in the functionality I want if you have a specific set of functions like so: from numba import jit @jit(nopython=True) def f1(x): return (x - 2.0)**2 @jit(nopython=True) def f2(x): return (x - 5.0)**2 def hardcoded(x, c): @jit(nopython=True) def f(x): return c[0] * f1(x) + c[1] * f2(x) return f lincomb = hardcoded(3, (0.5, 0.5)) print(lincomb(2)) Out: 4.5 However, say you don't know ahead of time what the f1, f2 are. I'd like to be able to use a factory to generate the functions, and then have another to generate linear combinations thereof: def f_factory(x0): @jit(nopython=True) def f(x): return (x - x0)**2 return f def linear_comb(funcs, coeffs, nopython=True): @jit(nopython=nopython) def lc(x): total = 0.0 for f, c in zip(funcs, coeffs): total += c * f(x) return total return lc And call it at runtime. This works without nopython mode: funcs = (f_factory(2.0), f_factory(5.0)) lc = linear_comb(funcs, (0.5, 0.5), nopython=False) print(lc(2)) Out: 4.5 But not with nopython mode. lc = linear_comb(funcs, (0.5, 0.5), nopython=True) print(lc(2)) TypingError: Failed at nopython (nopython frontend) Untyped global name 'funcs': cannot determine Numba type of &lt;class 'tuple'&gt; File "&lt;ipython-input-100-2d3fb6214044&gt;", line 11 So it looks like numba has trouble with tuples of jit functions. Is there any way to get this behavior to work? The set of functions and c's can get large so I would really like to get this to compile in nopython mode.
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85781547
accepted answer: http://stackoverflow.com/a/49392577
upvote count: 3
has title: Linear Combinations of Numba jitted functions in nopython mode
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49392577
has comment: http://stackoverflow.com/comment/85779143
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85778449
has comment: http://stackoverflow.com/comment/85782802
tagged with: numba
tagged with: python

http://stackoverflow.com/comment/85624314
score: 0
type: QuestionComment
has text: @MaxU Done. Sorry for the delay.
type: Comment
comment on: http://stackoverflow.com/q/49307601

http://stackoverflow.com/comment/85784395
type: AnswerComment
comment on: http://stackoverflow.com/a/49391078
type: Comment
has text: Yes exactly, because we only have to find a single match and can just straight up copy everything after that, I suspect this solution will be faster than anything with `set`. Could take some time later to properly time it and figure out for sure though. However, if the lists are really large, and they are indeed known to be sorted according to timestamps, binary search to find the first index may be more efficient.
score: 0

http://stackoverflow.com/q/49290994
has answer: http://stackoverflow.com/a/49291032
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -3
answer count: 1
tagged with: python
has body: I’m in a python programming class and I have to take the above function and complete it to find the area of a rectangle of 50 by 40. It wants the expected results of 2000 returned not print. Please help.
downvote count: 3
has comment: http://stackoverflow.com/comment/85585264
has title: Def getdimensions(dimension)

http://stackoverflow.com/q/49405240
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85811815
has body: Once I have a specific attribute of an object belonging to some class in Python, how can I get its name as a string? Is this info contained somewhere? In the following example, suppose I use a.someval in some function: how can I get its name as a string someval just from this value? class OneClass: def __init__(self): self.whatIam = 'I am a OneClass instance' self.whatIdo = 'Nothing really useful' def setSomeVal(self, val): self.someval = val a = OneClass() a.setSomeVal(13) If I had the object owning the attribute and not only the attribute value itself, I could go back to its name doing something like: def present_yourself_knowing_your_owner_object(you, owner): print 'My value is', you print 'My name is', owner.__dict__.keys()[owner.__dict__.values().index(you)] present_yourself_knowing_your_owner_object(a.someval, a) # My value is 13 # My name is someval present_yourself_knowing_your_owner_object(a.whatIam, a) # My value is I am a OneClass instance # My name is whatIam And I know we can access a method name like this: print a.setSomeVal.__name__ # setSomeVal But would it be possible to have the attribute name just from itself, something like: def present_yourself(you): print 'My value is', you print 'and my name is', '&lt; ** YOUR SOLUTION HERE ** &gt;' EDIT to answer @Daniel Roseman's comment: This can be achieved for some objects, e.g. methods: def present_yourself(you): print 'My value is', you print 'and my name is', you.__name__ #'&lt; ** YOUR SOLUTION HERE ;-) ** &gt;' present_yourself(a.setSomeVal) # My value is &lt;bound method OneClass.setSomeVal of &lt;__main__.OneClass instance at 0x7f3afe255f38&gt;&gt; # and my name is setSomeVal
tagged with: python
has comment: http://stackoverflow.com/comment/85811482
has title: Get the name of a specific attribute of some object as a string in Python
has comment: http://stackoverflow.com/comment/85812035
score: 2
upvote count: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85812127
downvote count: 0
has comment: http://stackoverflow.com/comment/85812354
answer count: 0
has comment: http://stackoverflow.com/comment/85811929
linked to: http://stackoverflow.com/q/192109
has comment: http://stackoverflow.com/comment/85811609
type: UnansweredQuestion
tagged with: namespaces

http://stackoverflow.com/comment/85697609
type: Comment
has text: youtube-dl is raising a URL error, indicating a problem with the URL string you've given it. Don't worry too much about which version of Python is being used. Python 2.7 is still used all over the place for various reasons.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49348921

http://stackoverflow.com/q/49371486
favorite count: 0
has body: I have a training set consisting of X and Y, The X is of shape (4000,32,1) and Y is of shape (4000,1). I would like to create a training/validation set based on split. Here is what I have been trying to do from sklearn.model_selection import StratifiedShuffleSplit sss = StratifiedShuffleSplit(test_size=0.1, random_state=23) for train_index, valid_index in sss.split(X, Y): X_train, X_valid = X[train_index], X[valid_index] y_train, y_valid = Y[train_index], Y[valid_index] Running the program gives the following error message related to the above code segment for train_index, valid_index in sss.split(X, Y): ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2. I am not very clear about the above error message, what's the right way to create a training/validation split for the training set as above?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49373093
accepted answer: http://stackoverflow.com/a/49373093
linked to: http://stackoverflow.com/q/48313387
tagged with: machine-learning
tagged with: python
has title: create training validation split using sklearn
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85755074
tagged with: scikit-learn
tagged with: sklearn-pandas

http://stackoverflow.com/q/49393692
tagged with: boolean-logic
has comment: http://stackoverflow.com/comment/85833153
has comment: http://stackoverflow.com/comment/85794077
linked to: http://stackoverflow.com/q/13005760
tagged with: eval
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85833247
favorite count: 0
type: Question
answer count: 0
tagged with: sympy
has comment: http://stackoverflow.com/comment/85789959
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Using Sympy "to_nnf" and a MemoryError using eval()
has body: I am using Sympy to convert a Boolean function to negation normal form. This boolean function is read in as a string with a large, variable number of elements. In order to handle the different number of symbols dynamically, I first create a list of symbols and replace the variable names. I end up with something like boolFunc = "~(ls[0] &amp; ls[1])" where ls is a list of symbols (except len(ls) could be very large). Then, I can convert the boolean Function using boolFunc = str(to_nnf(eval(val), simplify=False)) This works great for smaller Boolean Functions (up to about len(ls) = 40), but fails once the Boolean functions get complicated enough (about len(ls) = 60). It appears that the issue is with eval(). s_push: parser stack overflow Traceback (most recent call last): File "dualRail.py", line 187, in &lt;module&gt; eval(booleanFunction) MemoryError Does anyone know of a way to fix this issue either by getting rid of the need to use eval() somehow, or some other way? I have found a possible solution here, but I want to modify the Python source code as a last resort. Edit 1: I think the issue with eval is specifically deeply nested parenthesis. I also think there is a chance that some of these parenthesis are redundant. For example, in A | (B &amp; C) the parenthesis are not needed. If I write an algorithm to remove these extra parenthesis (assuming one doesn't already exist), this might allow a larger sized Boolean function, but I'm not sure if it will be enough. Edit 2: Here is a small example of what I am trying to do. I am using Python3.6 import re; from sympy import symbols from sympy.logic.boolalg import to_nnf #This function works fine boolean_function1 = '(((((~(op[2])) &amp; op[1]) &amp; op[0]) &amp; (~((~((((((((((((((((((A[1] &amp; A[0]) &amp; A[2]) &amp; A[3]) &amp; A[4]) &amp; A[5]) &amp; A[6]) &amp; A[7]) &amp; A[8]) &amp; A[9]) &amp; A[10]) &amp; A[11]) &amp; A[12]) &amp; A[13]) &amp; A[14]) &amp; A[15]) &amp; A[16]) &amp; A[17]) &amp; (~(A[18])))) &a…
has comment: http://stackoverflow.com/comment/85790810

http://stackoverflow.com/comment/85663039
has text: Bender - Went back to the browser and it did work. It brought up my authentication required. Completed this form and the video started.
score: 0
comment on: http://stackoverflow.com/q/49329929
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85707096
type: AnswerComment
has text: Looking at your question closely, I suppose you'd want to call super() last, but I'm not exactly following what you're trying to do here. It all seems a bit redundant
type: Comment
comment on: http://stackoverflow.com/a/49353263
score: 0

bit
tag name: bit
type: Tag
tags question: http://stackoverflow.com/q/49397709
tags question: http://stackoverflow.com/q/49306743

http://stackoverflow.com/q/49380738
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: The following piece of code works fine when I run the script in pycharm import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.patches as mpatches c1 = mpatches.Patch(color="green",label="No Traffic") c2 = mpatches.Patch(color="red",label="Traffic") df = predict_df.limit(100).toPandas() colors = {0:"red",1:"green"} fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(df["avgSpeed"],df["vehicleCount"],df["avgMeasuredTime"],c=df["prediction"].apply(lambda x: colors[x]),s=100,marker="o") ax.set_xlabel('avgMeasuredTime') ax.set_ylabel('avgSpeed') ax.set_zlabel('vehicleCount') plt.title("BiKmeans Traffic Data") plt.legend(handles=[c1,c2]) plt.show() I have installed matplotlib using pip, also based on some similar questions tried to install as sudo apt-get install python-matplotlib but I get the same error in Zepplin, File "/home/benjamin/.local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 280, in &lt;lambda&gt; key=lambda col: col.do_3d_projection(renderer), AttributeError: 'PathCollection' object has no attribute 'do_3d_projection' The version of matplotlib is 2.2.0
downvote count: 0
has title: Apache Zeppelin gives error when using matplotlib
tagged with: apache-zeppelin
score: 2
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/q/49340026
tagged with: django-forms
has comment: http://stackoverflow.com/comment/85689773
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I am trying to create a very basic form that allows the user to upload a txt file. the function form.is_valid() always fails and I don't know what to do. This is my code: (very similar to the example in the django documentation): views.py from django import forms from django.http import HttpResponse from django.shortcuts import render class UploadFileForm(forms.Form): # title = forms.CharField(max_length=50) file = forms.FileField() def handle_uploaded_file(f): with open('some/file/name.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def home(request): if request.method == 'POST': print(1) form = UploadFileForm(request.POST, request.FILES) print(form.errors) print(2) if form.is_valid(): print(3) handle_uploaded_file(request.FILES['file']) return HttpResponse('thanks') else: form = UploadFileForm() return render(request, 'home.html', {'form': form}) home.html {% extends "base.html" %} {% block content %} Choose file to attach {% csrf_token %} {{ form.file }} {% endblock %} url.py from django.urls import path from django.contrib import admin from django.conf.urls import url from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^$', views.home, name='/success/url/'), ]
has title: form.is_valid() always fails
answer count: 0
score: 1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85680456
downvote count: 0
has comment: http://stackoverflow.com/comment/85680425
upvote count: 1

http://stackoverflow.com/comment/85856219
has text: I'm looking for effective way of communicating between processes. If one process receives msgs from many processes, it needs to infinitely loop over every connection to check if there is msg pending. Is there a way for process to wait/freeze for msg from any of child processes?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49426565
score: 0

http://stackoverflow.com/a/49282989
downvote count: 0
has body: In my opinion this should be fine, because if you check the documentation of both dask and sklearn, you will find out that both are built on top numpy, which uses parallel processing. If you really want to use only dask you could check this repo out: https://pypi.python.org/pypi/dask-distance It includes a cosine similarity function.
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49282800

http://stackoverflow.com/q/49323696
score: 2
has body: I have a similar question as asked here (Strip suffix from all variable names in SPSS) and the answers there already helped a lot but there is still one question remaining. I have a dataset in which every variable name has the prefix "v23_1_". I want to remove this prefix from all variables, but there are hundreds of them, so I am looking for a way to do it without using the RENAME statement hundreds of times. I used this code: begin program. vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") spss.Submit(r""" rename variables ( %s = %s) . """ %(myvar, mynewvar)) end program. Here is a list of the first few variables: v23_1_dg_mnppusid v23_1_dg_sigstatus v23_1_dg_mnpvsno v23_1_dg_mnpvslbl v23_1_dg_mnpcvpid v23_1_dg_mnpvisid v23_1_dg_mnpvisno v23_1_dg_mnpvispdt v23_1_dg_mnpvisfdt v23_1_dg_mnpfs0 v23_1_dg_mnpfs1 v23_1_dg_mnpfs2 v23_1_dg_mnpfs3 v23_1_dg_mnpfcs0 v23_1_dg_mnpfcs1 v23_1_dg_mnpfcs2 It worked ok for the first variables but then stopped with the message "renaming has created two variables named dg_mnpfs". But the next variable would after stripping has the name "dg_mnpfs2". What has happened is that the 1 at the end in "v23_1_dg_mnpfs1" gets deleted too. And then it propbably intends to also delete the 2 at the end in "v23_1_dg_mnpfs2", which will then lead to the same variable. I don't understand why this is happening and how I can avoid it. Thanks a lot for your support! Kind regards, Beate
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85766608
possible better answer: http://stackoverflow.com/a/49340165
has comment: http://stackoverflow.com/comment/85651538
tagged with: macros
downvote count: 0
favorite count: 0
type: Question
has title: Strip prefix from all variable names in SPSS
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49325066
tagged with: spss
has answer: http://stackoverflow.com/a/49325066
has answer: http://stackoverflow.com/a/49340165
tagged with: rename
tagged with: python
tagged with: variables
linked to: http://stackoverflow.com/q/34798827

http://stackoverflow.com/q/49357315
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85753366
accepted answer: http://stackoverflow.com/a/49377086
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/85754048
has comment: http://stackoverflow.com/comment/85734404
has comment: http://stackoverflow.com/comment/85753351
answer count: 1
has comment: http://stackoverflow.com/comment/85754267
has comment: http://stackoverflow.com/comment/85714599
tagged with: kivy
has body: from kivy.app import App from kivy.clock import Clock from kivy.uix.widget import Widget from kivy.uix.anchorlayout import AnchorLayout from kivy.lang import Builder from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout Builder.load_string(""" &lt;WaterFill&gt;: id: c_canvas level: 0.0 width: self.height size_hint: None, 1 color: 0, 0, 1 canvas: StencilPush Ellipse: group: 'a' size: (200, 200) pos: 150,270 StencilUse Color: rgb: root.color Rectangle: group: 'a' pos: root.pos size: (root.width, root.level*root.height) StencilUnUse StencilPop Ellipse: group: 'b' size: (200, 200) pos: 450,270 Button: text: 'Try me!' on_release: root.press_me() """) class WaterFill(Widget): def __init__(self, *args, **kwargs): Widget.__init__(self, *args, **kwargs) self.delta = 0.01 Clock.schedule_interval(self.on_timeout, 0.05) def on_timeout(self, *args): #self.root.ids.c_canvas.canvas.get_group('a').level += self.delta #i tried by id and by group but unabel to find solution self.level += self.delta if self.level &gt;= 1: #self.delta = -0.01 self.delta = -1.1 elif self.level &lt;= 0: self.delta = 0.01 def press_me(self): print("pressed") # on press need to fill circle class TestApp(App): def build(self): #lay = AnchorLayout(anchor_x='center', anchor_y='center') #lay.add_widget(WaterFill()) return WaterFill() if __name__ == "__main__": TestApp().run() how i change 2 or more circle fill layout with Kivy GUI - fill color in circle like water fill in circle container level wise same logic. i tried by defining id but fails any way to do this??? please help how to use canvas design for 2 or more circle !!!
has comment: http://stackoverflow.com/comment/85753928
downvote count: 1
linked to: http://stackoverflow.com/q/49235731
favorite count: 0
type: Question
has title: Kivy GUI - fill color in circle like water fill in circle container level wise for two or more tank
has comment: http://stackoverflow.com/comment/85754203
has comment: http://stackoverflow.com/comment/85753434
has answer: http://stackoverflow.com/a/49377086
has comment: http://stackoverflow.com/comment/85754173
has comment: http://stackoverflow.com/comment/85753990
has comment: http://stackoverflow.com/comment/85753412
has comment: http://stackoverflow.com/comment/85753875

spss
tags question: http://stackoverflow.com/q/49323696
type: Tag
tag name: spss

http://stackoverflow.com/a/49368381
has comment: http://stackoverflow.com/comment/85738980
score: 3
has body: &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; var('X') X &gt;&gt;&gt; latex(S('10**20/X', evaluate=False)) '\\frac{10^{20}}{X}' See https://github.com/sympy/sympy/wiki/Quick-examples. EDIT: Your edited question differs considerably from the original. Here's an answer to it. Because your input values might not be powers of ten r might not be. Consequently, when it is expressed as a power of ten its exponent might not be an integer; hence, the use of base ten logarithms. from sympy import latex, sympify, Symbol from math import log10 a=10 b=100 c=1000 d=10000 r = a * b * c * d exponent = log10(r) X = Symbol('X') s = latex(sympify('10**{}/X'.format(exponent), evaluate=False)) print (s) The result for these values of a, b, c and d is \frac{10^{10.0}}{X}.
answers question: http://stackoverflow.com/q/49367869
has comment: http://stackoverflow.com/comment/85738091
has comment: http://stackoverflow.com/comment/85739890
has comment: http://stackoverflow.com/comment/85740342
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/85738855
has comment: http://stackoverflow.com/comment/85737883
has comment: http://stackoverflow.com/comment/85742337
type: Answer

http://stackoverflow.com/a/49418078
type: AcceptedAnswer
has body: (Posted on behalf of the question author). It was exactly what caused the problem and I honestly don't understand how I even made such a dumb mistake. Hopefully it will help someone in the future. In short: What was causing the problem for me was that I tried matching a grayscale video stream to an rgb template, that doesn't work. I think it has something to do with the depth of the image or it's channels. Make sure you compare grayscale to grayscale.
has comment: http://stackoverflow.com/comment/137332793
answers question: http://stackoverflow.com/q/49391103
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49391103
score: 3
upvote count: 3

http://stackoverflow.com/comment/85781307
type: Comment
type: QuestionComment
score: 0
has text: I dont get it. Why on earth he will get that error?
comment on: http://stackoverflow.com/q/49389292

http://stackoverflow.com/q/49320727
type: Question
has title: Searching for similar elements in a list of list
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/49320874
tagged with: python
has answer: http://stackoverflow.com/a/49320838
has answer: http://stackoverflow.com/a/49321073
downvote count: 4
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/85642322
has body: I have a table containing: table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']] and I'm writing a python function to traverse through the table, look for similarities in the string elements and printing out in the format: Movie: FANTASTIC FOUR, EXOTIC SPACE UserID: 1,20 #since user 1 and user 20 both watch exactly the same movie I have tried writing: i = 0 while i&lt;len(table)-1: g = table[i][1:] if g == table[i+1][1:]: print(table[i][0],table[i+1][0]) i+=1 but it's not working very well. I'm not that good at using while loops for printing so i'll appreciate some help on this.
has comment: http://stackoverflow.com/comment/85642407
favorite count: 0

http://stackoverflow.com/comment/85896287
has text: what is clone outliner editor ? is it something from maya ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49436679
score: 0
type: Comment

http://stackoverflow.com/comment/86191014
type: Comment
has text: I am sure switching languages like to java would help but is too time consuming, but would you be interested in looking in frameworks such as Apache beam? I could describe the use case for you
comment on: http://stackoverflow.com/a/49525170
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85635805
has text: what should the answer be for [1,2,3] and 2 connectives?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49317166
type: QuestionComment

http://stackoverflow.com/q/49374511
tagged with: recurrent-neural-network
tagged with: keras
has comment: http://stackoverflow.com/comment/85752760
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85751393
has title: Keras: Unable to continue training of loaded model
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85750796
has answer: http://stackoverflow.com/a/51200293
tagged with: python
has comment: http://stackoverflow.com/comment/85751616
linked to: http://stackoverflow.com/q/42666046
has body: I saved an RNN (GRU) model using model.save but when I run the fit function after I load the model, it messes up my weights and gives incorrect predictions. However, I get the correct predictions when I predict without running the fit function. opt = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, decay=0.01) rnn_model.compile(loss='binary_crossentropy', optimizer=opt, metrics=["accuracy"]) rnn_model.save('./models/my_model.h5') #This predicts correctly model = load_model('my_model.h5') model.predict(x) #This does NOT predict correctly model=load_model('my_model.h5') model.fit(X, Y, batch_size = 5, epochs=1) model.predict(x) Update (workaround found): I haven't figured out the root of the problem. But it seems that the model that I was loading was saved on Keras 2.0.6 and I am loading it on to Keras 2.1.5. Something with the "save_weights" and "load_weights" functions was not working, so I had to load the weights layer by layer on an architecture I built from scratch manually (loading the architecture from the saved model using json worked as well): for layer_loaded, layer_built in zip(loaded_model,built_model): layer_built.set_weights(layer_loaded.get_weights())
score: 0
has comment: http://stackoverflow.com/comment/85751822
answer count: 1

http://stackoverflow.com/comment/85774344
type: QuestionComment
has text: But here the scenario is the element are already present as i the same form is loaded again
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49386564

http://stackoverflow.com/q/49398430
has body: I want to perofrm UCM for Multivarate Data in Python in with my dependent variables as lets say Sales and Independent variable as Promo_Var1,Promo_Var2, Promo_Var3. Can we do something like this below import statsmodels.api as sm model = sm.tsa.UnobservedComponents(df['Sales'],df['Promo_Var1','Promo_Var2','Promo_Var3']).fit()
tagged with: python
has comment: http://stackoverflow.com/comment/85814903
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85843891
type: UnansweredQuestion
has title: Unobserved Component Model in Python
type: Question
has comment: http://stackoverflow.com/comment/85858014
tagged with: statsmodels

skygear
tag name: skygear
type: Tag
tags question: http://stackoverflow.com/q/49405183

http://stackoverflow.com/comment/85638281
type: QuestionComment
has text: Which version of Python?
comment on: http://stackoverflow.com/q/49318551
score: 0
type: Comment

http://stackoverflow.com/comment/85790232
comment on: http://stackoverflow.com/q/49393789
score: 0
has text: Here you have it now
type: Comment
type: QuestionComment

http://stackoverflow.com/a/58027750
upvote count: 3
has body: The previous method will be deprecated: use nx.selfloop_edges() instead
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49427638

http://stackoverflow.com/comment/85700834
score: 1
type: Comment
type: QuestionComment
has text: @saloni - SSE2, SSSE3, SSE4, AVX, AVX2, BMI, BMI2 and friends are CPU features. You can't install them. Older machines, Like Core Solo and Duo, lack them. For newer machines, Intel sells low end processors that only have SSE2, SSSE3 and AESNI. They lack SSE4 and above. OEM's have to request the product from Intel, like an [Atom D2550](https://ark.intel.com/products/65470/Intel-Atom-Processor-D2550-1M-Cache-1_86-GHz). Also see Crypto++ [Pull Request 72](https://github.com/weidai11/cryptopp/pull/172), which avoided a SIGILL crash because AESNI was available but not SSE4.1.
comment on: http://stackoverflow.com/q/49348999

http://stackoverflow.com/comment/85604481
has text: At the beginning of each iteration of the loop, `dict_1 = {}` will be executed, creating an empty dictionary. After the loop ends, `dict_1` will still exist, with all the data you added to it in the final loop iteration.
comment on: http://stackoverflow.com/q/49301365
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85851289
has text: I have found the executable
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49425007

http://stackoverflow.com/a/49462983
upvote count: 1
has comment: http://stackoverflow.com/comment/85963689
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85951525
answers question: http://stackoverflow.com/q/49405887
has comment: http://stackoverflow.com/comment/85990030
has body: I'm seeing similar behavior as you. Except that regardless of the workaround policy, the process always hangs without any exception thrown. Even stranger is that it's working on a colleagues machine and not mine. I have tried on two other machines and docker container and both hang. Next, I'm going try strip everything down to a minimal containerized example I can take to Google and hopefully get some feedback from them. Let me know if you learn anything in the interim.
downvote count: 0

http://stackoverflow.com/comment/85846695
has text: Specifically, you want https://stackoverflow.com/a/46746088/248065
comment on: http://stackoverflow.com/q/49422745
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49327240
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49327735
has comment: http://stackoverflow.com/comment/85656582
has answer: http://stackoverflow.com/a/49327735
has answer: http://stackoverflow.com/a/49327691
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49327718
score: 4
answer count: 4
linked to: http://stackoverflow.com/q/17604665
tagged with: ranking
upvote count: 4
type: AnsweredQuestion
has title: Rank DataFrame based on multiple columns
linked to: http://stackoverflow.com/q/49279404
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49327793
has body: How can I rank a DataFrame based on 2 columns? On below example, col_b would the tie breaker for col_a. DataFrame: df = pd.DataFrame({'col_a':[0,0,0,1,1,1], 'col_b':[5,2,8,3,7,4]}) df col_a col_b 0 0 5 1 0 2 2 0 8 3 1 3 4 1 7 5 1 4 Expected Output: col_a col_b Rank 0 0 5 2 1 0 2 1 2 0 8 3 3 1 3 4 4 1 7 6 5 1 4 5
has answer: http://stackoverflow.com/a/49327718

http://stackoverflow.com/q/49322980
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49323064
accepted answer: http://stackoverflow.com/a/49323064
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85647456
has title: AttributeError: Unknown property yerr
has body: I have been able to get my plot with matplotlib when I plotted without error bars. However, when I try to add the yerr parameters in (to get standard error bars), I get an error AttributeError: Unknown property yerr The erroneous code is: for i in range (3): j=i+1 plt.plot([1,2],[totalcount_baseline[i], totalcount_treatment[i]], yerr=[yerr_list_baseline[i], yerr_list_treatment[i]], label='label%d'%j) As seen in the code above, 1 and 2 are my x axis values, totalcount is the y axis values, and yerr contains a list of two numeric values. My code works (displays a plot), if I remove the yerr parameters. plt.plot([1,2],[totalcount_baseline[i], totalcount_treatment[i]], label='label%d'%j) Thus, how can I modify my code to obtain the error bars?
type: Question
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/q/49332044
has comment: http://stackoverflow.com/comment/85666177
tagged with: python-2.7
score: 0
tagged with: if-statement
has title: For, if, else statements
tagged with: python
has comment: http://stackoverflow.com/comment/85666149
type: Question
has comment: http://stackoverflow.com/comment/85669406
has comment: http://stackoverflow.com/comment/85666634
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85682220
has answer: http://stackoverflow.com/a/49334669
has body: So I have a multilayered problem. I am trying to I am trying to just print out 'input was jack' if the raw_input was 'jack' and also subtract 'tries' by 1, and then run the function again and print out amount of 'tries' at the end of both the first 'if' statement and the 'else' statement, and if the raw_input wasn't 'jack' it adds 1 to 'tries' and if 'tries' reaches a total of 4 the function prints stop. I have run into a couple of different problems. Either the counter seems to reset every single time so it's always just '1' or I can't just keep running the function. It just doesn't seem like it's following the 'if or else' theory I thought it would be. So I have the following code: tries = 0 def usrinfo(): name = raw_input('input name ') a = ('jill','jack',name,'meg') for element in a: if element == 'jack': print('input was jack') tries =-1 print(tries) usrinfo() else: if element != 'jack': tries =+ 1 return tries print(tries) usrinfo() if tries == 4: print('stopped') usrinfo() If I type 'jack' I get: Nothing...as in a blank output I want: input was jack -1 Then I want the function to run again...and get input was jack -2 And so on. If I type anything other than 'jack' I get: Nothing...as in a blank output I want to get: 1 Then for the function to run again....and get 2 Then if I type anything other than 'jack'. I want with each attempt to print the increasing level of tries from 1 - 4 such as below: 1 2 3 4 Then when it reaches 4 it prints 'stopped' or runs whatever command. I want to essentially keep the code running and control the value of 'tries' according to whether or not the input is 'jack' or something else. Because even when I create an even simpler code like this: def userinput(): tries = 0 username = raw_input('input username ') if username == 'jack': tries -=1 print(username + ' '+ str(tries) + ' success') userinput() else: if username != 'jack': tries +=1 print('tries ' + str(tries)) userinput() userinput() My results on this code with input of 'f' a…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85666292
has comment: http://stackoverflow.com/comment/85666738
has answer: http://stackoverflow.com/a/49332777
has comment: http://stackoverflow.com/comment/85681144
has comment: http://stackoverflow.com/comment/85666258
has comment: http://stackoverflow.com/comment/85666308
has comment: http://stackoverflow.com/comment/85666348

http://stackoverflow.com/a/49310162
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/85622495
has comment: http://stackoverflow.com/comment/85622486
answers question: http://stackoverflow.com/q/49310086
score: 2
has body: jpp's solution is probably the cleaner way to go, but in order to clarify why your code doesn't work: Your issue is that your id that you want to merge on in visitcounts is actually your index, and not the column named id: &gt;&gt;&gt; visitcounts id id 111 3 122 1 133 1 So, if you wanted to use merge, you could merge on the index for visitcounts and on the column idof your df, it should work: # First rename column in visitcounts to `count`: visitcounts.columns=['count'] # Then merge: merged_df = pd.merge(df, visitcounts, left_on='id', right_index=True) &gt;&gt;&gt; merged_df index id name dob visit count 0 0 111 Joe 1/1/2000 1/1/2018 3 1 1 111 Joe 1/1/2000 1/5/2018 3 4 4 111 Joe 1/1/2000 12/31/2018 3 2 2 122 Bob 1/1/1999 2/8/2018 1 3 3 133 Jill 1/2/1988 7/9/2017 1

http://stackoverflow.com/q/49279596
score: 1
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-slim
has answer: http://stackoverflow.com/a/49281899
has body: I am using tensorflow version 1.5 on Windows 10. I am using the Tensorflow slim model of Inception V4 network which has been picked up from the Website, using their pretrained weights and adding my own layers at the end to classify 120 different objects. This is the complete code except the lines containing the import modules and dataset paths. image_size = 299 tf.logging.set_verbosity(tf.logging.INFO) with slim.arg_scope(inception_blocks_v4.inception_v4_arg_scope()): X_input = tf.placeholder(tf.float32, shape = (None, image_size, image_size, 3)) Y_label = tf.placeholder(tf.float32, shape = (None, num_classes)) targets = convert_to_onehot(labels_dir, no_of_features = num_classes) targets = tf.constant(targets, dtype = tf.float32) Images = [] images = glob.glob(images_file_path) i = 0 for my_img in images: image = mpimg.imread(my_img)[:, :, :3] image = tf.constant(image, dtype = tf.float32) Images.append(image) logits, end_points = inception_blocks_v4.inception_v4(inputs = X_input, num_classes = pre_num_classes, is_training = True, create_aux_logits= False) pretrained_weights = slim.assign_from_checkpoint_fn(ckpt_dir, slim.get_model_variables('InceptionV4')) with tf.Session() as sess: pretrained_weights(sess) my_layer = slim.fully_connected(logits, 560, activation_fn=tf.nn.relu, scope='myLayer1', weights_initializer = tf.truncated_normal_initializer(stddev = 0.001), weights_regularizer=slim.l2_regularizer(0.00005),biases_initializer = tf.truncated_normal_initializer(stddev=0.001), biases_regularizer=slim.l2_regularizer(0.00005)) my_layer = slim.dropout(my_layer, keep_prob = 0.6, scope = 'myLayer2') my_layer = slim.fully_connected(my_layer, num_classes,activation_fn = tf.nn.relu,scope= 'myLayer3', weights_initializer = tf.truncated_normal_initializer(stddev=0.001), weights_regularizer=slim.l2_regularizer(0.00005), biases_initializer = tf.truncated_normal_initializer(stddev=0.001), biases_regularizer=slim.l2_regularizer(0.00005)) my_layer_logits = slim.fully_connected(…
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: I get an Invalid Argument Error on feeding tensors to a graph in tensorflow?

http://stackoverflow.com/q/49418578
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49418683
tagged with: django
tagged with: python
has body: I have django models that are simplified as: class Client(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class ClientDetail(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) business_format = models.CharField(max_length=255) def __str__(self): return "Details for {}".format(self.client.name) class ClientAssignment(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) def __str__(self): return "Assignment: {} for Client: {}".format(self.assignment.name, self.client.name) class Assignment(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name I am using django-rest-framework and would like to create a view where I can provide client_id and receive a serialized object that contains all 3 related models. I tried using PrimaryKeyRelatedField as follows but I'm not sure if I'm using this correctly. class CompleteClientObject(ModelSerializer): assignment = PrimaryKeyRelatedField(many=True, queryset=ClientAssignment.objects) detail = PrimaryKeyRelatedField(many=True, queryset=ClientDetail.objects) client = PrimaryKeyRelatedField(queryset=Client) class Meta: model = Client fields = ("id", "name", "detail", "assignment",) How can I achieve this using serializers?
has answer: http://stackoverflow.com/a/49418683
score: 4
upvote count: 4
has title: Serialize related models in Django Rest Framework
type: AnsweredQuestion
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/a/49461170
type: Answer
has body: Thanks to the answer of Yngve Moe I have managed to write this function def plot_yerr_filled(x=None, y=None, axis=plt, color=(0,0,0), alpha=0.25, *args, **kwargs): """Creates a 'filled error bar' plot. All keyword arguments in matplotlib functions are accepted. Parameters ---------- x : Array like (list of float, int, etc. or numpy.array or list of magnitude) of exact 'x' values (i.e. with no error, if 'x' is a list of 'magnitude' type objects, errors are discarded). y : Array like (list) of 'magnitude' type elements containing the 'y' values and the 'yerr' associated error. axis: matplotlib.axes (optional) in which to plot the data. color: tuple (r,g,b) defining the color. alpha: float between 0 and 1 indicating the transparency of the filled error bar. """ for i in range(0, len(x)): # Validation of x if isinstance(x[i], magnitude): x[i] = x[i].val for i in range(len(y)): # Validation of y if not isinstance(y[i], magnitude): raise ValueError('y[' + str(i) + '] is not of type "magnitude"') y_val = [y[i].val for i in range(len(y))] y_err = [y[i].err for i in range(len(y))] axis.fill_between(np.array(x), np.array(y_val)-np.array(y_err), np.array(y_val) + np.array(y_err), alpha=alpha, edgecolor=color, facecolor=color ) lines = axis.plot(np.array(x), np.array(y_val), color=color, *args, **kwargs) return lines which does exactly what I wanted. Here I let an example import pymagpy as mg import matplotlib.pyplot as plt plt.rc('axes', axisbelow=True) # This is for plotting data in front of the grid. plt.rcParams.update({'font.size': 8}) # Changes the default font size for the plots. import numpy as np x = mg.magnitude(1, 0.1) y = mg.magnitude(-6798, 6) z = mg.magnitude(1e-30, .00002872982778297289e-30) print(x) print(y) print(z) print(x+y/z*2-z/x*y) # Automatically calculates the error propagation. x_values = [] y_values = [] z_values = [] for k in range(10): x_values.append(mg.magnitude(k, k**2)) y_values.append(mg.magnitude(k**2, k)) z_values.append(mg.magnitude(np.sqrt(3…
accepted answer of: http://stackoverflow.com/q/49428050
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49428050

http://stackoverflow.com/q/49332610
upvote count: 0
has answer: http://stackoverflow.com/a/49332626
has body: I want to get data from multiple api in django using request.get() method. Normally we fetched data like this: response = requests.get('http://freegeoip.net/json/') Is it possible to get data from 3 different api like this. response=requests.get('http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com');
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49332689
has title: How to consume rest apis more than one with django?
has answer: http://stackoverflow.com/a/49332712
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85667116
tagged with: python
score: -1
answer count: 3
tagged with: api

http://stackoverflow.com/q/49393566
favorite count: 0
type: Question
has title: TensorFlow: Memory Allocation Alignment
type: UnansweredQuestion
tagged with: python
tagged with: memory-management
answer count: 0
has body: In TensorFlow, when I create a variable like this, kernel = tf.Variable(tf.truncated_normal([3, 3, 2, 1], dtype=tf.float32,stddev=1e-1), name='weights') 18 32-bit floating point variables are allocated in 72 (3*3*2*1*4) consecutive bytes. How can I align this variables in such a way that first 3*3 floating point values go to first 36 bytes of a 64 byte block and then the next 3*3 floating point values are allocated to the first 36 byte of the next 64 byte block. So far, I am only concerned with CPUs.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85793106
downvote count: 0
has comment: http://stackoverflow.com/comment/85789043
tagged with: tensorflow

http://stackoverflow.com/comment/85583509
has text: I won't be able to specify K4 directly, it could be any value. I need to iterate the dictionary items (all values -maybe using some loop function to know the length and then sort.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49289907

http://stackoverflow.com/comment/85866009
type: Comment
comment on: http://stackoverflow.com/a/49431899
type: AnswerComment
has text: @edge27 - ithink because working with columns names, if working with index is necessary specify it too, `df.T.groupby(level=0).sum()` is same as `df.T.groupby(level=0, axis=0).sum()`. So for columns need `axis=1` for get columns and `level=0` for first level. also I think it is for distinguish if `MultiIndex` in columns, then is possible specify always level like `df = df.groupby(level=1, axis=1).sum()`
score: 0

http://stackoverflow.com/comment/85820387
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49406740
has text: Thank you a lot for your reply! It helped me a lot!
type: Comment

http://stackoverflow.com/a/49391025
has comment: http://stackoverflow.com/comment/85787940
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49390950
upvote count: 7
has body: You can look at merge df1['value']=df1'time_by_hour','id'.merge(df2,how='left').value
answers question: http://stackoverflow.com/q/49390950
type: Answer

http://stackoverflow.com/comment/85605601
type: Comment
has text: @PacmanKX Exactly, naming the column there. It's just simple string concatenation.
comment on: http://stackoverflow.com/a/49301436
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85753736
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49359884
has text: Hi @jezrael. can we split the whole dataset based on one particular column that is "tenure column"?

http://stackoverflow.com/comment/85593069
comment on: http://stackoverflow.com/a/49295381
type: Comment
has text: They are instructed to use the strings `"year"` and `"s"`, you use `"year"` and `"years"`.
type: AnswerComment
score: 0

http://stackoverflow.com/a/49342953
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49342077
answers question: http://stackoverflow.com/q/49342077
type: Answer
score: 2
has body: Yes, you can do this recursively, for example: import pandas as pd class BillOfMaterials: def __init__(self, bom_excel_path): self.df = pd.read_excel(bom_excel_path) self.df = self.df'Item', 'Material' def find_parents(self, part_number): return list(set(self.df[self.df.Material == part_number]['Item'])) def find_top_levels(self, item): parents = self.find_parents(item) if not parents: # there are no parent items =&gt; this item is a leaf return [item] else: # there are parent items =&gt; recursively find grandparents grandparents = [] for parent in parents: grandparents = grandparents + self.find_top_levels(parent) return grandparents if __name__ == '__main__': BOM = BillOfMaterials(bom_excel_path="testdata.xlsx") ItemsToSearch = ['7547-122', 'MHY00007'] for i in ItemsToSearch: print('') print('The top levels of ' + i + ' are: ') print(BOM.find_top_levels(i)) Note the recursive call of self.find_top_levels(parent). This will give the output The top levels of 7547-122 are: ['2105-0001'] The top levels of MHY00007 are: ['2094-00003', '7932-00001', '7932-00002', '7932-00010']
upvote count: 2

http://stackoverflow.com/comment/85796408
has text: @avigil It's only scary because I don't remember exactly how things that were neither classic classes nor new-style classes (like 2.2 ints) works with `isinstance`, so I want to make sure nobody uses this code without testing on the oldest version they care about… I _think_ it just always returns false for anything else, but I can't test it.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49397259

http://stackoverflow.com/comment/85693586
comment on: http://stackoverflow.com/a/49346462
type: Comment
type: AnswerComment
has text: @FaqahatFareed - Do you create dataframe by `df = pd.read_table(file)` ?
score: 0

http://stackoverflow.com/comment/85691664
has text: It should work as expected. Are you sure there are any pixels with positive values in your data?
comment on: http://stackoverflow.com/q/49345012
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49437900
has comment: http://stackoverflow.com/comment/85878112
has comment: http://stackoverflow.com/comment/85878021
has comment: http://stackoverflow.com/comment/85878044
has comment: http://stackoverflow.com/comment/85878105
has comment: http://stackoverflow.com/comment/85878214
tagged with: couchapp
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52364532
linked to: http://stackoverflow.com/q/35778495
has title: fatal error: 'Python/Python.h' file not found while installing couchapp
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52364532
has body: I am trying to install couchapp from the terminal on macOs High Sierra. I have python 2.7.10 installed (by default) and I run $ pip2 install couchapp according to the couchapp documentation. This is the error I get: src/watchdog_fsevents.c:22:10: fatal error: 'Python/Python.h' file not found #include &lt;Python/Python.h&gt; ^~~~~~~~~~~~~~~~~ 1 error generated. error: command 'cc' failed with exit status 1 ---------------------------------------- Failed building wheel for watchdog Here is what I have when I do $ ls in /System/Library/Frameworks/Python.framework/ Examples Modules Python Resources Versions module.map What I have tried so far: Check that Xcode CL Tools are already installed running $ xcode-select --install Try to use pip3 instead of pip2 (I have installed python 3.6 with Homebrew), but I get the same error message. Do you have any idea? I have read other posts but they did not solve my problem. Thank you
score: 1
answer count: 1
downvote count: 0
tagged with: macos
linked to: http://stackoverflow.com/q/6151548
has comment: http://stackoverflow.com/comment/86564109
has comment: http://stackoverflow.com/comment/85892099
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85891776

http://stackoverflow.com/a/49387050
has body: Some of your files are badly formatted in some way. You should add exception handling to your loop, this would allow the conversions to continue and would indicate which of your files are causing the problem: excel_files = glob.glob('/*xlsx*') for excel_file in excel_files: print("Converting '{}'".format(excel_file)) try: df = pd.read_excel(excel_file) output = excel_file.split('.')[0]+'.csv' df.to_csv(output) except KeyError: print(" Failed to convert") You could then try opening the failing files inside Excel to see if they load ok. If they do load, you could upload an example of a failing Excel file to something like pastebin and add a comment here with the link to it so the problem can be recreated.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49352303
upvote count: 2
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49352303

http://stackoverflow.com/a/49343318
has body: I think you can use: def calculate_tax(income): income_cumsum = income.cumsum() rate = income_cumsum.apply(lambda x: 0.13 if x&lt;=1000 else 0.2).shift(1).fillna(0.13) return (income*rate).sum()
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49337922
answers question: http://stackoverflow.com/q/49337922
type: AcceptedAnswer

http://stackoverflow.com/q/49387093
score: 1
tagged with: database
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49407467
favorite count: 0
type: Question
has title: Is there a client for InfluxDB similar to PgAdmin4 for Postgres
downvote count: 0
upvote count: 1
has body: Hi is any one aware of any clients for InfluxDB so that I can visualize the tables inside an influx database. And do that database manipulations using the visual tool.
tagged with: influxdb
has answer: http://stackoverflow.com/a/49407467
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/118323130

http://stackoverflow.com/q/49344899
accepted answer: http://stackoverflow.com/a/49344940
has title: resample dataframe for every hour
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49344940
score: 7
upvote count: 7
answer count: 1
favorite count: 0
type: Question
has body: I want to resample the data in Sms ,call and Internet column by replacing the value by their mean for every hour. Code 1 tried : df1.reset_index().set_index('TIME').resample('1H').mean() error:Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index' Code 2 tried: df1['TIME'] = pd.to_datetime(data['TIME']) df1.CALL.resample('60min', how='mean') error: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' Dataframe: ID TIME SMS CALL INTERNET 0 1 2013-11-30 23:00:00 0.277204 0.273629 13.674575 1 1 2013-11-30 23:10:00 0.341536 0.058176 13.330858 2 1 2013-11-30 23:20:00 0.379427 0.054601 11.329552 3 1 2013-11-30 23:30:00 0.600781 0.218489 13.166163 4 1 2013-11-30 23:40:00 0.405565 0.134176 13.347791 5 1 2013-11-30 23:50:00 0.187700 0.080738 12.434744 6 1 2013-12-01 00:00:00 0.282651 0.135964 13.860353 7 1 2013-12-01 00:10:00 0.109826 0.056388 12.583463 8 1 2013-12-01 00:20:00 0.348638 0.053438 12.644995 9 1 2013-12-01 00:30:00 0.138375 0.054062 12.251733 10 1 2013-12-01 00:40:00 0.054062 0.163803 11.292642 df1.dtypes ID int64 TIME object SMS float64 CALL float64 INTERNET float64 dtype: object

http://stackoverflow.com/comment/86010836
comment on: http://stackoverflow.com/q/49352971
type: Comment
type: QuestionComment
has text: Nobody? really? so sad.
score: 0

http://stackoverflow.com/q/49404793
upvote count: 2
type: UnansweredQuestion
has body: I want to write an abstract base class that should enforce that its derived classes implement one method with specific parameters and specific returns. However, since in Python you specify neither the return type nor the argument types in the method's signature, how can I enforce such an interface? For example: class BaseClass(ABC): @abstractmethod def __call__(self, image, labels=None): pass I want derived classes to have to implement the __call__() method such that it accepts as arguments a 3D Numpy array (image) and, optionally, a 2D Numpy array (labels), and that it returns a 3D Numpy array (the transformed image) and, once again optionally, a 2D Numpy array (the transformed labels). How can I enforce, for example, that the __call__() method in a derived class must return exactly that (a 3D Numpy array and, optionally, a 2D Numpy array)?
has comment: http://stackoverflow.com/comment/85810524
tagged with: python
has comment: http://stackoverflow.com/comment/85810637
score: 2
tagged with: abstract-class
answer count: 0
downvote count: 0
has title: Using abstract base classes to specify an interface enforcing input and return types
favorite count: 0
type: Question

signals
tags question: http://stackoverflow.com/q/49426485
type: Tag
tags question: http://stackoverflow.com/q/49414471
tags question: http://stackoverflow.com/q/49284591
tag name: signals

http://stackoverflow.com/q/49363247
tagged with: list
has answer: http://stackoverflow.com/a/49363633
downvote count: 2
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85726582
has comment: http://stackoverflow.com/comment/85727377
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85727399
accepted answer: http://stackoverflow.com/a/49363324
has comment: http://stackoverflow.com/comment/85727471
has answer: http://stackoverflow.com/a/49366823
has answer: http://stackoverflow.com/a/49363324
tagged with: arrays
tagged with: python
score: -1
answer count: 4
has comment: http://stackoverflow.com/comment/85726696
has title: How to combine multiple lists into one using first element of each list as key?
has body: I use Python 3.6.4. I have multiple lists inside a list, but with the same keys (first element of inner list) for certain elements: [[1, 100], [1, 250], [2, 340], [2, 5200]] Element 0 is the same for the first 2 inner lists. How can I combine those to one list by the same keys to get something like this: [[1, 100, 250], [2, 340, 5200]] In my case, max count of the same keys is always two.
possible better answer: http://stackoverflow.com/a/49363633
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85727383
has answer: http://stackoverflow.com/a/49365230

http://stackoverflow.com/q/49304234
tagged with: python-3.6
tagged with: exe
has title: Creating a stand alone program from Python 3.6 - with xml files
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85610793
type: UnansweredQuestion
has body: I want to create a stand-alone program from a Python project. Part of my data is saved in xml files, so I need them to be a part of the build Wich program can help me do so? Thanks, Avishay
tagged with: python
has answer: http://stackoverflow.com/a/49304586

http://stackoverflow.com/comment/85700845
score: 0
comment on: http://stackoverflow.com/q/49344251
type: Comment
type: QuestionComment
has text: Welcome! -------

http://stackoverflow.com/a/49370890
has comment: http://stackoverflow.com/comment/85742836
answers question: http://stackoverflow.com/q/49370769
type: Answer
has comment: http://stackoverflow.com/comment/85756324
score: 2
upvote count: 2
downvote count: 0
has body: You could do what you want like this: class MyClass(object): def __init__(self,name): self.name=name @classmethod def alternative_init(cls,name,surname): new_instance = cls(name) new_instance.surname = surname return new_instance a = MyClass.alternative_init('Bob', 'Spongy') print(a.name, a.surname) # Bob Spongy

http://stackoverflow.com/comment/85688352
has text: is there a way to specify the number value being between 0 and 255 with regex in this manner?
type: Comment
comment on: http://stackoverflow.com/a/49332834
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85894062
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49389898
has text: @AllenLavoie thanks passing a batch size of 100 seems to solve the problem. It appears that even I have specified num_epochs=1, it reused 32 examples to complete the last batch to 128, but when I use 100 it will not to do that.
type: Comment

http://stackoverflow.com/q/49351479
tagged with: reddit
has comment: http://stackoverflow.com/comment/85705791
type: UnansweredQuestion
tagged with: redditkit
tagged with: python
has title: Reddit Bot Stops commenting after certain time
score: 2
has comment: http://stackoverflow.com/comment/85703104
tagged with: bots
answer count: 0
downvote count: 0
has body: I have been trying to make a bot that searches for a specific keyword in the reddit title, if that keyword is true it would then comment something in that thread. Everything works find, just I have one problem, after around 4 hours of it running it keeps searching but it stops commenting for some reason, no idea why. Then I restart it and it works ok. It seems to happen around 3pm PST everyday, it keeps on printing that it is searching but it just wont comment even if there are posts that contain the keywords. Is this somehting that reddit does to stop bots or is something wrong with my code. Before I had the reddit praw statement ouside of my 3 subreddit functions, but I wanted to test if i kept on reconnecting to the prawl after every seach would it stop the issue. In sort my reddit bot stops commenting after a certain point and is there any way I could fix this or is it permanent. #!/usr/bin/python import praw import pdb import re import os import threading import time sub1_array = ['Title'] sub1_array = ['Comment'] def sub1(): reddit = praw.Reddit('bot1') if not os.path.isfile("posts_replied_to.txt"): posts_replied_to = [] else: with open("posts_replied_to.txt", "r") as f: posts_replied_to = f.read() posts_replied_to = posts_replied_to.split("\n") posts_replied_to = list(filter(None, posts_replied_to)) subreddit = reddit.subreddit('sub1') print("Checking sub1") for submission in subreddit.new(limit=20): i = 0 while i &lt;= (len(sub1_array) - 1): # If we haven't replied to this post before if submission.id not in posts_replied_to: # Do a case insensitive search if re.search(sub1_array[i], submission.title, re.IGNORECASE): # Reply to the post submission.reply(link_array[i]) print("Bot replying to match: ", submission.title) del sub1_array[i] del sub1_array[i] posts_replied_to.append(submission.id) time.sleep(100) else: i += 1 else: i += 1 with open("posts_replied_to.txt", "w") as f: for post_id in posts_replied_to: f.write(post_id + "\n") sub2_array = ['Title'] su…
tagged with: jreddit
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85702915

http://stackoverflow.com/a/49295674
has comment: http://stackoverflow.com/comment/127996257
upvote count: 2
answers question: http://stackoverflow.com/q/49285546
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49285546
has body: Assuming your django application is named myapp, this is a function that returns all of the classes that inherit an abstract base class: from django.apps import apps def get_subclasses(abstract_class): result = [] for model in apps.get_app_config('myapp').get_models(): if issubclass(model, abstract_class) and model is not abstract_class: result.append(model) return result This works in django 1.11, you must possibly adapt it with other version.
type: AcceptedAnswer

http://stackoverflow.com/a/49393610
has comment: http://stackoverflow.com/comment/85789249
has comment: http://stackoverflow.com/comment/85789729
upvote count: 2
has comment: http://stackoverflow.com/comment/85789602
answers question: http://stackoverflow.com/q/49392915
downvote count: 0
has body: You say you want to keep indexing, that means numpy is out (someone already posted a numpy solution as well). My recommendation would be to create a series of DataFrames, as panels are deprecated. new series = pd.Series() for index, element in pds: new_series.append(pd.DataFrame(element)) Should do the trick.
type: Answer
has comment: http://stackoverflow.com/comment/85789000
score: 2

http://stackoverflow.com/q/49408298
type: AnsweredQuestion
tagged with: python
has body: The following piece of code is getting the data from Excel in the 5th row and the 14th row: import pandas as pd import pymssql df=[] fp = "G:\\Data\\Hotels\\ABZPD - Daily Strategy Tool.xlsm" data = pd.read_excel(fp,sheet_name ="CRM View" ) row_date = data.loc[2, :] row_sita = "ABZPD" row_event = data.iloc[11, :] df = pd.DataFrame({'date': row_date, 'sita': row_sita, 'event': row_event }) print(df) However, it is not actually using the worksheet I need it to. Instead of using "CRM View" (like I told it to!) it is using the worksheet "Previous CRM View". I assume this is because both worksheets have similar names. So the question is, how do I get it to use the one that is called "CRM View"?
has comment: http://stackoverflow.com/comment/85818090
accepted answer: http://stackoverflow.com/a/49408855
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85820100
answer count: 1
has comment: http://stackoverflow.com/comment/85818777
tagged with: excel
type: Question
has title: How do I ensure 'read_excel' on Pandas reads the correct sheet?
has answer: http://stackoverflow.com/a/49408855

http://stackoverflow.com/q/49291521
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85653683
answer count: 1
has title: Change point size in Basemap
tagged with: python
accepted answer: http://stackoverflow.com/a/50097904
tagged with: matplotlib-basemap
has answer: http://stackoverflow.com/a/50097904
type: Question
has body: How can I reduce the point size of a place I have plotted on the map with its coordinates using Basemap in Python? The code for the plotting is: m = Basemap(width=4000000,height=4000000,projection='lcc', resolution='c',lat_1=45.,lat_2=55,lat_0=20,lon_0=80.) m.drawmapboundary(fill_color='aqua') m.drawcountries() m.drawcoastlines(linewidth=0.50) m.fillcontinents(color='green', alpha = 0.6, lake_color='aqua') for i in range(len(lngtd)): lon = lngtd[i] lat = lattd[i] xpt,ypt = m(lon,lat) lonpt, latpt = m(xpt,ypt,inverse=True) m.plot(xpt,ypt,'ro') plt.show()

http://stackoverflow.com/comment/85722920
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49361020
has text: No it doesn't, and no it isn't. All you're doing is printing the string representation of a method - hence `method-wrapper` - which happens to include (in its own `__repr__`, but that's irrelevant) the ID of the object it is called on. And the linked question explains exactly why the IDs work that way.

http://stackoverflow.com/comment/85709755
comment on: http://stackoverflow.com/q/49354615
has text: I've answered based on your desired output, as your logic is confusing.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85730174
score: 0
has text: The warning is generated from the optimization process where an invalid value was encountered while calculating Lhat. What you should take note is that the solution may not be the globally optimal solution, as noted in the docs.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49361288

http://stackoverflow.com/comment/85607050
type: Comment
has text: What if I want to realize the second phase ( please refer to the main question) Thank you in advance
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49287017

http://stackoverflow.com/comment/85874503
comment on: http://stackoverflow.com/a/49435082
type: Comment
score: 0
type: AnswerComment
has text: I am getting it now, are the pixels drawn, starting from the `upper left corner` to the last pixel drawn at the `lower right corner`. I mean are the pixels drawn in `row major` order?

http://stackoverflow.com/comment/85701810
type: QuestionComment
comment on: http://stackoverflow.com/q/49344890
type: Comment
has text: I don't think django throws some exceptions while calling a `get()` query method
score: 0

http://stackoverflow.com/q/49433936
has answer: http://stackoverflow.com/a/57116138
has title: How do I initialize weights in PyTorch?
tagged with: python
answer count: 11
has answer: http://stackoverflow.com/a/53966365
has answer: http://stackoverflow.com/a/66193447
linked to: http://stackoverflow.com/q/52465723
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49433937
tagged with: deep-learning
has answer: http://stackoverflow.com/a/52545824
tagged with: pytorch
has answer: http://stackoverflow.com/a/55546528
upvote count: 277
tagged with: neural-network
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/79302055
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49433937
has answer: http://stackoverflow.com/a/56037200
score: 277
has answer: http://stackoverflow.com/a/60593883
has body: How do I initialize weights and biases of a network (via e.g. He or Xavier initialization)?
has answer: http://stackoverflow.com/a/56773737
has answer: http://stackoverflow.com/a/59441468
has comment: http://stackoverflow.com/comment/118529394
possible better answer: http://stackoverflow.com/a/55546528

http://stackoverflow.com/q/49302626
has comment: http://stackoverflow.com/comment/85609480
has comment: http://stackoverflow.com/comment/85607301
tagged with: xpath
has comment: http://stackoverflow.com/comment/85609310
has comment: http://stackoverflow.com/comment/85609221
score: 0
has title: I've got IndexError: list index out of range after selecting an element with xpath
accepted answer: http://stackoverflow.com/a/49304083
has body: I made a python program using xpath and web driver for 2 different links. I would like to get the price that appears with 2 ids. This programs runs from 2 different pages that's why price has 2 ids. I used try and except but it doesn't work. I attached the code. Now I get IndexError: list index out of range. I will appreciate any help. Ask me any question if you want. from selenium import webdriver import csv # set the proxies to hide actual IP proxies = { 'http': 'http://218.50.2.102:8080', 'https': 'http://185.93.3.123:8080', } chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % proxies) driver = webdriver.Chrome(executable_path="C:\\Users\Andrei\Downloads\chromedriver_win32\chromedriver.exe", chrome_options=chrome_options) header = ['Product title', 'Product price'] with open('csv/products.csv', "w") as output: writer = csv.writer(output) writer.writerow(header) links = ['https://www.amazon.com/Windsor-Glider-Ottoman-White-Cushion/dp/B017XRDV5S/ref=sr_1_1?s=home-garden&amp;ie=UTF8&amp;qid=1520265105&amp;sr=1-1&amp;keywords=-gggg&amp;th=1', 'https://www.amazon.com/Instant-Pot-Multi-Use-Programmable-Packaging/dp/B00FLYWNYQ/ref=sr_1_1?s=home-garden&amp;ie=UTF8&amp;qid=1520264922&amp;sr=1-1&amp;keywords=-gggh'] for i in range(len(links)): driver.get(links[i]) product_title = driver.find_elements_by_xpath('//*[@id="productTitle"][1]') prod_title = [x.text for x in product_title] try: product_price = driver.find_elements_by_xpath('//*[@id="priceblock_ourprice"][1]') prod_price = [x.text for x in product_price] except: print('no price v1') try: product_price = driver.find_elements_by_xpath('//*[@id="_price"][1]') prod_price = [x.text for x in product_price] except: print('no price v2') csvfile = 'csv/products.csv' data = [prod_title[0], prod_price[0]] with open(csvfile, "a", newline="") as output: writer = csv.writer(output) writer.writerow(data)
has comment: http://stackoverflow.com/comment/85609071
has comment: http://stackoverflow.com/comment/85607461
answer count: 1
has comment: http://stackoverflow.com/comment/85607908
tagged with: webdriver
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49304083
has comment: http://stackoverflow.com/comment/85607248
tagged with: python
has comment: http://stackoverflow.com/comment/85609741
has comment: http://stackoverflow.com/comment/85609151
has comment: http://stackoverflow.com/comment/85609826

http://stackoverflow.com/a/49370607
has comment: http://stackoverflow.com/comment/114466944
has body: You can use webbrowser module from standard library import webbrowser url = "http://docs.python.org/library/webbrowser.html" webbrowser.open(url,new=1) so import webbrowser from tkinter import * window = Tk() window.title("DdP Program") window.geometry("300x100") def onClick(x): webbrowser.open(x,new=1) label = Label(text="some text") label.pack() labelOne = Label(text="A little bit more text") labelOne.pack() url = "http://docs.python.org/library/webbrowser.html" click = Button(text="Clica Aqui!", command=lambda: onClick(url)) click.pack() window.mainloop() We need to give argument but we can't use command=onClick(url) because it will invoke the function instantly (not when the button clicked) and assign its value to command so we can wrap the Onclick function with lambda function like this command=lambda: onClick(url). Lambda function will be invoked when button clicked and it will invoke onClick function with its argument
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/49369364
has comment: http://stackoverflow.com/comment/118550114
type: Answer
has comment: http://stackoverflow.com/comment/85742634
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49369364

http://stackoverflow.com/comment/85855855
comment on: http://stackoverflow.com/q/49427408
has text: Cannot reproduce, returns `True` for me (once I fix the errant `)`)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85868390
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49433220
score: 3
has text: Please edit the question and add `EXPLAIN (ANALYZE, BUFFERS)` output. Are `shared_buffers`, `work_mem` and `effective_cache_size` configured correctly?

http://stackoverflow.com/comment/85734168
comment on: http://stackoverflow.com/q/49305730
score: 0
type: Comment
type: QuestionComment
has text: @Drise , `while 1==1` == `while True` == `while 1` == `while 1>0` == ... This part of code I just got of another example I found out at github... the problem is not related to that, so, I left as it was (though I also prefer `True`). Good observation, btw, related to performance!

http://stackoverflow.com/q/49411783
has answer: http://stackoverflow.com/a/49415283
has title: Make a plot from a csv file with thousand entries in python
score: 0
tagged with: visualize
tagged with: http://stackoverflow.com/tag/csv
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49413174
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85826358
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85825784
has body: I have this code in python, which is working. from matplotlib import style from matplotlib import pylab as plt import numpy as np style.use('ggplot') filename='results.csv' value=[] date=[] import csv with open(filename, 'r') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: if len(row) ==2: value.append(row[0]) date.append(row[1]) value=np.array(value) import datetime for ii in range(len(date)): date[ii]=datetime.datetime.strptime(date[ii], '%a %b %d') plt.ylim(2, -2) plt.plot(date, value) plt.show() And the .csv file(almost 18000 entries) : [0.0] Thu Mar 15 [0.0] Thu Mar 15 [0.0] Thu Mar 15 [0.0] Thu Mar 15 [-0.05] Thu Mar 15 [0.0] Thu Mar 15 [0.0] Thu Mar 15 .... So, when I run the code I get this result: The thing is that I want to have the values in the y axis from [-2,2] in ascending order so to observe the route of the plotline. Is my rationale for visualizing such a csv wrong or do I have missed something important? I would appreciate any help.

http://stackoverflow.com/q/49299229
tagged with: django
has title: How i create diff. list_filters for superuser and staff user
downvote count: 1
accepted answer: http://stackoverflow.com/a/49299743
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49299743
tagged with: python
score: -1
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49300052
upvote count: 0
tagged with: django-admin
has body: In admin i want to display diff. list_filter for superuser and staff user. How it possible. When superuser is logged in: list_filter = ('is_active', 'membership_type', 'is_blocked') and for staff user with limited permission list_filters should be: list_filter = ('is_active',)
has answer: http://stackoverflow.com/a/49300052

http://stackoverflow.com/q/49292942
tagged with: python
linked to: http://stackoverflow.com/q/36355073
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49294394
accepted answer: http://stackoverflow.com/a/49294394
answer count: 1
has body: I've pandas as a dependency to read some excel files in my webapp. Everything was fine until I started a new deployment today. The app service has shown that pandas has numpy as dependency(yes I agree it has) and downloads the 1.14.2 version of numpy to install and then the installation fails with the below error. I tried providing a wheel file in the wheelhouse and specifying the numpy version in requirements is giving me the same error. PermissionError: [Errno 13] Permission denied: 'D:\home\python364x64\Lib\site-packages\numpy\.libs\libopenblas.BNVRK7633HSX7YVO2TADGR4A5KEKXJAW.gfortran-win_amd64.dll'
type: Question
tagged with: azure-web-app-service
score: 0
tagged with: pandas
tagged with: azure
has title: Numpy Installtion on Azure App Service WebApp - [Errno 13] Permission denied:

http://stackoverflow.com/q/49331908
favorite count: 0
type: Question
tagged with: filesystems
has answer: http://stackoverflow.com/a/49332057
accepted answer: http://stackoverflow.com/a/49332057
downvote count: 0
upvote count: 1
tagged with: python
tagged with: disk
type: AnsweredQuestion
tagged with: buffer
has comment: http://stackoverflow.com/comment/85666062
score: 1
has body: I'm working with an arcane data collection filesystem. It's got a block describing the files and their exact offsets on disk, so I know each files' start byte, end byte and length in bytes. The goal is to grab one file from the physical disk. They're big files so performance is paramount. Here's what "works," but very inefficiently: import shutil, io def start_copy(startpos, endpos, filename="C:\\out.bin"): with open(r"\\.\PhysicalDrive1", 'rb') as src_f: src_f.seek(startpos) flength = endpos - startpos print("Starting copy of "+filename+" ("+str(flength)+"B)") with open(filename, 'wb') as dst_f: shutil.copyfileobj( io.BytesIO(src_f.read(flength)), dst_f ) print("Finished copy of "+filename) This is slow: io.BytesIO(src_f.read(flength)) technically works, but it reads the entire file into memory before writing to the destination file. So it takes much longer than it should. Copying directly using dst_f won't work. (I assume) the end position can't be specified, so the copy doesn't stop. Here are some questions, each of which could be a solution to this: Is there a copy library (or external utility for Windows 7 that would work with subprocess) that takes start/end byte arguments? Is it possible to create a file-like object that copyfileobj can use, which references just a portion of another file-like object? Can an exception be raised when an io object seeks past a certain end point? Can copyfileobj be forced to naturally stop at a given byte offset of the drive (a sort of "fake EOF")?
tagged with: windows
answer count: 1
has title: How to copy a large portion of a raw filesystem to a file?

http://stackoverflow.com/a/49412673
has comment: http://stackoverflow.com/comment/85829835
has comment: http://stackoverflow.com/comment/85827184
answers question: http://stackoverflow.com/q/49412229
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85833963
has body: Don't do this on the Jinja2 template, but wherever you are generating these querysets: result = all(item in list(group.dependancies.all()) for item in list(SelectedGroups.all())) if result: msg = " All dependencies satsfied. " else: msg = " Dependencies missing. Then return msg to the template and render it with {{msg}}.
accepted answer of: http://stackoverflow.com/q/49412229

http://stackoverflow.com/a/49366955
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: In hindsight, I recommend against using lxml to create subclasses. As the comments mentioned, lxml.objectify.Element() is not a class. It is a factory method that creates and returns an object, meaning it cannot be inherited. While it's possible to inherit from ElementBase or ObjectifiedElement, the lxml documentation strongly warns that you must not override __init__ or __new__, which my original answer did. BIG FAT WARNING: Subclasses must not override __init__ or __new__ as it is absolutely undefined when these objects will be created or destroyed. All persistent state of Elements must be stored in the underlying XML. If you really need to initialize the object after creation, you can implement an _init(self) method that will be called directly after object creation. - Documentation for lxml.etree.ElementBase I suggest inheriting from a different class instead. As mentioned in the original question, you can inherit from lxml.etree.ElementTree.Element fairly easily. from xml.etree import ElementTree class Person(ElementTree.Element): def __init__(self, name, age): super().__init__("person", name=name, age=str(age)) person = Person("Paul", 23) Working with sub-classes of lxml may be more trouble than it's worth. However, if you really want to subclass lxml despite the warnings, you can see my original answer below. Old Answer (Unsafe) Try inheriting from lxml.objectify.ObjectifiedElement instead. from lxml import objectify class person(objectify.ObjectifiedElement): def __init__(self, name, age): super().__init__(name=name, age=str(age)) my_person = person("Paul", 23) print(etree.tostring(my_person, encoding="unicode")) # output: &lt;person age="23" name="Paul"/&gt; Make sure that your class name matches your XML tag, as ObjectifiedElement uses the class name for the root XML tag name. As Goyo and bruno desthuilliers pointed out, objectify.Element is not a class, which means you can't inherit from it. Going off their comments, I used type() to confirm this for myse…
answers question: http://stackoverflow.com/q/49366392
has comment: http://stackoverflow.com/comment/99079205

http://stackoverflow.com/q/49413026
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85881171
tagged with: listboxitem
tagged with: listbox
answer count: 0
has title: How to stylize items in a ListBox (urwid)?
has comment: http://stackoverflow.com/comment/86058509
tagged with: python
type: UnansweredQuestion
tagged with: command-line-interface
tagged with: urwid
downvote count: 0
has body: I'm trying to make a ListBox out of text items where the first line of every item is a bold, white title (with the first couple words colored green) and the next two lines are grey body text. Here's what I currently have: class SelectableText(urwid.Text): def selectable(self): return True def keypress(self, size, key): return key palette = [('reveal focus', 'black', 'dark cyan', 'standout')] items = ["This part should be green and is the bold title!\nThese are the two lines of grey body text... Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc facilisis at mi eu efficitur.", "This part should be green and is the bold title!\nThese are the two lines of grey body text... Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc facilisis at mi eu efficitur."] item_list = list(map(lambda item: urwid.AttrMap(SelectableText(item), None, "reveal focus"), items)) item_list_walker= urwid.SimpleListWalker(item_list) listbox = urwid.ListBox(item_list_walker) layout = urwid.Filler(listbox, valign="top", top=1, bottom=1) main_loop = urwid.MainLoop(layout, palette) main_loop.run() My question is how do I add display attributes to the items without changing the behavior of the "reveal focus" attribute? i.e. The item text should still turn black with a dark cyan background when it's selected but be stylized differently when it's not selected.
upvote count: 1

http://stackoverflow.com/comment/85648490
has text: I have tried using a chunk size, but made no difference. I am more convinced that the format the data I am receiving is in, is not what I expect it to be. I have dumped the headers and it is 'vnd.ms-excel', but I don't know enough about mime types to determine if that would even be related to my problem.
comment on: http://stackoverflow.com/q/49308917
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49342926
has comment: http://stackoverflow.com/comment/85686151
answer count: 1
has comment: http://stackoverflow.com/comment/85686165
has answer: http://stackoverflow.com/a/49343001
downvote count: 1
has comment: http://stackoverflow.com/comment/85686164
has comment: http://stackoverflow.com/comment/85686169
favorite count: 0
has comment: http://stackoverflow.com/comment/85689166
has body: My random string function: def random_string(chars=string.ascii_letters + string.digits): size = random.randrange(10, 15) return str(''.join(random.choice(chars) for _ in range(size))) I want it to generate random strings between 10 and 15 characters in length, hence why I have done size = random.randrange(10, 15). However it doesn't abide by this rule. Also, about 20% of the time, random_string() just returns an empty string: ''. Not sure why this is. Any one have any idea how to fix these problems?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85686145
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85686126
has comment: http://stackoverflow.com/comment/85686157
has title: randrange() not working on my random_string() function
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85686160
upvote count: 0
accepted answer: http://stackoverflow.com/a/49343001

http://stackoverflow.com/q/49307863
accepted answer: http://stackoverflow.com/a/49653023
has answer: http://stackoverflow.com/a/49653023
answer count: 1
type: Question
has body: I'm having success reading in and printing some Serial Port data in a python script. I'm having difficulty with what tools/functions to use to change the Serial port data into a table or continuously append to a .csv. So after spending many hours researching everything about Serial Ports and python on stack overflow and other sites I'm reaching out for a hand as I don't know what steps to take next and I can't find information that helps answer my question. Here is my script so far: ser = serial.Serial('com4', baudrate=38400, timeout=1, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) while True: rawdata = (ser.readline().decode('ascii')) print(rawdata) Ok....great we have the Sensor data printing in the console looking like this: $PDLMA,+11.91,+20.7,-0.1,-0.4*6C $PDLMH,134829.844,+2644.8,+81.46,+3094.7,+21.99*6F $PDLM1,134829.844,+1824.1,+127.69,+3276.7,+36.82*26 Now here's how the data from the sensor is structured: $PDLMH 134829.844 2644.8 81.46 3094.7 21.99 *6F Hhmmss.sss HCP05 HCPI PRP05 PRP05I Checksum $PDLM1 134829.844 1824.1 127.69 3727.7 36.82 *26 Hhmmss.sss HCP10 HCP10I PRP10 PRP10I Checksum $PDLMA 11.91 20.7 -0.1 -0.4 Voltage Temperature Pitch Roll Now my goal is to get the final output to look like this: Time HCP05 HCP05I PRP05 PRP05I HCP10 HCP10I PRP10 PRP10I Voltage Temp Pitch (now) data data data data data data data data Data Data Data So what should I do to take the serial data and transform it to what I need above as well as continuously reading in the data? I have tried dataframes, lists, etc but clearly I'm missing something here. In the .csv output file I would expect there to be about 120000 lines of data on average in our use case. The Newbie of the day.
tagged with: serial-port
tagged with: python
tagged with: parsing
tagged with: real-time
has title: Reading Serial Port data and saving to .csv Python
type: AnsweredQuestion
score: 0
tagged with: sensors

http://stackoverflow.com/comment/85735687
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49366928
score: 0
has text: @abarnert It's asking as to which style is preferred. I would suggest a good rule of thumb is to limit the scope of *everything* as much as possible. Later you can always expand it

http://stackoverflow.com/q/49309121
tagged with: numpy
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49309278
has body: I have variables that looks like these: data.head() Ones Population Profit 0 1 6.1101 17.5920 1 1 5.5277 9.1302 2 1 8.5186 13.6620 3 1 7.0032 11.8540 4 1 5.8598 6.8233 X = data.iloc[:, 0:cols] y = data.iloc[:, cols] X1 = np.matrix(X.values) y1 = np.matrix(y.values) X.shape &gt;&gt;(97, 2) y.shape &gt;&gt;(97,) X1.shape &gt;&gt;(97, 2) y1.shape &gt;&gt;(1, 97) data is in pandas frame. I expected the dimension of y1 would be 97 X 1, but instead it is 1 X 97. Somehow y1 was transposed in the middle, and I don't understand why this is happening. Since my original y panda array was 97 X 1, I thought y1 should be the same too, but apparently thats not how it works Any explanations?
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49309322
tagged with: pandas
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49309278
favorite count: 0
type: Question
has title: Python numpy and pandas matrix dimensions
possible better answer: http://stackoverflow.com/a/49309322

http://stackoverflow.com/comment/85647840
type: AnswerComment
has text: you mean it should be no problem with categoricals?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49323139

http://stackoverflow.com/a/49337919
has body: You can use itertools.groupby: import itertools table = [[3, 'AVENGERS','PACIFIC'],[1, 'A WALK,DRAGONBALL'],[2, 'A WALK,DRAGONBALL'],[5, 'A WALK,DRAGONBALL'],[6, 'JAMES BOND,MISSION'],[7,'JAMES BOND,MISSION']] new_table = [list(b) for a, b in itertools.groupby(sorted(table, key=lambda x:x[1:]), key=lambda x:x[1:])] last_results = [[b for b, _ in i] for i in new_table if len(i) &gt; 1] Output: [[1, 2, 5], [6, 7]]
type: Answer
answers question: http://stackoverflow.com/q/49337866
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85628883
has text: Can't we use `try:.. except ValueError:`?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49313662
type: QuestionComment

http://stackoverflow.com/q/49351191
has title: python extract part from a list of paths
tagged with: python
downvote count: 4
upvote count: 0
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49382464
has answer: http://stackoverflow.com/a/49351285
score: -4
has body: I've got a list of path from a folder, so I have: folder/subfolder1/file1 folder/subfolder1/file2 folder/subfolder2/file1 folder/subfolder2/file2 folder/subfolder3/file1 folder/subfolder3/file2 etc. From this list of path I want iteratively extract the element file1, file2, file1, file2 from my first list as a separate list. It's always the element [2] but I'm not understanding how to iterate
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/49366704
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49365432
score: 0
has body: Use nlargest instead of slicing, then reheapify the combined lists. from heapq import nlargest, heapify n = len(population) // 2 population = heapify(nlargest(population, n) + nlargest(new_population, n)) print(heappop(population)) You may want to benchmark, though, if sorting the two original lists, then merging the results, is faster. Python's sort routine is fast for nearly sorted lists, and this may impose a lot less overhead than the heapq functions. The last heapify step may not be necessary if you don't actually need a priority queue (since you are sorting them anyway). from itertools import islice from heapq import merge, heapify n = len(population) # == len(new_population), presumably population = heapify(islice(merge(sorted(population), sorted(new_population)), n))
type: Answer
accepted answer of: http://stackoverflow.com/q/49365432

http://stackoverflow.com/q/49374427
has comment: http://stackoverflow.com/comment/85758275
has comment: http://stackoverflow.com/comment/85792855
tagged with: gpu
has comment: http://stackoverflow.com/comment/85836885
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108584539
tagged with: python
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/108556401
has comment: http://stackoverflow.com/comment/85758110
has comment: http://stackoverflow.com/comment/85750164
tagged with: parallel-processing
has title: How to parallelize nested for loops on a GPU in Python?
downvote count: 0
answer count: 0
has body: Question I have three nested for loops and would like to run them in parallel on my (CUDA-capable) GPU using Python 3.6. The order of evaluation doesn't matter, but the outputs must be stored. How can I do this? Notice the range for each for loop is different. Code def f(i, j, k): if i &lt; j &lt; k: return np.log(1 + i + j + k) else: return (i, j, k) for i in range(1000): for j in range(2000): for k in range(3000): f(i, j, k) # Save the output??? Extra Details Is this even possible to be parallelized on a GPU? What packages can I use? How can I store the outputs without having to wait for other loops to compile? Should I just append [i, j, k, f(i, j, k)] to a list and put them into an organized array later? If the output of f is float16, the output volume easily gets out of hand. How can I overcome that? The function above is made up so it would have mixed form arguments, if statements, and call a NumPy function purely for educational purposes. If using for loops is not the right approach, please enlighten me. Should I perhaps create a list of all possible (i, j, k) and send a few thousand to GPU to evaluate it? Please consider memory limitations. Even storing 100 x 200 x 300 integers on memory is expensive. Outside the box How can I convert this problem to a linear algebra problem so I can take advantage of Numpy or Numba?
has comment: http://stackoverflow.com/comment/85750080
favorite count: 0
type: Question

http://stackoverflow.com/q/49408644
favorite count: 0
type: Question
tagged with: argparse
has comment: http://stackoverflow.com/comment/85819533
has comment: http://stackoverflow.com/comment/85826482
has answer: http://stackoverflow.com/a/57605883
has body: I am trying to use argparse to create my script with parameters but I am not being able to. The name of my script is pipeline and it has some options arguments like -b, -c, -i and -r. If you call the script ./pipeline -b should give an error asking for a git repository path but I am not being able to do this. from git import Repo import os import sys import subprocess import argparse class Ci: def build(self,args): cloned_repo = Repo.clone_from(args) print("clonning repository " + args) cloned_repo dir = git.split('/')(-1) if os.path.isdir(dir): print("repository cloned successfully") else: print("error to clone repository") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-b','-build',action='store_true', help='execute mvn clean install') parser.add_argument('-c','-compress',action='store_true',help='zip a directory recursively') parser.add_argument('-i','-integration',action='store_true',help='execute mvn verify') parser.add_argument('-r','-release',action='store_true',help='execute build,integration and compress respectively') args = parser.parse_args() if args.b: a = Ci() a.build() if len(sys.argv) &lt; 2: parser.print_help() sys.exit(1) I can't make this sub-parameter work and I can't find a way to pass this parameter to my build function. e.g: ./pipeline -b Output: error missins git path ./pipeline -b https://git/repo Output: clonning repo and the string "https://git/repo" has to be passed as the argument to my build function: How can I make it work?
has answer: http://stackoverflow.com/a/49409015
tagged with: python
has answer: http://stackoverflow.com/a/49415905
has comment: http://stackoverflow.com/comment/85818955
possible better answer: http://stackoverflow.com/a/49415905
has comment: http://stackoverflow.com/comment/85833023
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-3.x
answer count: 3
accepted answer: http://stackoverflow.com/a/49409015
downvote count: 0
has comment: http://stackoverflow.com/comment/85819680
has title: argparse function arguments

http://stackoverflow.com/a/49429363
has body: To strip the extra whitespace from the text, you can simply use .get_text(' ', strip=True) html = ''' EICHERMOT 28-Mar-18 28,079.75 0.45 0.00% 28,560.00 28,027.05 28298.25 49,050 1,962 13,880.29 197,375 750 0.38% >''' soup = BeautifulSoup(html, 'lxml') print(soup.find_all('td')[5].get_text(' ', strip=True)) # 28,560.00 28,027.05
accepted answer of: http://stackoverflow.com/q/49428951
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49428951
score: 1
type: Answer

http://stackoverflow.com/comment/85725870
type: QuestionComment
comment on: http://stackoverflow.com/q/49362719
has text: Show the sample input and output so that someone can help.
score: 0
type: Comment

http://stackoverflow.com/comment/85564562
type: QuestionComment
has text: Ignore the numbering in the file name...Simply load a list of all your files, and use random indexes into the list
comment on: http://stackoverflow.com/q/49280966
score: 1
type: Comment

http://stackoverflow.com/q/49434019
has answer: http://stackoverflow.com/a/49434077
linked to: http://stackoverflow.com/q/47152691
downvote count: 0
upvote count: 4
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: dataframe
tagged with: python
score: 4
has body: I have a pandas data frame counted and grouped by specific columns. import pandas as pd df = pd.DataFrame({'x':list('aaabbbbbccccc'),'y':list('2225555577777'), 'z':list('1312223224432')}) # df.groupby(['x','y','z'])['z'].count() # or df.groupby(['x','y','z'])['z'].agg(['count']) # or df.groupby(['x','y','z'])['z'].count().reset_index(name='counts') Results is; x y z counts 0 a 2 1 2 1 a 2 3 1 2 b 5 2 4 3 b 5 3 1 4 c 7 2 2 5 c 7 3 1 6 c 7 4 2 How can I convert the result to following form? x y 1 2 3 4 0 a 2 2 0 1 0 1 b 5 0 4 1 0 2 c 7 0 2 1 2
possible better answer: http://stackoverflow.com/a/49434185
has answer: http://stackoverflow.com/a/49434390
has answer: http://stackoverflow.com/a/49434185
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49434077
answer count: 3
has title: How to change table form of python 3 pandas.DataFrame?
tagged with: pandas
has comment: http://stackoverflow.com/comment/85871656

http://stackoverflow.com/comment/85836458
type: Comment
type: QuestionComment
has text: The `datalab.*` namespace is deprecated, you should now switch to `google.datalab.*`. I believe there were some UTF-8 fixes there, can you give that a try?
score: 0
comment on: http://stackoverflow.com/q/49411182

http://stackoverflow.com/q/49435728
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85879339
has comment: http://stackoverflow.com/comment/85875206
has comment: http://stackoverflow.com/comment/85879996
tagged with: duplicates
has comment: http://stackoverflow.com/comment/85875317
has answer: http://stackoverflow.com/a/49436610
has comment: http://stackoverflow.com/comment/85875379
downvote count: 1
score: -1
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85877338
tagged with: python
linked to: http://stackoverflow.com/q/17076345
has title: Remove duplicates from json file matching against multiple keys
has body: Original Post = Remove duplicates from json data This is only my second post. I didnt have enough points to comment my question on the original post...So here I am. Andy Hayden makes a great point - "Also, those aren't really duplicates... – Andy Hayden" My question is just that situation... How can you remove duplicates from a json file but by matching against more than 1 key in the json file? Here is the original example: (it was pointed out that it is not a valid json) { {obj_id: 123, location: { x: 123, y: 323, }, {obj_id: 13, location: { x: 23, y: 333, }, {obj_id: 123, location: { x: 122, y: 133, }, } My case is very similar to this example except In my case, it would keep all these because the x and y values of obj_id are unique, however if x and y were the same than one would be removed from json file. All the examples I have found only kick out ones based on only one key match.. I don't know if it matters, but the keys that I need to match against are "Company Name" , "First Name", and "Last Name" (it is a 100k plus line json of companies and contacts - there are times when the same person is a contact of multiple companies which is why I need to match against multiple keys) Thanks.
answer count: 1
has comment: http://stackoverflow.com/comment/85875095
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49436610
has comment: http://stackoverflow.com/comment/129705159

http://stackoverflow.com/a/49296678
type: Answer
has comment: http://stackoverflow.com/comment/85596682
score: 3
upvote count: 3
downvote count: 0
has body: To debug your environment add this to /etc/crontab * * * * * root env &gt; ~/cronenv Wait for file ~/cronenv to be created (after a minute) and start a new shell using does environments: env - `cat ~/cronenv` /bin/sh Then call your script /usr/local/bin/python3.6 /root/myscript.py This will help to test/debug your code within the same environment cron is using.
answers question: http://stackoverflow.com/q/49284717
has comment: http://stackoverflow.com/comment/85696094

http://stackoverflow.com/q/49423082
tagged with: urlopen
has comment: http://stackoverflow.com/comment/85847162
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85847394
has comment: http://stackoverflow.com/comment/85847142
has body: Because raptr is closing sooner or later I want to save all my play data. I can access first tab but that's it. How can I get data from 2nd, 3rd etc (It's at the bottom of the screen)? My code: import urllib2 page = urllib2.urlopen('http://raptr.com/john/games') data = [] for line in page: if "game\/" in line: data.append(line) sorter = [] for i in data: sorter.append(i.split("game\/")) games = [] for lst in sorter: for part in lst: if "game-title" in part: games.append(part) for game in games: print(game) P.S. I know about file but this file does't have all information I've uploaded to to the web page
tagged with: python
has comment: http://stackoverflow.com/comment/85847196
has comment: http://stackoverflow.com/comment/85847098
has title: urllib2.urlopen I only get part of the web page
tagged with: python-2.7
tagged with: urllib2
answer count: 0
has comment: http://stackoverflow.com/comment/85847052
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49402881
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85806905
has body: I can do import random a = [1, 2, 3] random.shuffle(a) or from random import shuffle a = [1, 2, 3] shuffle(a) But I can't import random.shuffle a = [1, 2, 3] random.shuffle(a) which will make the interpreter complain 'random' is not a package. Why is this?
tagged with: python-import
has comment: http://stackoverflow.com/comment/85807458
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/85806935
accepted answer: http://stackoverflow.com/a/49403008
tagged with: python
possible better answer: http://stackoverflow.com/a/49403109
has title: Why can't I "import random.shuffle"?
has answer: http://stackoverflow.com/a/49403109
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85806887
answer count: 3
tagged with: python-packaging
has answer: http://stackoverflow.com/a/49403008
has comment: http://stackoverflow.com/comment/85806947
favorite count: 0
has answer: http://stackoverflow.com/a/68423360
type: Question

http://stackoverflow.com/a/49338782
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49315620
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49315620
has body: The library you use generates an exception (whois.parser.PywhoisError) when the domain name is not found. Hence, you need to capture this exception and deal with it. Replace the end of your loop by something like: try: data = whois.whois(n) w.append(data['domain_name']) except whois.parser.PywhoisError: w.append('none') You may need an import whois.parser at top of your file, so that the exception is known (symbol resolved) in your program.

http://stackoverflow.com/comment/85622376
type: QuestionComment
comment on: http://stackoverflow.com/q/49310057
has text: @rogerdpack if I run `python .../python/initUser.py ... ` it hangs for 2 minutes if you mean that. And if this script is run as a normal script (non-cgi executed) it also hangs
score: 0
type: Comment

http://stackoverflow.com/q/49370016
answer count: 2
tagged with: pip
tagged with: python
has title: Flask-ask Cannot Deploy zappa
accepted answer: http://stackoverflow.com/a/49373701
tagged with: aws-lambda
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49395069
score: 2
possible better answer: http://stackoverflow.com/a/49395069
tagged with: zappa
downvote count: 0
has answer: http://stackoverflow.com/a/49373701
has body: I was trying to deploy flask-ask alexa skill using Zappa. I followed the instructions on Alexa Tutorial: Deploy Flask-Ask Skills to AWS Lambda with Zappa` But I'm getting a KeyError: pip._vendor.urllib3.contrib. when I run: zappa deploy dev
favorite count: 0
type: Question

dst
tags question: http://stackoverflow.com/q/49325624
tag name: dst
type: Tag

http://stackoverflow.com/comment/85694267
score: 0
type: QuestionComment
has text: You need to add `python3` tag to make your question clear.
comment on: http://stackoverflow.com/q/49347226
type: Comment

http://stackoverflow.com/a/49282174
type: Answer
upvote count: 2
has body: Using jezrael's data df = pd.DataFrame({'user_id':list('aaacbbt')}) You can use array slicing df.assign( user_type= np.array(['Single', 'Frequent'])[ df['user_id'].duplicated(keep=False).astype(int) ] ) user_id user_type 0 a Frequent 1 a Frequent 2 a Frequent 3 c Single 4 b Frequent 5 b Frequent 6 t Single
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/49282033

http://stackoverflow.com/a/49390970
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85783823
upvote count: 5
score: 5
has body: One way to approach what you are after is to inherit from click.Option, and customize the parser. Custom Class: import click class OnceSameNameOption(click.Option): def add_to_parser(self, parser, ctx): def parser_process(value, state): # method to hook to the parser.process if self.name in state.opts: param_same_name = [ opt.opts[0] for opt in ctx.command.params if isinstance(opt, OnceSameNameOption) and opt.name == self.name ] raise click.UsageError( "Illegal usage: `{}` are mutually exclusive arguments.".format( ', '.join(param_same_name)) ) # call the actual process self._previous_parser_process(value, state) retval = super(OnceSameNameOption, self).add_to_parser(parser, ctx) for name in self.opts: our_parser = parser._long_opt.get(name) or parser._short_opt.get(name) if our_parser: self._previous_parser_process = our_parser.process our_parser.process = parser_process break return retval Using Custom Class: To use the custom class, pass the cls parameter to @click.option() decorator like: @click.option("--an_option", 'option-name', cls=OnceSameNameOption) The string option-name is used to check for other invocations of the same option. How does this work? This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods. In this case we over ride click.Option.add_to_parser() and the monkey patch the parser so that we can validate that the same name parameter has not been seen before. Test Code: @click.command() @click.option('--upper', 'transformation', flag_value='upper', cls=OnceSameNameOption, default=True) @click.option('--lower', 'transformation', flag_value='lower', cls=OnceSameNameOption) def info(transformation): """Show the transformed platform""" click.echo(getattr(sys.platform, transformation)()) if __name__ =…
type: Answer
accepted answer of: http://stackoverflow.com/q/49387833
answers question: http://stackoverflow.com/q/49387833

http://stackoverflow.com/a/49393396
score: 1
has comment: http://stackoverflow.com/comment/85789279
type: Answer
accepted answer of: http://stackoverflow.com/q/49393269
answers question: http://stackoverflow.com/q/49393269
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85829529
has body: [s for s in statuses if s in snip[0][3]] with regex: import re statuses = ['421-A','421-G','ARTICLE 11','ARTICLES 14 &amp; 15', 'COOP/CONDO PLAN FILE','EVICT COOP/CONDO', 'GARDEN COMPLEX' 'J-51','NON-EVICT COOP/CONDO','ROOMING HOUSE','SEC 608'] snip = ' '.join(statuses) statuses_re = map(lambda s : (s,re.compile('(^| )%s($| )' % s)),statuses) print([s[0] for s in statuses_re if s[1].search(snip)]) but if you have statuses like 'GARDEN COMPLEX', 'GARDEN COMPLEX 1', 'GARDEN COMPLEX 2' it isn't work
has comment: http://stackoverflow.com/comment/85824826
upvote count: 1
has comment: http://stackoverflow.com/comment/85829263

http://stackoverflow.com/comment/85889029
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49423533
type: AnswerComment
has text: this is just an example, you should take it an adjust to fit your own case, if you can provide some of the data I may be able to help you...

http://stackoverflow.com/comment/85711456
score: 0
comment on: http://stackoverflow.com/q/49351442
has text: Any change that you are mixing up Python 2 and Python 3?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85693430
comment on: http://stackoverflow.com/a/49346853
has text: @MrT sorry but didnt got u
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49345269
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The error is because of your model definition instead of ImageDataGenerator (which I don't see used in the code you have posted). I am assuming that len(classes) = 2 because of the error message that you are getting. You are getting the error because the last layer of your model expects trainingLabels to have a vector of size 2 for each datapoint but your trainingLabels is a 1-D array. For fixing this, you can either change your last layer to have just 1 unit because it's binary classification: model.add(Dense(1)) or you can change your training and validation labels to vectors using one hot encoding: from keras.utils import to_categorical training_labels_one_hot = to_categorical(trainingLabels) validation_labels_one_hot = to_categorical(validationLabels)
answers question: http://stackoverflow.com/q/49344429
accepted answer of: http://stackoverflow.com/q/49344429
type: Answer

http://stackoverflow.com/comment/85673077
has text: [Here](https://en.wikipedia.org/wiki/Quotation_mark#Unicode_code_point_table) are all the codepoint variants of quotation marks that you'll find. Make sure you account for all the ones that you're processing.
comment on: http://stackoverflow.com/q/49335307
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49438246
tagged with: python
has answer: http://stackoverflow.com/a/49438675
tagged with: queue
favorite count: 0
type: Question
tagged with: multithreading
answer count: 1
downvote count: 0
upvote count: 1
has title: Do Python's queue.Queue get/put methods hold the lock for that queue while blocking?
accepted answer: http://stackoverflow.com/a/49438675
type: AnsweredQuestion
score: 1
has body: I have a conventional multithreaded producer/consumer pattern with a queue.Queue in between. This implementation of queues is thread safe. The consumer can consume the data in two ways: Blocking while self.running: data = self.receiver_q.get(block=True) # do something with data Non-blocking while self.running: try: data = self.receiver_q.get(block=False) except queue.Empty: continue # do something with data In the blocking method, the consumer waits until there is data in the queue. During this time, is the consumer holding the lock on the queue? I can't imagine a way for it to hold the lock while allowing the queue to have new data placed on it. Also, is there a performance difference between the two patterns?

http://stackoverflow.com/q/49304191
tagged with: mpi
has comment: http://stackoverflow.com/comment/85646240
has comment: http://stackoverflow.com/comment/85624817
answer count: 1
has comment: http://stackoverflow.com/comment/85621173
has answer: http://stackoverflow.com/a/49326035
downvote count: 1
has comment: http://stackoverflow.com/comment/85615184
favorite count: 0
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/23611396
has comment: http://stackoverflow.com/comment/85611920
has comment: http://stackoverflow.com/comment/85645756
has comment: http://stackoverflow.com/comment/85646761
has comment: http://stackoverflow.com/comment/85615011
has body: I am attempting to create a python script that can drive multiple MPI simulations (F90 executables, though it doesn't matter). Each of these MPI simulations use 2 processors. Lets say I want to have three of these MPI simulations running simultaneously. If I run these 3 simulation from the command line in 3 separate terminals, without python, they each get their own 2 processors, and run as though they are the only things that exist in the world. My current implementation does not appear to be doing this. It is clear from tracking the MPI simulations that there is competition amongst the MPI simulations. Here is my current procedure import subprocess import multiprocessing as mp def execute(inputs, output): do_stuff_with_inputs() subprocess.call('mpiexec -np 2 my_executable.x', shell=True) results = post_process_stuff() output.put(results) output = mp.Queue() processes = [] for i in xrange(3): process.append(mp.Process(target=execute, args=args))) for p in process: p.start() for p in process: p.join() results = [output.get() for p in process] What I would like to do is be more explicit with the procedure, somehow 'creating' processor space in python so that the executable call has its own dedicated number of processors.
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41699585
tagged with: python
score: -1
has title: Being more explicit with processing in parallel with python in parallel
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/85645912
has comment: http://stackoverflow.com/comment/85612031

http://stackoverflow.com/comment/85773857
type: QuestionComment
comment on: http://stackoverflow.com/q/49374323
score: 0
has text: We cannot reproduce the problem as the problem is not with the bs4 scraping, but with the getting the page source of the web page (content is loaded dynamically).
type: Comment

http://stackoverflow.com/comment/85680536
score: 1
has text: Sorry for the late reply, I've had to focus on some school projects. That looks awesome! Thank you so much for the help- I'll look into it more in-depth when I get some free time.
type: Comment
comment on: http://stackoverflow.com/a/49287201
type: AnswerComment

http://stackoverflow.com/comment/85679587
type: AnswerComment
comment on: http://stackoverflow.com/a/49338594
score: 0
has text: I frequently use hyphens in URLs. Maybe another rule is matching your URLs. What does "it fails" mean? Do you get a 404, or does a different view load? Please edit your question and add your whole `urls.py` file.
type: Comment

http://stackoverflow.com/a/49433071
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49374730
has body: There seems to be a fundamental misunderstanding about flask and the relationship between your code and your templates. First of all, you can't drop code into your HTML template without using Jinja (Flask standard) or some other tool. Using Jinja you can add variables into your HTML template with {{variable}} and add limited logic into your template with {% for item in list %} HTML to loop {% endfor%}. More about Jinja conventions here and here. Presuming you want the users to use your select and inputs to set layer type and number of filters and that the other details are set in similar fasshion, you will want your template to look like this: Then in your corresponding flask route, you can build this dictionary like this: networks = {} networks['network'] = [] networks['network'][0] = {'layer_type': request.form['net1_layer_type_1'], 'num_filters': request.form['net1_num_filters_1'], "kernel_size": 2, "padding": "valid", "stride": 2} Repeat for the other items. Using this as a basis, I'm sure you can see how you can make this more dynamic, allowing additional networks with additional members, and using loops to create each network member. Let's say you want to make 4 networks each with 5 memebers, on the route that renders your form, you create the lists "network_count" and "member_count" which look like [1,2,3,4] and [1,2,3,4,5], respectively. Then on your template use a loop to build your form that looks like this: {% for net in network_count %} {% for mem in member_count %} {% endfor %} {% endfor %} Use the same python as before to process, but loop that as well.
answers question: http://stackoverflow.com/q/49374730
has comment: http://stackoverflow.com/comment/85868941
type: Answer
has comment: http://stackoverflow.com/comment/85868637

http://stackoverflow.com/q/49321361
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/27037241
has comment: http://stackoverflow.com/comment/85644281
upvote count: 1
accepted answer: http://stackoverflow.com/a/49321625
favorite count: 0
has answer: http://stackoverflow.com/a/49321625
type: Question
linked to: http://stackoverflow.com/q/49315084
has title: How to align xlabels and ylabels in seaborn?
duplicate of: http://stackoverflow.com/q/27037241
tagged with: seaborn
has body: I am plotting heatmap of features but the feature names on x and y axes conincide with each other. So how can I align x axis feature names vertically and y axis feature names horizontally so that they do not overlap. Code: %matplotlib notebook corr = data.loc[:,'PERID':'PRXRETRY'].corr() sns.set(font_scale=0.8) sns.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values,cmap="YlGnBu",annot=True) Screenshot:
tagged with: python
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/q/49422838
has title: What is the preferred way to export python symbols from a pacakge?
type: Question
tagged with: package
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49427828
has answer: http://stackoverflow.com/a/49423112
tagged with: python
score: 0
has body: Let's say I have the following structure: package module1 class1 class2 And the user of the package wants to use class1 and class2. The way I understand I have too options, in my __init__.py: from module1 import class1,class2 Which will let the user do something like x = pacakge.class1() Or: import module1 Which will let the user do something like x = pacakge.module1.class1() Is there is a preferred way?
answer count: 2
has comment: http://stackoverflow.com/comment/85846550

http://stackoverflow.com/comment/85693379
comment on: http://stackoverflow.com/a/49346070
score: 0
type: Comment
has text: Output should be 1,3 , user 4 is not included since it's 3 logins are in 8 day period, not in 7 days
type: AnswerComment

http://stackoverflow.com/a/49349115
answers question: http://stackoverflow.com/q/49348613
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49348613
type: AcceptedAnswer
downvote count: 0
has body: Getting newly created issues will involve you creating a new JQL query - here's a get started with JQL page from the Atlassian blog. From the examples at the bottom it looks like you can query by relative date like this: assignee is EMPTY and created &lt; -1d I hope that helps.
type: Answer

http://stackoverflow.com/q/49371947
answer count: 3
has answer: http://stackoverflow.com/a/49372138
upvote count: 1
has answer: http://stackoverflow.com/a/49372544
favorite count: 0
tagged with: beautifulsoup
has title: Regular expression in Beautiful Soup output
has body: I am trying to get the lines from html page, proccessed by BS, containing word 'billion'. But I am getting empty list..... Btw, these lines are between &lt;li&gt; tags, I have tried to use soup.findAll("&lt;li&gt;", {"class": "tabcontent"}) but it gives me an empty list also. import requests from bs4 import BeautifulSoup import re url = 'http://www.worldstopexports.com/united-states-top-10-exports/' header = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36", "X-Requested-With": "XMLHttpRequest" } page = requests.get (url, headers=header) soup = BeautifulSoup (page.text, 'lxml') table = soup.find_all (class_='tabcontent')[0].text print(re.findall(r'^.*? billion', table)) print(table) Machinery including computers: US$201.7 billion (13% of total exports) Electrical machinery, equipment: $174.2 billion (11.3%) Mineral fuels including oil: $138 billion (8.9%) Aircraft, spacecraft: $131.2 billion (8.5%) Vehicles: $130.1 billion (8.4%) Optical, technical, medical apparatus: $83.6 billion (5.4%) Plastics, plastic articles: $61.5 billion (4%) Gems, precious metals: $60.4 billion (3.9%) Pharmaceuticals: $45.1 billion (2.9%) Organic chemicals: $36.2 billion (2.3%)
type: Question
tagged with: python
tagged with: regex
score: 1
possible better answer: http://stackoverflow.com/a/49372200
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49372200
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49372138
downvote count: 0

storage
tag name: storage
type: Tag
tags question: http://stackoverflow.com/q/49285347

http://stackoverflow.com/q/49389107
has answer: http://stackoverflow.com/a/49389809
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85779775
score: 0
has comment: http://stackoverflow.com/comment/85780073
has answer: http://stackoverflow.com/a/49389444
has comment: http://stackoverflow.com/comment/85780188
type: Question
has body: I am struggling with running python script in shell. I use PyCharm where is everything ok, but I want to run script without running PyCharm. So my project folder is like: data/ file.txt main/ __init__.py script.py tools/ __init__.py my_strings.py I want to run main/script.py, which start with from tools import my_strings and working directory should be data/. My PyCharm config is: Script path: &lt;PROJECT&gt;/main/script.py Working directory: &lt;PROJECT&gt;/data Add content roots to PYTHONPATH: YES Add source roots to PYTHONPATH: YES So I want to run main/script.py in shell on Ubuntu. I tried: PYTHONPATH=&lt;PROJECT&gt; cd &lt;PROJECT&gt;/data python3 ../main/script.py But I just got: ImportError: No module named 'tools'
has title: Run python script in package
has comment: http://stackoverflow.com/comment/85779887
tagged with: python
has comment: http://stackoverflow.com/comment/85780229
has comment: http://stackoverflow.com/comment/85780334
answer count: 2
linked to: http://stackoverflow.com/q/19917492
has comment: http://stackoverflow.com/comment/85780382

http://stackoverflow.com/q/49310057
has comment: http://stackoverflow.com/comment/85622595
has comment: http://stackoverflow.com/comment/85622292
downvote count: 0
answer count: 1
score: 6
has comment: http://stackoverflow.com/comment/85622395
linked to: http://stackoverflow.com/q/3516007
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85622376
has body: I have an python cgi script that handles login, this is because my website is three (school) websites combined and before my website can be used the data needs to be extracted from those websites. This extraction takes 2 minutes so I want to make a fancy (semi-fake) loading screen. My register code ends with: import subprocess token = "".join(random.choice( string.ascii_lowercase + string.digits + string.ascii_uppercase) for _ in range(5)) #generate 5 random characters #run initScript subprocess.Popen("python {}/python/initUser.py {} {}".format( os.getcwd(), uid,token), shell=True, stdin=None, stdout=None, stderr=None, close_fds=True) print "Content-type: text/html" print "Location: registerLoading.php?token={}".format(token) print sys.exit(0) With the subprocess line stolen from: Run Process and Don&#39;t Wait But the subprocess line is still blocking and I can't figure out why. I'm developing on ubuntu 16.04, and it's going to run on an raspbarry pi 3 (that explains the loading time)
has title: Why is subprocess.Popen blocking?
has comment: http://stackoverflow.com/comment/85622149
accepted answer: http://stackoverflow.com/a/49310221
has answer: http://stackoverflow.com/a/49310221
tagged with: python
has comment: http://stackoverflow.com/comment/85622402
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85623308
tagged with: subprocess

http://stackoverflow.com/comment/85907455
has text: Your method does work. I was wondering why you include date in `df_plot` instead of just using `df_plot.reset_index(inplace = True)` at the end. I don't know if it would simplify much, but it seems like reducing something in a `for` loop would be a good idea. I was also wondering why you used the t in `tdfX`. Is that a common formatting for a boolean map?
comment on: http://stackoverflow.com/a/49416031
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49410042
has answer: http://stackoverflow.com/a/49418075
score: 0
answer count: 2
tagged with: twisted
type: Question
has title: Controlling the feed of incoming bytes using twisted
accepted answer: http://stackoverflow.com/a/49428055
has comment: http://stackoverflow.com/comment/85831131
has answer: http://stackoverflow.com/a/49428055
has body: I need to address the following issue As a client I connect to a server, the server sends blocks of data in the following form: [4 bytes][msg - block of bytes the size of int(previous 4 bytes)] When using twisted I need to make dataReceived(self, data) to be called with the msg part, I don't mind receiving the the 4 bytes prefix, but I have I need to make sure I get the entire message block in one piece, not fragmented, one at a time. Please advise.
tagged with: python
possible better answer: http://stackoverflow.com/a/49418075
has comment: http://stackoverflow.com/comment/85837157
type: AnsweredQuestion

http://stackoverflow.com/a/49323039
has comment: http://stackoverflow.com/comment/85649203
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49322712
has comment: http://stackoverflow.com/comment/85649669
has comment: http://stackoverflow.com/comment/85648843
has body: Attributes not defined by C are searched for using C's method resolution order: &gt;&gt;&gt; C.__mro__ (&lt;class '__main__.C'&gt;, &lt;class '__main__.A'&gt;, &lt;class '__main__.B'&gt;, &lt;class 'object'&gt;) Since C.MyFunc isn't defined, classC.MyFunc resolves to A.MyFunc. B.MyFunc is never called, unless A.MyFunc were to call it explicitly for some reason.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85649050
accepted answer of: http://stackoverflow.com/q/49322712
score: 5
has comment: http://stackoverflow.com/comment/85649578

http://stackoverflow.com/q/49335880
tagged with: python
accepted answer: http://stackoverflow.com/a/49336162
type: AnsweredQuestion
score: 3
has title: Passing command line arguments to a python script, called from a Makefile
has answer: http://stackoverflow.com/a/49336162
upvote count: 3
downvote count: 0
answer count: 1
has body: I have just started using GNU's make command to automate things. I ran into a problem and need some help. I have a python script (abc.py) which accepts a command line argument with short notation as ("-t") and long notation("--type") and can be run as : python abc.py --type "blah" However, I wish to run this script(abc.py) from a Makefile. So, now my Makefile looks as: command: python abc.py I can now execute the code as make command, but how do I accept and pass the user input to abc.py? Hope, the question is well formed.
favorite count: 0
type: Question
tagged with: gnu-make
tagged with: command-line-arguments
tagged with: makefile

http://stackoverflow.com/comment/85571948
type: QuestionComment
has text: @abarnert Yup, I deleted that line and re-ran my program and it worked. I guess I just assumed that the full file was downloaded and that there was an error in the middle, (because it should be WAY more than 26,000 lines) instead of an incomplete file. Thank you for your help and your side note about JSON documentation. I just am doing it this way because the file came with one per line.
type: Comment
comment on: http://stackoverflow.com/q/49284203
score: 0

numpy-ndarray
tags question: http://stackoverflow.com/q/49281459
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/49345411
tags question: http://stackoverflow.com/q/49359952
type: Tag
tags question: http://stackoverflow.com/q/49324377

http://stackoverflow.com/a/49293683
answers question: http://stackoverflow.com/q/49293401
type: Answer
has body: Before adding i to list, convert it to float by float(i). for i in lines: print(i) if(i != " "): if(a % 4 == 0 and a != 1): second.append(float(i)) tuple(tmp) first.append(tmp) tmp = [] else: tmp.append(float(i)) a+=1
score: 0
accepted answer of: http://stackoverflow.com/q/49293401
type: AcceptedAnswer

http://stackoverflow.com/q/49371575
accepted answer: http://stackoverflow.com/a/49371700
favorite count: 0
type: Question
score: 1
has title: Print Subprocess.Popen
tagged with: stdout
tagged with: python
has comment: http://stackoverflow.com/comment/85744305
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49371700
has comment: http://stackoverflow.com/comment/85744437
has comment: http://stackoverflow.com/comment/85744521
tagged with: subprocess
answer count: 1
downvote count: 0
upvote count: 1
has body: I have problem with function Popen. I try retrieving the output from command which i used. print(subprocess.Popen("dig -x 156.17.86.3 +short", shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip()) This part working, but when I call the variable inside Popen (for adress in IP) print(subprocess.Popen("dig -x ",Adres," +short", shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip()) happens something like that: raise TypeError("bufsize must be an integer") I thought it would be problem with command so I used this solution: command=['dig','-x',str(Adres),'+short'] print(subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip()) But now the return values is different than from console : dig -x 156.17.4.20 +short vpn.ii.uni.wroc.pl. How I can print this the above name in script ? Thank a lot of

http://stackoverflow.com/q/49285076
tagged with: django
has answer: http://stackoverflow.com/a/49285127
has title: Django relations between Models
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85573560
has body: What I currently have in my models is this: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') Now my question is: Users should be able to have multiple Projects - so I obviously can't use a OneToOne-Field in the Profile-Model. Later I want to use it for example to just show a user news which are only related to the projects he participates in. What would be the best strategy to make this possible? Any input is highly appreciated.
tagged with: python
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/49285127
answer count: 1
has comment: http://stackoverflow.com/comment/85573404

http://stackoverflow.com/comment/85789669
has text: I tried [i,j] but it didn't work, unfortunately. Thank you for checking it in IDLE though, I have to admit I miss using it.
score: 0
comment on: http://stackoverflow.com/a/49393867
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49398457
has comment: http://stackoverflow.com/comment/85846445
has body: I'm trying to build a model using Keras (Tensorflow backend): def build_model(args): # Define the input nodes text1 = build_input_node('text1', args.batch_size, args.time_steps) text2 = build_input_node('text2', args.batch_size, args.time_steps) # Create the shared LSTM node shared_lstm = LSTM(INPUT_SIZE, stateful=args.stateful) # Run inputs through shared layer encoded1 = shared_lstm(text1) encoded2 = shared_lstm(text2) # Concatenate outputs to form a tensor of shape (2*batch_size, INPUT_SIZE) concatenated = concatenate([encoded1, encoded2], axis=0) # Input shape: (2*batch_size, INPUT_SIZE) # Output shape: (2*batch_size, batch_size) dense1 = Dense(args.batch_size, input_shape=(2 * args.batch_size, INPUT_SIZE), activation='sigmoid')(concatenated) # Input shape: (2*batch_size, batch_size) # Output shape: (2*batch_size, 1) output_shape = (2 * args.batch_size, 1) output = Dense(1, input_shape=(2 * args.batch_size, args.batch_size), activation='sigmoid')(dense1) model = Model(inputs=[text1, text2], outputs=output) optimizer = build_optimizer(name=args.optimizer, lr=args.learning_rate) model.compile(loss=args.loss, optimizer=optimizer, metrics=['accuracy']) return model, output_shape The data which is supposed to be fed into the model is reshaped to fit the output_shape variable: def build_datasets(input, time_steps, output_shape): T1 = [] T2 = [] Y = [] for sentence1, sentence2, score in input: T1.append([t.vector for t in nlp(sentence1)]) T2.append([t.vector for t in nlp(sentence2)]) Y.append(np.full(output_shape, score)) T1 = pad_and_reshape(T1, time_steps) T2 = pad_and_reshape(T2, time_steps) X = [T1, T2] Y = np.asarray(Y) # fit the scores between 0 and 1 Y = expit(Y) return X, Y But when I call model.fit(X, Y, epochs=100, batch_size=8) it throws the following error: ValueError: Error when checking target: expected dense_34 to have 2 dimensions, but got array with shape (1468, 16, 1) where 1468 is the number of samples, 16 is 2*batch_size. What am I doing wrong? How …
type: Question
has title: Dimensionality error when fitting model in Keras
score: 0
accepted answer: http://stackoverflow.com/a/49503848
tagged with: keras
has comment: http://stackoverflow.com/comment/85808227
answer count: 1
has answer: http://stackoverflow.com/a/49503848
has comment: http://stackoverflow.com/comment/85808005
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85808331
tagged with: tensorflow

http://stackoverflow.com/a/49334280
accepted answer of: http://stackoverflow.com/q/49282595
downvote count: 0
answers question: http://stackoverflow.com/q/49282595
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: It's not very clear from your answer where the program is failing. It complains about not being able to open a file though. This line looks suspicious to me: path = 'E:\Dummy\sam\\'+ str(folder) I advise you to never concatenate paths with backslashes manually, but to always use the Python standard library to do this for you. You don't need to care about escaping certain characters for instance. dir_path = os.path.join('E:', 'Dummy', 'sam', str(folder)) file_name = '{}.png'.format(char) file_path = os.path.join(dir_path, file_name) Another improvement in your code can be made if you don't add 1 to folder inside the loop, but use the built-in function enumerate: for folder_index, file in enumerate(dirs, start=1): # Do your thing here # The variable folder_index is incremented automatically.
score: 2

http://stackoverflow.com/q/49427936
has answer: http://stackoverflow.com/a/49428227
has comment: http://stackoverflow.com/comment/85859803
tagged with: python
tagged with: tkinter-entry
linked to: http://stackoverflow.com/q/34667710
has body: If I had a Frame named as the variable table which has multiple Entry widgets within this Frame, would there be a way of getting all the Entry widgets' text content?
has comment: http://stackoverflow.com/comment/85857194
linked to: http://stackoverflow.com/q/9815063
linked to: http://stackoverflow.com/q/15995783
has comment: http://stackoverflow.com/comment/85857114
duplicate of: http://stackoverflow.com/q/15995783
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85857219
tagged with: python-3.5
score: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85856956
downvote count: 1
has title: Getting all of the Entry text content from a frame
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49428227

http://stackoverflow.com/q/49298120
score: 0
has answer: http://stackoverflow.com/a/49301557
tagged with: django
has body: I have a Lecture model which contains lectures. For each lecture I have a title and a content and eventually some files. I was trying to make that when somebody presses on a title, the title and the content will display under, but only for that lecture. Problem is that if I use a class, all lectures will be shown and if I use and id only the first one will be shown. How should I do this ? $('#title').click(function () { $('#lecture-hide').toggle(); }); {% for c in category.list %} Lecture {{ forloop.counter }}: {{ c.lecture_title }} {{ c.lecture_title }} {{ c.content }} {% for file in c.files.all %} {% if file.files %} {% if forloop.first %} Lecture files: {% endif %} {{ file.files.name }} {% endif %} {% endfor %} {% endfor %}
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49301557
tagged with: python
accepted answer: http://stackoverflow.com/a/49300407
tagged with: django-templates
answer count: 2
has title: How do I hide or show content for each iteration?
has answer: http://stackoverflow.com/a/49300407

http://stackoverflow.com/comment/85665224
score: 0
has text: is the error I get when telegram blocks me because of SPAM. Flood\spam
comment on: http://stackoverflow.com/q/49329364
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49360709
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85813825
has answer: http://stackoverflow.com/a/51957328
upvote count: 10
downvote count: 1
tagged with: python
favorite count: 0
has body: Hi I'm trying to make pycharm's auto-complete works with **kwargs. To do this I'm wrote a doc string using epytext syntax which has a way to declare keyword arguments with @keyword p: but it doesn't works. Do someone know the way to fix it? P.S. I have changed a docstring format in PyCharm setting.
score: 9
tagged with: python-3.x
tagged with: pycharm
has comment: http://stackoverflow.com/comment/85721870
has comment: http://stackoverflow.com/comment/85721574
type: UnansweredQuestion
has title: Pycharm **kwargs auto-complete
has comment: http://stackoverflow.com/comment/85821391

http://stackoverflow.com/comment/85717044
score: 0
comment on: http://stackoverflow.com/q/49284908
type: Comment
has text: (see the reply to my original post below)
type: QuestionComment

http://stackoverflow.com/a/49341506
score: 0
has body: You want to use the threading library. The following program runs the receiving in one thread and the sending in another: import socket from threading import Thread def listen(conn): while True: received = conn.recv(1024).decode() print("Message received: " + received) def send(conn): while True: to_send = input("Input message to send: ").encode() conn.sendall(to_send) host = "127.0.0.1" port = 12345 sock = socket.socket() sock.connect((host, port)) Thread(target=listen, args=[sock]).start() Thread(target=send, args=[sock]).start() This program is for Python 3. Python 2 is very similar, except print() works differently, and you don't need to encode() and decode() everything being sent through a socket. The listen and send functions are run in parallel, so that as soon as data arrives, it is printed, but you can also send data at any time. Practically, you would probably want to make some changes so that the data isn't just printed over the input prompt. However, this would be hard just in a command line application. Research queues for control over data passing between threads. Let me know if you have any more questions.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49341204
type: Answer
answers question: http://stackoverflow.com/q/49341204

http://stackoverflow.com/comment/85824209
type: QuestionComment
comment on: http://stackoverflow.com/q/49411263
score: 3
has text: You need to show the actual code and data you are using. `json.loads(lst)` works fine if `lst` is as you have shown it above.
type: Comment

http://stackoverflow.com/q/49379760
type: Question
duplicate of: http://stackoverflow.com/q/8898765
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85760320
tagged with: python
linked to: http://stackoverflow.com/q/36660460
has body: I am a beginner in Python and I need to call .py script from Java code. I have installed jython but the tutorials I am getting online has material where they are importing Java packages in Python code. But my query is the other way round. I just need a simple code in Java which is able to run Python scripts(.py). Any leads will be highly appreciated.
upvote count: 2
has answer: http://stackoverflow.com/a/49379887
score: 1
tagged with: java
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/8898765
has title: How to run .py scripts from Java code?
favorite count: 0

http://stackoverflow.com/a/49418629
type: Answer
answers question: http://stackoverflow.com/q/49417445
has comment: http://stackoverflow.com/comment/85839040
has comment: http://stackoverflow.com/comment/85839064
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49417445
downvote count: 0
upvote count: 1
has body: If you are having issues with .get(), then you must be on a bad combination of chromedriver and Chrome browser. I would recommend updating to chromedriver 2.36 or Above from HERE And also make sure you have updated to the current Chrome Build 65 by opening this URL: chrome://settings/help If you cannot update to current, please try this: from selenium import webdriver ChromeOptions = webdriver.ChromeOptions() ChromeOptions.add_argument('--disable-browser-side-navigation') driver = webdriver.Chrome('your/path/to/chromedriver.exe', chrome_options=ChromeOptions) For my original answer on this issue, please refer to THIS
score: 1
has comment: http://stackoverflow.com/comment/85869303
has comment: http://stackoverflow.com/comment/85839125

http://stackoverflow.com/comment/85646066
type: QuestionComment
has text: Are you running this with Chrome Driver? (its a separate executable that WebDriver uses to control Chrome) [(Download Page)](https://sites.google.com/a/chromium.org/chromedriver/downloads)
type: Comment
comment on: http://stackoverflow.com/q/49322339
score: 1

http://stackoverflow.com/comment/85775926
score: 0
comment on: http://stackoverflow.com/q/49387174
type: Comment
type: QuestionComment
has text: Maybe the web server is checking the referrer in the headers and actively preventing hotlinking?

http://stackoverflow.com/q/49286039
has answer: http://stackoverflow.com/a/49287151
has body: I am coding on a project where I need to process many tree-like data elements, to overcome some performance issues I want to call a given processing function already written in C with the signature int process(Node* root) and a tree node defined as: typedef struct Node { int value; struct Node ** children; int num_children; } Node; Thus a tree node can have an arbitrary number of child nodes. Analogously a tree node in my Python project is defined as: class Node(): def __init__(self,value): self.value = value self.children = list() def add_child(self,child): self.children.append(child) To call the C function I would like to use CFFI. The problem I ran into is that I need to convert my Python tree data structure to a matching C representation. A node representation, which can be passed to the CFFI function can be created via: ffi_node = ffi.new("Node *") ffi_node.value = some_value But I could not find a way to convert the list references to children to the struct Node** children.
tagged with: python-cffi
tagged with: list
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: pointers
answer count: 1
favorite count: 0
type: Question
tagged with: python
tagged with: http://stackoverflow.com/tag/c
accepted answer: http://stackoverflow.com/a/49287151
has title: Pass a list of object references to a CFFI function

http://stackoverflow.com/comment/85651465
score: 0
type: AnswerComment
type: Comment
has text: as a cludge, you can edit the `gof.py` code, increasing the 1000 to 10000 or perhaps 1e6. But the statsmodels developers will be able to comment on whether there are other reasons that the 1000 value is chosen, e.g. due to loss of support of the distribution.
comment on: http://stackoverflow.com/a/49322957

http://stackoverflow.com/a/49440182
has body: Thank you all for your help. I've managed to figure it out. It now builds a dynamic dictionary or dynamic json for whatever need. import sys, json from faker import Faker fake = Faker() def build_dic(dic_len, dic): if isinstance(dic, (list, tuple)): dic = dict(dic) if isinstance(dic, dict): for counter in range(len(dic)): for k,v in dic.items(): if k[0] == 'B' or k[0] == "M": update = [(fake.first_name(), fake.uri()) for i in range(5)] update = dict(update) dic.update({k: update}) return dic def walk(dic): for key, item in dic.items(): #print(type(item)) if isinstance(item, dict): build_dic(5, item) walk(item) return dic a = build_dic(10, ([(fake.first_name(), fake.uri()) for i in range(10)])) walk(a) print(json.dumps(a, indent=4))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49417719

compare
tags question: http://stackoverflow.com/q/49347045
tag name: compare
type: Tag
tags question: http://stackoverflow.com/q/49319933

http://stackoverflow.com/comment/85749485
comment on: http://stackoverflow.com/a/49373962
score: 1
type: Comment
type: AnswerComment
has text: Well that post was kinda passive agressive, but I understand what's Your point. Thanks for the tips and advice for the future :) Thank You

http://stackoverflow.com/a/49407909
type: Answer
has body: You can try s=df.sum() s.loc['Name']='Total' df.loc[0]=s df.sort_index() Out[457]: Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6
answers question: http://stackoverflow.com/q/49407096
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85580453
comment on: http://stackoverflow.com/a/49287476
type: Comment
has text: I don't believe you can gain a speed advantage from knowing the keys ahead of time and applying this to different dictionaries, the look-ups are O(1) time, your speed-ups will come from elsewhere. Because the operations over the 500 dictionaries are distinct, you could run them in parallel rather than sequentially.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85640577
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49319494
type: QuestionComment
has text: To see the error output, package the app with `console=True` and then run the executable from the command line.

http://stackoverflow.com/a/49321881
answers question: http://stackoverflow.com/q/49320312
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You can use builtin function any to check if there is a match. It will return boolean True or False based on whether the value is matched or not. &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; any(var['name'] == k for k in map(itemgetter('name'),var_list)) &gt;&gt;&gt; True However if you are interested in actual matched element you can do it with following generator expression: &gt;&gt;&gt; next((item for item in var_list if item["name"] == var["name"]),None) &gt;&gt;&gt; {'name': 'John', 'age': 36, 'city': 'Orlando'}

http://stackoverflow.com/a/49327477
has body: It looks like you are going through some extra hoops here. You have a quantity that is already a perfect key. Instead of just using it, you define a comparator that recomputes and compares two of these quantities for every pair of objects, and then convert that comparator back to a key. This seems very inefficient. Why not just define a simple key function and use it directly? def distance_from_origin_squared(point): return point[0]**2 + point[1]**2 points = sorted(points, key=distance_from_origin_squared) Keep in mind that sorted does not operate in-place, so you have to stash it somewhere. Replacing the original name if fine. If you want an in-place sort, use list.sort instead: points.sort(key=distance_from_origin_squared) From a practical point of view, keys offer a number of advantages over comparators. For one thing, a key function only needs to be called once per element, while a comparator is called O(nlog(n)) times. Of course the keys are compared O(nlog(n)) times, but the comparison is usually much simpler since the values of interest are computed up front. The main difficulty coming from C (in my case) is grasping the idea that keys do not have to be single integers, as is usually shown in examples. Keys can be any type that clearly defines the &lt; (or &gt;) operator. Lexicographical comparison of strings, lists and tuples makes it very easy to boil a complex chained comparator to a key that is just a short sequence of values.
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49327344
score: 4

http://stackoverflow.com/comment/85677428
has text: Thank you for your insight, I am currently experiencing a new error while using confusion_matrix.
type: AnswerComment
comment on: http://stackoverflow.com/a/49331149
score: 1
type: Comment

http://stackoverflow.com/a/49352187
score: 1
has comment: http://stackoverflow.com/comment/85787798
has comment: http://stackoverflow.com/comment/85720154
downvote count: 0
has comment: http://stackoverflow.com/comment/85736370
upvote count: 1
has comment: http://stackoverflow.com/comment/85800488
answers question: http://stackoverflow.com/q/49349918
has comment: http://stackoverflow.com/comment/85798984
has comment: http://stackoverflow.com/comment/85798734
has comment: http://stackoverflow.com/comment/85784318
type: Answer
has body: EDIT: 1 Here is an untested substitution: (took the liberty of normalizing the variable names ) def get_balance(x_true, x_pred): x_true = K.tf.round(x_true) x_pred = K.tf.round(x_pred) # didnt see the need for these # NumberOfBars = (x_true) # NumberOfHours = NumberOfBars/60 trade_index = K.tf.not_equal(x_pred[:,1], 0 ) ##remove predictions that are not tradable x_true_tradeable = K.tf.boolean_mask(x_true[:,0], trade_index) x_pred_tradeable = K.tf.boolean_mask(x_pred[:,0], trade_index) cm = K.tf.confusion_matrix(x_true_tradeable, x_pred_tradeable) correct_predictions = cm[0,0]+cm[1,1] wrong_predictions = cm[1,0]+cm[0,1] total_trades = correction_predictions + wrong_predictions accuracy = (correct_predictions/total_trades)*100 return accuracy Original Answer Welcome to SO. As you might know we need to compute the the gradient on the loss function. We can't compute the gradient correctly on numpy arrays (they're just constants). What is done ( in keras/theano which are the backends one uses with keras) is automatic differentiation on Tensors (e.g tf.placeholder()).This is not the entire story but what you should know at this point is that tf / theano gives us gradients by default on operators like tf.max, tf.sum. What that means for you is all the operations on tensors (y_true and y_pred) should be rewritten to use tf / theano operators. I'll comment with what I think would be rewritten and you can substitute accordingly and test. See tf.round used as K.tf.round where K is the reference to the keras backend imported as import keras.backend as K x_true = np.round(x_true) x_pred = np.round(x_pred) Grab the shape of the tensor x_true. K.shape. Compute the ratio over a constant could remain as it as Here NumberOfBars = len(x_true) NumberOfHours = NumberOfBars/60 See tf.where used as K.tf.where TradeIndex = np.where( x_pred[:,1] == 0 )[0] You could mask the tensor w/ a condition instead of deleting - see masking ##remove predictions that are not tradable x_true = np.delete…

http://stackoverflow.com/a/49326901
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49326873
downvote count: 0
has comment: http://stackoverflow.com/comment/85655651
accepted answer of: http://stackoverflow.com/q/49326873
score: 5
upvote count: 5
has body: Add QApplication.processEvents(). QCoreApplication.processEvents (QEventLoop.ProcessEventsFlags flags = QEventLoop.AllEvents) Processes all pending events for the calling thread according to the specified flags until there are no more events to process. You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file). Your widget originally will be shown but unresponsive. To make the application responsive, add processEvents() calls to some whenever you add an item. Do keep in mind that this can affect performance a lot. This lets the whole application loop execute including any queued events. Don't add this to performance sensitive loops. Also consider that this allows your user to interact with the application, so make sure that any interactions that can happen either are not allowed, such as somebutton.enabled(False), or are handled gracefully, like a Cancel button to stop a long task. See the original C++ docs for further information, since pyqt is a direct port.

http://stackoverflow.com/q/49379491
has body: I have added a python script to my PATH variable in linux, but when I called it does not seem to execute. Steps I've tried: I have checked that it is pointing to the right file with which. I have added a bash script in the same directory as the python file, it worked fine. I have tried to print to terminal as well as generate a file, neither worked. I have successfully run the script by calling it directly from within the directory. I am using the BASH shell if that helps, but I am stumped. Thanks!
score: 1
tagged with: scripting
has comment: http://stackoverflow.com/comment/85759851
has comment: http://stackoverflow.com/comment/85759796
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85781939
answer count: 0
has comment: http://stackoverflow.com/comment/85759775
type: UnansweredQuestion
tagged with: path
downvote count: 0
has title: Calling python script on PATH
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85759945

http://stackoverflow.com/comment/85797613
type: Comment
comment on: http://stackoverflow.com/a/49377086
score: 0
type: AnswerComment
has text: ok @eyllanesc actually i had less time in hand for development and kivy is new platform for me. i learned this in last week and that's why facing issue in merging 2 seperate code. please help once. if possible can you open chat session

http://stackoverflow.com/comment/85874211
score: 0
has text: Roughly, if you loop over the Py3 `map` object then you only hold in memory each item of the iterable at any one time, rather than the entire iterable (like with a `list`); see my suggested dupe for some other details/differences
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49435978

http://stackoverflow.com/q/49343473
has body: I am trying to add data to my firebase real-time database. I am using this following code below: from firebase import firebase class Sugar: firebase = firebase.FirebaseApplication('https://diatrack-48525.firebaseio.com/',authentication=None) result = firebase.post('/Sugar type',{'name':name,'gender':gender,'age': age,'sugartype':'Type 1'}) It shows following error: result = firebase.post('/Sugar type',{'name':name,'gender':gender,'age': age,'sugartype':'Type 1'}) AttributeError: module 'firebase.firebase' has no attribute 'post'
answer count: 1
downvote count: 0
tagged with: python-requests
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49343554
has title: AttributeError: module 'firebase.firebase' has no attribute 'post' on firebase python
type: UnansweredQuestion
tagged with: firebase-realtime-database
tagged with: python
tagged with: python-3.6
tagged with: firebase
score: 2
upvote count: 2

http://stackoverflow.com/q/49299905
linked to: http://stackoverflow.com/q/12573816
has title: error LNK2001: unresolved external symbol PyInit_
type: AnsweredQuestion
answer count: 2
score: 7
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/85601490
favorite count: 0
accepted answer: http://stackoverflow.com/a/49300644
type: Question
has answer: http://stackoverflow.com/a/49300644
possible better answer: http://stackoverflow.com/a/70788413
tagged with: cpython
has body: I am trying to follow this tutorial to be abe to use C code in python. http://dfm.io/posts/python-c-extensions/ here is the gist https://gist.github.com/GreenJoey/b08528d6abe62da70f28f73c39c0efd0 when I try to compile it using python setup.py build_ext --inplace it fails with this error message: running build_ext No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils building '_chi2' extension creating build\temp.win-amd64-3.6 creating build\temp.win-amd64-3.6\Release C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" -I"C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" -I"C:\Program Files (x86)\Windows Kits\8.1\include\shared" -I"C:\Program Files (x86)\Windows Kits\8.1\include\um" -I"C:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tc_chi2.c /Fobuild\temp.win-amd64-3.6\Release\_chi2.obj C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" -I"C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" -I"C:\Program Files (x86)\Windows Kits\8.1\include\shared" -I"C:\Program Files (x86)\Windows Kits\8.1\include\um" -I"C:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcchi2.c /Fobuild\temp.win-amd64-3.6\Release\chi2.obj C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIF…
has answer: http://stackoverflow.com/a/70788413
tagged with: python
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/a/49389257
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49388091
has body: Thanks for the tip to use Selenium. I was able to get the price information with the following code. browser.get("https://www.vudu.com/content/movies/details/title/835625") price_element = browser.find_elements_by_xpath("//div[@class='row nr-p-0 nr-mb-10']") prices = [x.text for x in price_element]

http://stackoverflow.com/a/49305778
has body: This is likely caused by your locale settings. If it's set to UTF-8, then this should work as expected in your Python script. Try this command to see the charmap in your setup: $ locale charmap UTF-8 If you get something else in the output (like ISO-8859-1 or ANSI_X3.4-1968) then it means you're not correctly set up for UTF-8... You can try to set environment variable LC_CTYPE to something like en_US.UTF-8 (assuming English is your language), which might fix this. Inside Python, you can also force a default encoding with: text_file = open(filepath, "r", encoding="utf-8") But it's possible you're going to find other encoding problems if your system is not correctly set up for it... So try to fix that first, if you can. Good luck!
downvote count: 0
has comment: http://stackoverflow.com/comment/85613906
answers question: http://stackoverflow.com/q/49305349
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85621230
accepted answer of: http://stackoverflow.com/q/49305349
has comment: http://stackoverflow.com/comment/85614149
type: AcceptedAnswer

http://stackoverflow.com/q/49417780
has title: How can I wait for the finish of execution of a command in Unix?
tagged with: unix
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/85837867
type: UnansweredQuestion
has body: I have 25 processor in a compute node. I have a main python script A that a) runs in a loop 3) Performs 20 tasks in every loop that is also distributed among the 25 processors. Main Python Script A Lots of calculations os.system("csh subtask.csh; wait") Lots of calculations Return to beginning of loop Where, subtask.csh is of this type: ./model -h 1 controlfile ./model -h 2 controlfile ./model -h 3 controlfile ./model -h 4 controlfile ./model -h 5 controlfile ... ./model -h 20 controlfile But, this way, my program doesn't wait for subtask.csh to finish. How can I make it wait?
has answer: http://stackoverflow.com/a/49421980
answer count: 1
tagged with: shell
has comment: http://stackoverflow.com/comment/85837319
has comment: http://stackoverflow.com/comment/85837647
type: Question
has comment: http://stackoverflow.com/comment/85837470
has comment: http://stackoverflow.com/comment/85837495
tagged with: csh
tagged with: python
has comment: http://stackoverflow.com/comment/85837666

http://stackoverflow.com/comment/85744522
comment on: http://stackoverflow.com/a/49371681
type: Comment
has text: This indeed works as expected - but _their ops need to have control dependencies when they're created_ still escapes me. I mean doesn't `with tf.control_dependencies([d_optim]):` mean that `d_optim`, that is the `tf.assign(a, a + 2)` must be executed before the `op` aka the print ? Or could this behavior mean that for instance the `assign` ops are executed anyway in random order before the print ? In other words, as the assign ops are linked to the print they should not execute unless the Print is executed (evaluated). I miss something here
score: 0
type: AnswerComment

http://stackoverflow.com/q/49436224
type: Question
tagged with: firefox-profile
has comment: http://stackoverflow.com/comment/87073263
has body: I try to connect to a specific site using Selenium WebDriver Firefox through TOR Socks5 at 9050 port and I can't establish the connection. profile = FirefoxProfile() profile.set_preference('network.proxy.type', 1) profile.set_preference( "network.proxy.socks_version", 5 ) profile.set_preference('network.proxy.socks', '127.0.0.1') profile.set_preference('network.proxy.socks_port', 9050) profile.set_preference( "network.proxy.socks_remote_dns", True ) browser = webdriver.Firefox(firefox_profile=profile) The site is probably blocking some TOR connections but the odd thing is that I can connect to it using TorBrowser! I even found the exit node that was used by TorBrowser and edited my torrc file to use it too (ExitNodes 'ip'). I checked that my selenium Firefox's exit node was the same (I can successfuly connect to other sites through TOR proxy and check my ip), but I still can't connect, even using the same ip! Where is my mistake? And the second thing is that if I set up: profile.set_preference('network.proxy.socks_port', 9150) i.e. use TorBrowser proxy, selenium Firefox successfully establishes connection to the site . Is it something wrong with my tor settings?
type: UnansweredQuestion
upvote count: 5
has title: Using Selenium WebDriver + Tor as proxy
tagged with: python
tagged with: proxy
has answer: http://stackoverflow.com/a/53738789
tagged with: tor
score: 3
downvote count: 2
answer count: 1
tagged with: selenium
favorite count: 0

http://stackoverflow.com/comment/85817286
has text: Just be careful. If a pressing `w` moves the robot and releasing the key stops it, then if the robot gets out of range will keep moving forever. Trust me, you will need a more complex system where the robot pings the computer and activates a safe stop if no ping is received back.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49353430
score: 0

http://stackoverflow.com/q/49341712
answer count: 1
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 0
has body: In my Flask app I allocate a ThreadPool before the first request and use the threads allocated here to execute tasks asynchronously from app import app from multiprocessing.pool import ThreadPool @app.before_first_request def initialize(): app.pool = ThreadPool(10) Sometime later... app.pool.apply_async(exporter, args=(domains)) I am using a uWSGI backend for my webserver and this works fine except my uwsgi log in /var/log/uwsgi/%n.log only logs the stdout from threads executed from this pool. I am unable to see the stderr. I was wondering if this was possible using uwsgi logging capabilities or if I have to use a pluggable logger. Thanks!
has title: How to log stderr from task executed asynchronously using uWSGI
accepted answer: http://stackoverflow.com/a/49344288
tagged with: uwsgi
has answer: http://stackoverflow.com/a/49344288
type: Question

http://stackoverflow.com/q/49390096
accepted answer: http://stackoverflow.com/a/49390218
type: Question
type: AnsweredQuestion
has body: This is a problem that I found recently and I enjoy very much to design a solution. I think that it is a nice exercise and a good example of the combination of for loops and pandas. I have the following pandas data frame, with three columns: ['runs','Period_change', 'Close', 'sum']. I want to implement an alternative to the following for loop to speed up the program. import pandas as pd game = pd.read_csv('test.csv').set_index('timestamp').dropna() for l in game['runs'].unique(): game['sum'][game['runs'] == l] = game[game['runs'] == l]['Period_change'].sum()/game[game['runs'] == l]['Close'].iloc[0]
tagged with: python
tagged with: optimization
score: 0
tagged with: for-loop
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49390218
has title: Optimization of a for loop with pandas

http://stackoverflow.com/a/49283144
type: Answer
accepted answer of: http://stackoverflow.com/q/49281459
has body: It's easier to work with einsum than tensordot. So let's start there: In [469]: a = np.random.normal(size=[3,2,5]) ...: b = np.random.normal(size=[5,2,3]) ...: In [470]: c = np.zeros([3,3,5]) # c.size is 45 In [471]: for i in range(5): ...: c[:,:,i] = a[:,:,i].dot(b[i,:,:]) ...: In [472]: d = np.einsum('abi,ibd-&gt;iad', a, b) In [473]: d.shape Out[473]: (5, 3, 3) In [474]: d = np.einsum('abi,ibd-&gt;adi', a, b) In [475]: d.shape Out[475]: (3, 3, 5) In [476]: np.allclose(c,d) Out[476]: True I had to think a bit about to match up the dimensions. It helped to focus on a[:,:,i] as 2d, and similarly for b[i,:,:]. So the dot sum is over the middle dimension of both arrays (size 2). In testing ideas it might help if the first 2 dimensions of c were different. There'd be less chance of mixing them up. It's easy to specify the dot summation axis (axes) in tensordot, but harder to constrain the handling of the other dimensions. That's why you get a 4d array. I can get it to work with a transpose, followed by taking the diagonal: In [477]: e = np.tensordot(a,b,[1,1]) In [478]: e.shape Out[478]: (3, 5, 5, 3) In [479]: e1 = e.transpose(0,3,1,2)[:,:,np.arange(5),np.arange(5)] In [480]: e1.shape Out[480]: (3, 3, 5) In [481]: np.allclose(c,e1) Out[481]: True I've calculated a lot more values than needed, and thrown most of them away. matmul with some transposing might work better. In [482]: f = a.transpose(2,0,1)@b In [483]: f.shape Out[483]: (5, 3, 3) In [484]: np.allclose(c, f.transpose(1,2,0)) Out[484]: True I think of the 5 dimension as 'going-along-for-ride'. That's what your loop does. In einsum the i is the same in all parts.
answers question: http://stackoverflow.com/q/49281459
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85571332
type: Comment
comment on: http://stackoverflow.com/a/49283315
type: AnswerComment
score: 0
has text: After a little tweaking (had to groupby two variables in my actual code), this did the trick! Thanks @Wen

http://stackoverflow.com/comment/85756054
type: AnswerComment
comment on: http://stackoverflow.com/a/49358018
has text: and how can I fix the Error, I have no clue
type: Comment
score: 0

http://stackoverflow.com/a/49396508
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49396310
has body: You need to handle some edge cases when removing your elements, namely when the p is the first or last element in the list. This uses a handy random function, choice to determine which adjacent element you choose. while len(nlist) &gt; 1: # the number to remove p_index = random.randrange(len(nlist)) if p_index == 0: q_index = p_index + 1 elif p_index == len(nlist) - 1: q_index = p_index - 1 else: q_index = p_index + random.choice([-1, 1]) p, q = nlist[p_index], nlist[q_index] nlist.pop(p_index) nlist.pop(q_index) return p, q

http://stackoverflow.com/q/49351146
downvote count: 0
has answer: http://stackoverflow.com/a/49351316
tagged with: python
has body: I'm new to Python and trying to verify if a given port number is valid or not. 1st Attempt PortNumber = input("Enter a port number: ") if PortNumber.isdigit() == True: print("This is a VALID port number.") else: print("This is NOT a valid port number.") Output C:\&gt; python test.py Enter a port number: a This is NOT a valid port number. C:\&gt; python test.py Enter a port number: -1 This is NOT a valid port number. C:\&gt; python test.py Enter a port number: 8 This is a VALID port number. C:\&gt; python test.py Enter a port number: 88888 This is a VALID port number. C:\&gt; The only problem with this code is the port number has to be an integer between 1-65535. 2nd attempt PortNumber = int(input("Enter a port number: ")) if 1&lt;= PortNumber &lt;= 65535: print('This is a VALID port number.') else: print('This is NOT a valid port number.') Output C:\&gt; python test2.py Enter a port number: 65535 This is a VALID port number. C:\&gt; python test2.py Enter a port number: 65536 This is NOT a valid port number. C:\&gt; python test2.py Enter a port number: -1 This is NOT a valid port number. C:\&gt; python test2.py Enter a port number: a Traceback (most recent call last): File "test2.py", line 1, in &lt;module&gt; PortNumber = int(input("Enter a port number: ")) ValueError: invalid literal for int() with base 10: 'a' C:\&gt; I managed to filter out the numbers between 1-65535 in second code, however there is another problem with the a character. How can I combine both ideas in the code?
has comment: http://stackoverflow.com/comment/85702107
score: 2
has answer: http://stackoverflow.com/a/49351218
has comment: http://stackoverflow.com/comment/85702109
has answer: http://stackoverflow.com/a/49351304
has answer: http://stackoverflow.com/a/49351198
has comment: http://stackoverflow.com/comment/85703661
has title: Python 3: Verifying port number (integer between 1-65535)
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49351216
upvote count: 2
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/q/49379864
has comment: http://stackoverflow.com/comment/85816860
has comment: http://stackoverflow.com/comment/85790686
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: bash
has title: Tensorflow Error when restoring pretrained network - speech recognition
score: 0
tagged with: text-to-speech
has comment: http://stackoverflow.com/comment/85773464
answer count: 0
tagged with: tensorflow
tagged with: speech-recognition
has body: I'm trying to complete this tutorial of TensorFlow: https://www.tensorflow.org/versions/master/tutorials/audio_recognition There I'm interested in creating a simple words recognition that can do speech-to-text. However, after successfully training the network, the next step (according to the tutorial) would be to do this: python tensorflow/examples/speech_commands/freeze.py \ --start_checkpoint=/tmp/speech_commands_train/conv.ckpt-18000 \ --output_file=/tmp/my_frozen_graph.pb When I do this I get the following error: InvalidArgumentError (see above for traceback): Unsuccessful TensorSliceReader constructor: Failed to get matching files on ./tmp/speech_commands_train/conv.ckpt-18000: Not found: ./tmp/speech_commands_train; No such file or directory [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]] To see the whole error, I created this pastebin: https://pastebin.com/NUBSec6Q Anyone know how I can fix this? Have been going through my directories and fiddling around, but cannot seem to come up with a solution.

http://stackoverflow.com/q/49363092
has body: I use to django for my web site. But ı have a question about blog/urls.py(my app name is blog ) I use to with one to many releationship in blog/models.py. Category (1 => *) Subject (1 => *) Article. class Category(models.Model): name = models.CharField(max_length=200) statement = models.TextField() slug=models.SlugField() page_name = models.ForeignKey('Page', on_delete=models.CASCADE) def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=200) statement = models.TextField() slug=models.SlugField() category_name = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.name class Article(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug=models.SlugField() text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) subject_name = models.ForeignKey('Subject', on_delete=models.CASCADE) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={'id' : self.id}) blog/views.py def detail(request,article_slug): article = get_object_or_404(Article, slug=article_slug) article_list=Article.objects .all() subject_list = Subject.objects.all() context={ 'article': article, 'article_list':article_list, 'subject_list': subject_list } return render(request, 'blog/detail.html', context) blog/urls.py url(r'^(?P&lt;category_slug&gt;[\w-]+)/(?P&lt;subject_slug&gt;[\w-]+)/(?P&lt;article_slug&gt;[\w-]+)/$', views.detail, name='detail'), I want to see the url when I click on the links of my article http://127.0.0.1:8000/myworkandresearch/category_slug/subject_slug/article_slug blog / urls.py 'How can I edit?
tagged with: url
has answer: http://stackoverflow.com/a/49365345
type: Question
has answer: http://stackoverflow.com/a/49363978
has comment: http://stackoverflow.com/comment/85727884
has title: Django One to Many relationship urls
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/85729832
tagged with: python
score: 0
tagged with: view
answer count: 2
tagged with: models

http://stackoverflow.com/comment/85782432
has text: thanks again! That fixed the upper end of the colormap. Now I just need to figure out how to get the quiver line working to plot wind vectors. Curious about this line: lower = np.ones((int(256/4),4)) I know np.ones returns an array of ones, but what does 'int' accomplish? Return whole integers?
comment on: http://stackoverflow.com/a/49367945
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85878306
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49437868
has text: Thanks @Jean-FrançoisFabre, but from what ive read this is how you do a dictionary comprehension, what is the correct dict comprehension?
score: 0

http://stackoverflow.com/a/49383057
upvote count: 3
has body: I believe you need extract values to new column and then merge, last remove helper column Test3: pat = '|'.join(r"{}".format(x) for x in DF1.Test1) DF2['Test3'] = DF2.Test1.str.extract('('+ pat + ')', expand=False) DF = pd.merge(DF1, DF2, left_on= 'Test1', right_on='Test3').drop('Test3', axis=1) print (DF) Test1_x Test2_x Test1_y Test2_y 0 A 1 bA 2 1 C 3 cCc 3 Detail: print (DF2) Test1 Test2 Test3 0 ee 1 NaN 1 bA 2 A 2 cCc 3 C 3 D 4 NaN
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49382937
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49382937
score: 3

http://stackoverflow.com/comment/85800022
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49398660
has text: `setup script which can set IE zoom level to 100%` shouldn't be a _usecase_ itself to be validated rather it's [**Required Configuration**](https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration) to set up the _Internet Explorer Driver_.
type: Comment

http://stackoverflow.com/q/49283341
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 6
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
type: Question
has body: Using sklearn to run a grid search on a random forest classifier. This has been running for longer than I thought, and I am trying to estimate how much time is left for this process. I thought the total number of fits it would do would be 3*3*3*3*5 = 405. clf = RandomForestClassifier(n_jobs=-1, oob_score=True, verbose=1) param_grid = {'n_estimators':[50,200,500], 'max_depth':[2,3,5], 'min_samples_leaf':[1,2,5], 'max_features': ['auto','log2','sqrt'] } gscv = GridSearchCV(estimator=clf,param_grid=param_grid,cv=5) gscv.fit(X.values,y.values.reshape(-1,)) From the output, I see it cycling through the tasks where each set is the number of estimators: [Parallel(n_jobs=-1)]: Done 34 tasks | elapsed: 1.2min [Parallel(n_jobs=-1)]: Done 184 tasks | elapsed: 5.3min [Parallel(n_jobs=-1)]: Done 200 out of 200 tasks | elapsed: 6.2min finished [Parallel(n_jobs=8)]: Done 34 tasks | elapsed: 0.5s [Parallel(n_jobs=8)]: Done 184 tasks | elapsed: 3.0s [Parallel(n_jobs=8)]: Done 200 tasks out of 200 tasks | elapsed: 3.2s finished [Parallel(n_jobs=-1)]: Done 34 tasks | elapsed: 1.1min [Parallel(n_jobs=-1)]: Done 50 tasks out of 50 tasks | elapsed: 1.5min finished [Parallel(n_jobs=8)]: Done 34 tasks | elapsed: 0.5s [Parallel(n_jobs=8)]: Done 50 out of 50 tasks | elapsed: 0.8s finished I counted up the number of "finished" and it is at 680 currently. I thought it would be done at 405. Is my calculation wrong?
accepted answer: http://stackoverflow.com/a/49284287
tagged with: random-forest
has answer: http://stackoverflow.com/a/49284287
tagged with: grid-search
tagged with: python
has title: How many combinations will GridSearchCV run for this?
upvote count: 6

http://stackoverflow.com/comment/85682643
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49340963
has text: @user3000345 It is anything _but_ efficient.
type: Comment

http://stackoverflow.com/q/49397489
has comment: http://stackoverflow.com/comment/85840551
has comment: http://stackoverflow.com/comment/85797338
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49463117
type: UnansweredQuestion
answer count: 1
tagged with: perspective
downvote count: 0
has comment: http://stackoverflow.com/comment/85822544
upvote count: 1
favorite count: 0
type: Question
tagged with: opencv
has title: Using getPerspective in opencv
has body: I have an image that I want to stretch to cover the entire screen after transformation. My code is as such: src = np.array([[0, 0], [997, 102], [1000, 600], [0, 995]], np.float32) dst = np.array([[0, 0], [997, 0], [1000, 995], [0, 995]], np.float32) M = cv2.getPerspectiveTransform(src, dst) warped = cv2.warpPerspective(img, M, (1000, 1000)) where the src coordinates refer to the 4 red points in the image, in clockwise order. The dst coordinates refer to the 2 red points on the left, and the 2 blue points on the right of the image, in clockwise order. The idea is that I want to "stretch" the image such that the 2 red points on the right correspond to the 2 blue points. However, the warped image turns out to be: Is there something I did wrong, or assumed wrongly about the usage of the functions?

http://stackoverflow.com/comment/85744149
has text: The SQL query is actually massive, and I can't sum it there unfortunately. I've been doing some research and cannot find a solution the works for summing the columns in python.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49371574

http://stackoverflow.com/a/49332019
downvote count: 0
upvote count: 1
has body: The difference is a reflection of the assignment syntax as specified in the python language reference. Your first example generates a modified copy of the list and sets the contents of your list to the contents of the copy. The second example generates a modified copy and assigns the list identifier to point to that copy. You can see this more clearly by calling id on your list before and after: id(list) list[:] = list[len(list) - k:] + list[:len(list) - k] id(list) # prints the same id as above id(list) list = list[len(list) - k:] + list[:len(list) - k] id(list) # prints a new id representing a new list object In the second case, list has a different id because it actually represents a new list object, where the first reuses the list and only updates the contents. With that being said, notice that in both cases a copy of the list is being made so you aren't really gaining anything. Neither update is truly being calculated in-place. For this reason, in 99% of cases I would go with the second more concise syntax. Furthermore the 'in place' version involves updating potentially many elements within the list, where just updating the list identifier is always a single update. You can see the small performance overhead from the extra copy work with the following experiments: $ python -m timeit 'x=range(100000); x[:]=x[::-1]' 100 loops, best of 3: 3.62 msec per loop $ python -m timeit 'x=range(100000); x=x[::-1]' 100 loops, best of 3: 2.62 msec per loop $ python -m timeit 'x=range(10); x[:]=x[5:] + x[:5]' 1000000 loops, best of 3: 1.31 usec per loop $ python -m timeit 'x=range(10); x=x[5:] + x[:5]' 1000000 loops, best of 3: 1.02 usec per loop
type: Answer
answers question: http://stackoverflow.com/q/49331802
score: 1

http://stackoverflow.com/comment/85716393
score: 1
type: Comment
type: QuestionComment
has text: What part of the pip website makes you think it's not included with 3.4+?
comment on: http://stackoverflow.com/q/49358231

http://stackoverflow.com/q/49434432
has comment: http://stackoverflow.com/comment/85873880
type: Question
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85872492
has comment: http://stackoverflow.com/comment/85874516
favorite count: 0
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49437398
accepted answer: http://stackoverflow.com/a/49439633
has body: I have the following square DataFrame: In [104]: d Out[104]: a b c d e a inf 5.909091 8.636364 7.272727 4.454545 b 7.222222 inf 8.666667 7.666667 1.777778 c 15.833333 13.000000 inf 9.166667 14.666667 d 4.444444 3.833333 3.055556 inf 4.833333 e 24.500000 8.000000 44.000000 43.500000 inf this is modified distance matrix, representing pairwise distance between objects ['a','b','c','d','e'], where each row is divided by a coefficient (weight) and all diagonal elements artificially set to np.inf. How may I get a list/vector of indices like as follows in an efficient (vectorized) way: d # index of minimal element in the column `a` a # index of minimal element in the column `b` (excluding already found indices: [d]) b # index of minimal element in the column `c` (excluding already found indices: [d,a]) c # index of minimal element in the column `d` (excluding already found indices: [d,a,b]) I.e. in the first column we had found index d, so when we search for a minimum in the second column we are excluding row with index d (found previously in the first column) - this would be a. When we are looking for the minimum in the third column we are excluding rows with indices found previously (['d','a']) - this would be b. When we are looking for the minimum in the fourth column we are excluding rows with indices found previously (['d','a','b']) - this would be c. I don't need diagonal (inf) elements, so the resulting list/vector will contain d.shape[0] - 1 elements. I.e. the resulting list will look like: ['d','a','b','c'] or in case of Numpy solution the corresponding numerical indices: [3,0,1,2] It's not a problem to do it using slow for loop solution, but I can't wrap my head around a vectorized (fast) solution...
has answer: http://stackoverflow.com/a/49437398
answer count: 2
has answer: http://stackoverflow.com/a/49439633
downvote count: 0
has title: *Vectorized* way to find indices of minimums for each column (excluding all already found indices)
tagged with: python
has comment: http://stackoverflow.com/comment/85874453
has comment: http://stackoverflow.com/comment/85871689
upvote count: 6
score: 6

http://stackoverflow.com/comment/86190139
type: AnswerComment
comment on: http://stackoverflow.com/a/49525170
has text: I believe that I am aggregating the results in memory. I take each of the 1024 dictionaries and dump them one by one into the Redis database through a local network connection. It takes a long time to loop through the key-value pairs, and I cannot use `redis.mset` because each of those dictoinaries is too large and I get `redis.exceptions.ConnectionError: connection reset by peer`
score: 0
type: Comment

http://stackoverflow.com/comment/85763819
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49381525
has text: Thanks for Your answer, i'm still new to python, how does this fit in with my code, do i need to define 'labels' ?

http://stackoverflow.com/comment/85637379
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49316872
has text: I edit my post. I think I misunderstand something from your answer.

http://stackoverflow.com/comment/85716414
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49358231
has text: pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4 binaries downloaded

http://stackoverflow.com/a/49333846
type: Answer
score: 0
has body: You could In [22]: (df.groupby(df'Students','Class'.isnull().all(1).cumsum()) .agg({'Subjects': ' '.join, 'Students': 'first', 'Class': 'first'})) Out[22]: Students Subjects Class 0 10.0 Mathematics 3.0 1 12.0 Computer Science 5.0 In [23]: df Out[23]: Subjects Students Class 0 Mathematics 10.0 3.0 1 Computer NaN NaN 2 Science 12.0 5.0
answers question: http://stackoverflow.com/q/49333733

http://stackoverflow.com/a/49343103
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: For this type of work the basic pattern is to define a function that knows how to yield the meaningful units (the blocks or sections of the file that you care about): import sys def main(file_path): blocks = list(read_blocks(file_path)) for block in reversed(blocks): for line in block: print(line, end = '') def read_blocks(file_path): block = [] with open(file_path) as fh: for line in fh: if line.startswith('Label: '): if block: yield block block = [] block.append(line) # A common bug is to forget the last block. if block: yield block main(sys.argv[1])
answers question: http://stackoverflow.com/q/49343043

http://stackoverflow.com/q/49397440
has body: I have a numpy array that is a 3d array. It is supposed to be shape (1000,100, 3), but the shape of it at first dimension is (1000,) and of each entry inside, the shape is (100, 3). How can I reshape it such that I have (1000,100, 3) for the original array?
accepted answer: http://stackoverflow.com/a/49397466
has title: Nested numpy array with shape difference
has answer: http://stackoverflow.com/a/49397466
tagged with: python
tagged with: numpy
score: 0
answer count: 1
type: Question
type: AnsweredQuestion

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

http://stackoverflow.com/comment/85835603
comment on: http://stackoverflow.com/q/49366473
has text: Are you familiar with otree? I'm assuming you are given that you guessed "views.py" was relevant. I can post them, but I should not leave them up.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49352655
has body: I'am developing a website in Python Django. I have two "class CustomUser" it is used in order to login and another "class coach", this class contains information about users. I need to match these two class. My website identify the user who is logged in but it fail to assign this user a coach class. When I try to submit my form I receive the error "Cannot assign "'prof'": "coach.user" must be a "CustomUser" instance." I'am a beginner in Python Django. Can you help me to resolve this problem ? This is Site/models.py class coach(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) Telephone = models.IntegerField() Level = models.TextField() Study = models.TextField() This is my users/models.py from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() This is my Site/views.py there I have a function which find the user and assign him a coach class. def Register(request): form = ContactForm(request.POST or None, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user.username obj.save() form.save() return render(request, 'Register.html', {'form': form})
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85706352
score: 0
has title: Django: Cannot assign "'prof'": "coach.user" must be a "CustomUser" instance
answer count: 0
tagged with: django-custom-user
tagged with: assign
has comment: http://stackoverflow.com/comment/85705957
type: Question
has comment: http://stackoverflow.com/comment/85706305

http://stackoverflow.com/q/49381342
answer count: 1
accepted answer: http://stackoverflow.com/a/49382797
score: -1
has answer: http://stackoverflow.com/a/49382797
tagged with: scrapy
has title: Can't extract information without unnecessary characters
type: Question
tagged with: xpath
has comment: http://stackoverflow.com/comment/85765533
upvote count: 0
tagged with: web-scraping
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has body: I was doing webscraping with Scrapy and Python and not able to write a proper xpath command to extract full event description from this URL : [https://www.......com/events/9275-big-talks] without any unnecessary character but it's fetching many unnecessary chars like ' ', '\r\n' etc. I am writing this command: response.xpath('//*[@class = "events-discription-block"]//*/text()').extract() And getting this output: ['Event Description', 'The Theme of the conference will be ‘Learn from Leaders’, where Industry experts and great influential leaders will address. This Conference will deliver an exceptional speaks. The concept or the idea is to connect great leaders to the one who are looking for guidance in their life. A ‘Social Experiment’ to provide a platform for sharing success stories and ideas, empowering people to work towards their dreams from great leaders.', ' ', 'Agenda:', ' 09:00 am – 09:30 am: Registration &amp; Welcome Note by Organizers.', ' ', '09:30 am to 10:00 am: Innovation &amp; story of Lakshmi asu machine By Padamashri Chintakindi Mallesham (Handloom Weaver).', ' ', '10:00 am to 10:25 am: A Moment of Choice By Vyjayanti Vasanta Mogli (Transgender Activists).', ' ', '10:25 am to 10:50 am: Back to the Roots By Dr. G V Ramanjaneyulu (Agriculturist).', ' ', '10:50 am to 11:00 am: Snacks break.', ' ', '11:00 am to 11:25 am: Journey Bonded to Psoriasis By Munipally Snigdha (Youngest poets in the poetry circuit).', ' ', '11:25 am to 11:50 am: Startups how to raise Funds By Suman Gandham (Venture Capitalist. Barcelona, Spain).', ' ', '11:50 am to 12:15 pm: Qualities Of The Most Effective Leaders By Mir Mahmood Ali (Leadership Motivator).', ' ', '12:15 pm to 12:45 pm: Entrepreneur Journey By Sri Charan Lakkaraju (Entrepreneur).', ' ', '12:45 pm to 01:00 pm: Announcements / Networking / Closing Note. ', 'Rules &amp; Regulations:', '\r\n', 'Attendees must carry a print out of the booking confirmation for entry inside the venue.', '\r\n', 'Each ticket / confirma…

http://stackoverflow.com/q/49328814
has answer: http://stackoverflow.com/a/49328901
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am using pyodbc to create or drop table. And I wrote a function to drop table if table has already existed. Please look at my syntax below try: cur.execute('Drop table {}'.format(table_name)) except ProgrammingError: cur.execute(create_table) However, I got error message : &lt;ipython-input-79-fe0fe29a1e8e&gt; in upload_to_SQL(file_name, skiprows, table_name) 26 try: 27 cur.execute('Drop table {}'.format(table_name)) ---&gt;28 except ProgrammingError: 29 cur.execute(create_table) 30 NameError: name 'ProgrammingError' is not defined I confirm that ProgrammingError is the error message if I drop a table didn't exist in the sql server. Anyone have idea how to revise this?
possible better answer: http://stackoverflow.com/a/49329256
tagged with: try-except
has title: Python try except to drop or create table in sql server
has answer: http://stackoverflow.com/a/49329256
linked to: http://stackoverflow.com/q/7887011
accepted answer: http://stackoverflow.com/a/49328901
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49293053
has title: python : np.where() and broadcasting
has comment: http://stackoverflow.com/comment/85588736
has comment: http://stackoverflow.com/comment/85588734
has body: Can someone please help me to understand how broadcasting works below in np.where() function ? x = np.arange(9.).reshape(3, 3) np.where(x &lt; 5, x, -1) # Note: broadcasting. array([[ 0., 1., 2.], [ 3., 4., -1.], [-1., -1., -1.]])
type: Question
tagged with: python
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/85588849
tagged with: array-broadcasting
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49294146
answer count: 1

http://stackoverflow.com/comment/85616291
score: 0
has text: @SagarRuchandani Done, doesn't work either, same outcome.
comment on: http://stackoverflow.com/q/49306112
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85686169
comment on: http://stackoverflow.com/q/49342926
score: 0
has text: We need a [mcve]. The code you've posted doesn't contain anything that would cause the behavior described.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49367132
possible better answer: http://stackoverflow.com/a/49367184
linked to: http://stackoverflow.com/q/6260089
tagged with: python
has answer: http://stackoverflow.com/a/49367184
tagged with: dictionary
has answer: http://stackoverflow.com/a/49367228
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49367194
answer count: 3
has answer: http://stackoverflow.com/a/49367194
has body: I have a dictionary: {'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]} I wish to pop the list values that are outside of the UK, therefore taking the first value within the lists and comparing to see if it is equal to 'UK'. I currently have: for k,v in insideUK.items(): for i in v: if i[0] == "UK": print(x) else: k.pop(v) I know after the else is wrong but need help! I wish for the dict to look like this once finished popping values that aren't equal to "UK". {'dict': 'UK', '3', '-9'}
type: Question
has title: Python pop dictionary list values

http://stackoverflow.com/comment/85589852
comment on: http://stackoverflow.com/a/49293352
has text: I tried giving the absolute path for activating my virtual environment, but this didn't seem to solve my issue.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49339373
has body: The problem here is that you're calling checkPath() in the class initialization. checkPath() read the path one time, and then start to evaluate if that path is valid 'forever'. This while loop running may even prevent the software to be able to effectively read again the text from self.pathEditLine. Usually it's better to connect each function to an event: Check if the folder exist when a button is pressed Check if the folder exist when the text change Check if the folder exist when the user press enter For doing any of these, you have to connect one of these events to the function: button event: self.btnMyNewButton.clicked.connect(checkPath) text changing event: self.pathEditLine.textChanged.connect(checkPath) enter button event: self.pathEditLine.returnPressed.connect(checkPath) This means that you have to substitute one of the previous lines with the line where you call the checkPath() function in the initialization: def __init__(self,windowObject ): self.windowObject = windowObject self.setupUi(windowObject) self.pathEditLine.textChanged.connect(checkPath) self.windowObject.show() you also have to remove the pathOfFile argument from checkPath(self, checkPath) because you are not using it. Since we decided a different behaviour for our checkPath() function, we no longer need a while loop: we will be reading the user input each time the event occurs, evaluate the user input, return the user input if we like it or return False if we don't: def checkPath(self): folder = str(self.pathEditLine.text()) if os.path.exists(folder): print '%s is a valid folder' % folder return folder else: print '%s is NOT a valid folder' % folder return False
answers question: http://stackoverflow.com/q/49327154
score: 0
has comment: http://stackoverflow.com/comment/85679226
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85679454
has comment: http://stackoverflow.com/comment/85679247
accepted answer of: http://stackoverflow.com/q/49327154
type: Answer
has comment: http://stackoverflow.com/comment/85679295

http://stackoverflow.com/comment/85786848
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49392606
has text: what is i equal to before you call generate_voltage_plot? how are you defining it?

http://stackoverflow.com/q/49419009
tagged with: python-3.x
has title: Unable to draw to canvas in Tkinter after() loop
has answer: http://stackoverflow.com/a/49419348
tagged with: canvas
has comment: http://stackoverflow.com/comment/85839648
has comment: http://stackoverflow.com/comment/85839597
tagged with: python
linked to: http://stackoverflow.com/q/16424091
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85839584
has body: I'm having a problem that when i try to create an image on the canvas i am unable to produce the image. However before my after() loop is initiated i am able to create and configure my images. Also, i am able to remove objects from my canvas using canvas.delete() in my after() loop so i do still have some level of control. I am on windows 8.1, using Python 3.5.4 import tkinter as tk from PIL import Image, ImageTk from math import floor import numpy as np from scipy import ndimage root = tk.Tk() HEIGHT = 600 WIDTH = 600 CANVAS_MID_X = WIDTH / 2 CANVAS_MID_Y = HEIGHT / 2 def my_mainloop(): #THIS WORKS!!! REMOVES THE DIAL CREATED BEFORE THE MAINLOOP canvas.delete(dial_1) #THIS WORKS BELOW BEFORE MAINLOOP, BUT NOT IT WONT WORK! (use opencv?) img = dial_1_img_resized img2 = img.rotate(45, expand=True) dial_1_photo_new = ImageTk.PhotoImage(img2) dial_2 = canvas.create_image((dial_1_center), image=dial_1_photo_new, anchor=tk.E) '''CANT DRAW TO CANVAS IN AFTER LOOP''' print("loop!") root.after(4000,my_mainloop) '''-------------------Create Canvas, and starting dials in their starting positions---------------------''' canvas = tk.Canvas(root, width=HEIGHT, height=WIDTH, bg="black") canvas.grid(row=0, column=0) dial_1_path = "gauge1.png" dial_1_width = 400 dial_1_img = Image.open(dial_1_path, 'r') #open image dial_1_img_ratio = int(dial_1_img.size[1]) / int(dial_1_img.size[0]) dial_1_img_resized = dial_1_img.resize((dial_1_width, floor(dial_1_img_ratio * dial_1_width)), 1) dial_1_photo = ImageTk.PhotoImage(dial_1_img_resized) dial_1_center = (CANVAS_MID_X, CANVAS_MID_Y) #CREATE DIAL ON CANVAS, THIS WORKS!! dial_1 = canvas.create_image((dial_1_center), image=dial_1_photo) '''Start Main Loop''' root.after(0, my_mainloop) root.mainloop() Therefore my question is: is there a way to manipulate and create canvas images in the after() loop? (called my_mainloop) any help is appreciated!
tagged with: user-interface
tagged with: tkinter-canvas
answer count: 1
accepted answer: http://stackoverflow.com/a/49419348
type: Question

http://stackoverflow.com/q/49321054
has comment: http://stackoverflow.com/comment/85643186
has title: How to can I read ony two tags of this xml if I have 200 files like this in a folder by python
has answer: http://stackoverflow.com/a/49321423
tagged with: python
score: -1
tagged with: dom
tagged with: http://stackoverflow.com/tag/xml
has body: I want to write only and in csv file. <?xml version='1.0' encoding='UTF-8'?> <EmissionSpotMarketECarbixResults> Emission Spot ECarbix 2018-03-14 2018-03-14T20:08:43+01:00 Day EUR/tCO2 11,250 3632000 </EmissionSpotMarketECarbixResults> import os from os import walk from xml.etree import ElementTree import xml.etree.ElementTree as ET for filenames in walk("D:\EEX_EMS\XML"): (filenames) fname= list(filenames) for f in fname[2]: if "EmissionSpotMarketECarbixResults" in f : tree = ET.fromstring(f)
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/49321655
type: UnansweredQuestion
downvote count: 1
favorite count: 0
tagged with: parsing
type: Question

state
tag name: state
tags question: http://stackoverflow.com/q/49352351
type: Tag

http://stackoverflow.com/q/49327478
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85657948
upvote count: 1
tagged with: python
tagged with: get
has title: python BaseHTTPRequestHandler returning json bad string
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/85656936
has comment: http://stackoverflow.com/comment/85657906
downvote count: 0
has body: I have a simple http server like so: from http.server import BaseHTTPRequestHandler, HTTPServer class S(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write(bytes("{\"result\": 200}", "utf-8")) def do_HEAD(self): self._set_headers() def do_POST(self): # Doesn't do anything with posted data self._set_headers() self.wfile.write(bytes("{\"result\": 200}", "utf-8")) def run(server_class=HTTPServer, handler_class=S, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print("Starting http server on port " + str(port)) httpd.serve_forever() if __name__ == "__main__": from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run() When I make a GET request, I expect the json: {result: 200}, but instead I get bad string. What can I do to fix this? I've seen other examples where you can write python objects as json, but not really sure how to put it into this code.
tagged with: http
favorite count: 0
type: Question

http://stackoverflow.com/comment/85614162
type: AnswerComment
comment on: http://stackoverflow.com/a/49305593
has text: This works perfectly. I have accepted your post since it answers the original question. But may I ask, how would this regex look if the section 'number' would be "Section I." or "Section 1." instead of only just digits such as "4.1.2"? Like if the line would look like "Section I. Administrative..........................I-i"
score: 0
type: Comment

http://stackoverflow.com/q/49299033
type: Question
has body: I'm running a script in ipython via the run magic: %run myscript.py and this script imports various modules that I've written, and which I often change between runs. I want to automatically reload these modules, rather than having to restart ipython. There are lots of questions on stackoverflow and elsewhere that recommend %load_ext autoreload %autoreload 2 and maybe also %aimport &lt;your module&gt; thrown in for good measure. But this simply doesn't work. Is a deep reload beyond what autoreload is capable of doing? Is there perhaps some other way of removing all loaded modules, or silently restart the python background process that ipython relies on? EDIT: having played around with this a bit more, it seems that the autoreload failure is a little more subtle. It may be (I'm not 100% certain yet) that autoreload only fails when my module's __init__.py is doing from .&lt;some file in the module&gt; import *, rather than importing each member by name. I have also tried the %reset magic, but this only appears to empty the namespace, it doesn't clear the cached modules. As an aside, Spyder is able to force reloading of modules, but I'm not sure how this is done (some kind of wrapper around ipython which restarts the process?)
answer count: 1
downvote count: 0
has title: how to force ipython deep reload?
upvote count: 7
type: AnsweredQuestion
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/49552654
accepted answer: http://stackoverflow.com/a/49552654
tagged with: ipython
favorite count: 0

http://stackoverflow.com/comment/85675648
type: QuestionComment
has text: Floats are not stored as base-10 decimals. Therefore, a print representation may not match internal representation.
score: 0
comment on: http://stackoverflow.com/q/49336556
type: Comment

http://stackoverflow.com/q/49364731
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/85730175
tagged with: javascript
answer count: 1
has answer: http://stackoverflow.com/a/49365277
favorite count: 0
has body: I'm very new to python and programming in general but have enrolled in a few courses to improve my knowledge. It seems it's quite important to have a 'goal' in mind when learning and one of mine is to successfully scrape and manipulate sports data. I would like to scrape the results from https://www.britishhorseracing.com/racing/results/ but it looks like it's dynamically loading data via JS: There looks to be a LOT of data here, results going back ~20 years plus multiple races for each racecourse on the day. From what I've read, selenium and beautifulsoup may offer some solutions here but before I start experimenting I wanted to check with you guys how realistic this goal is/ whether it's even achivable with how the website is structing the data and some pointers for how to get started? Any help would be hugely appreciated. Thanks
type: Question
accepted answer: http://stackoverflow.com/a/49365277
tagged with: python
has comment: http://stackoverflow.com/comment/85729972
has title: Python Scrape Website loading JS
linked to: http://stackoverflow.com/q/12293158
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49425941
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85853220
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85852739
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85852793
has answer: http://stackoverflow.com/a/49426044
has answer: http://stackoverflow.com/a/49426168
has comment: http://stackoverflow.com/comment/85852789
has body: Let's say a = {1:2, 3:4, 5:6} Is there a builtin function (maybe something like a.get2(7,5)) that will return a[7], or a[5] if a[7] doesn't exist? Such function can be defined easily as a.get(val, a.get(def_key)) but would prefer a builtin solution if exists.
has answer: http://stackoverflow.com/a/49440763
favorite count: 0
has title: Function like dict.get but returns value of default key instead of default value?
type: Question
has comment: http://stackoverflow.com/comment/85852730

http://stackoverflow.com/a/49398277
has comment: http://stackoverflow.com/comment/85798043
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85798018
answers question: http://stackoverflow.com/q/49398218
has body: Yes, there are at least to straightforward approaches. The most straightforward is for the parameter accept a container of objects to skip: def method_runner(self, skipnames): for m in [self.method_a, self.method_b, self.method_c]: if m.__name__ not in skipnames: m() And you would call by passing an appropriate container (in this case a set but a list or tuple might do): SomeClass().method_runner({'method_a', 'method_c'}) But it sounds like you'd rather use variable-length arguments: def method_runner(self, *skipnames): for m in [self.method_a, self.method_b, self.method_c]: if m.__name__ not in skipnames: m(self) Which you could then call like this: SomeClass().method_runner('method_a', 'method_c') However, skipnames will now always be a tuple, which might not have the performance characteristics you require. As recommended by @ChristianDean you may want to make your list of methods a class variable: In [7]: class SomeClass: ...: def method_a(self): ...: print('method_a') ...: ...: def method_b(self): ...: print('method_b') ...: ...: def method_c(self): ...: print('method_c') ...: ...: _my_methods = method_a, method_b, method_c ...: ...: def method_runner(self, skipnames): ...: for m in self._my_methods: ...: if m.__name__ not in skipnames: ...: m(self) ...: In [8]: SomeClass().method_runner({'method_a', 'method_c'}) method_b Just note, you'd have to pass self to the function manually, because it is not a method!
score: 2
has comment: http://stackoverflow.com/comment/85798153
type: Answer
has comment: http://stackoverflow.com/comment/85798142

http://stackoverflow.com/comment/85581189
score: 0
type: Comment
has text: Thanks @piRSquared. Are these codes based on `python2.7` ?
type: AnswerComment
comment on: http://stackoverflow.com/a/49287796

http://stackoverflow.com/a/49395194
upvote count: 2
has body: In O(n), n refers to the length of the input (total characters), not the quantity of words. I suspect you're confused because the code uses a variable n in the latter sense. Note the explanation: "traversing the array ...". "The array" consists of individual characters. The implementation seems a bit silly to me; it's much more readable to: Join letter groups into words. Reverse the word order (including spaces) with a trivial list slice. Expand the words back into characters.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49395162
has comment: http://stackoverflow.com/comment/85792242
downvote count: 0
has comment: http://stackoverflow.com/comment/85792203
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49395162
has comment: http://stackoverflow.com/comment/85792173

single-responsibility-principle
tags question: http://stackoverflow.com/q/49302478
type: Tag
tag name: single-responsibility-principle

ixmldomelement
tag name: ixmldomelement
tags question: http://stackoverflow.com/q/49402888
type: Tag

http://stackoverflow.com/comment/85857906
comment on: http://stackoverflow.com/q/49428212
has text: Seems like you already know the answer then. Are you asking for people's agreement?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85849651
type: Comment
type: AnswerComment
has text: do you also know how to put in that widget a livestream from openCV instead of a video file.
score: 0
comment on: http://stackoverflow.com/a/49423852

http://stackoverflow.com/q/49387425
has body: I need to generate 5000 random values from 0 to 1 and for each find closest greater value of "sum" column and put this row in my new dataframe. my old dataframe: Probability sum 0.008773 0.008773 0.008715 0.017488 0.007244 0.024732 0.006997 0.031730 So it will be new dataframe with 5000 rows from old one.
has title: Pandas dataframe: find closest greater value in a row
type: AnsweredQuestion
upvote count: 0
downvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85776920
type: Question
has comment: http://stackoverflow.com/comment/85776282
has answer: http://stackoverflow.com/a/49388373
accepted answer: http://stackoverflow.com/a/49388373
has comment: http://stackoverflow.com/comment/85776485
score: -2
tagged with: python

http://stackoverflow.com/comment/85788740
comment on: http://stackoverflow.com/a/49393361
has text: Your code works fine with `GTK3Cairo` and `Qt5Agg`. MaxU's original code worked fine for me (using matplotlib v2.2.0) with `GTK3Cairo` but with backend `Qt5Agg` the xlabels do not update.
type: Comment
type: AnswerComment
score: 1

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/49315547
tags question: http://stackoverflow.com/q/49317852
type: Tag
tags question: http://stackoverflow.com/q/49365883
tags question: http://stackoverflow.com/q/49369575

http://stackoverflow.com/comment/85685192
type: QuestionComment
has text: Yeah, i'm guilty of not reading your question completely (assumed less knowledge). But yeah: SGD, SAG, and all those are not very robust and convergence is sensitive to parameters. This also applies to GD without line-search. This is experienced all the time (and of course the nature of the data matters).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49342218

http://stackoverflow.com/a/49442035
has body: I am the author of the question... The problem was a permissions issue, as I mentioned earlier, I did modify the system and could not remember what I had done to prevent Jupyter Notebook from working as before. I spent the better part of three days researching the problem and could not find an answer, in frustration, today I posted the problem. And with the comments and suggestion from a couple of the users I was able to take a better look at the problem and try a few different approaches. I had enabled a feature in "Windows Defender Security Center" that prevented Jupyter from working as before, preventing me from running Notebooks in different locations, more specifically the "Documents" folder. Should this happen to you: Go to "Windows Defender Security Center" Scroll &amp; Click on "Virus &amp; threat protection settings" Scroll down to "Controlled folder access" Make sure is Disabled This was the "global" solution I was looking for That should fix a similar problem ~ eb
has comment: http://stackoverflow.com/comment/97870888
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49436155
has comment: http://stackoverflow.com/comment/85918959
type: Answer
answers question: http://stackoverflow.com/q/49436155
has comment: http://stackoverflow.com/comment/111784299
has comment: http://stackoverflow.com/comment/97939622
type: AcceptedAnswer
score: 16
upvote count: 16
has comment: http://stackoverflow.com/comment/121348638

http://stackoverflow.com/q/49366431
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85734514
has title: How to get latest subdirectory created in project folder
tagged with: python
has answer: http://stackoverflow.com/a/49367874
has comment: http://stackoverflow.com/comment/85734363
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49368871
has body: I am trying to get the last modified directory of a folder in the project directory. With the code below, I can get the last modified directory only for the scripts saved in the directory, but I want to get the last modified subdir of a folder, which is in project directory. And I only want to fetch the folder name, not the whole path, because I will increment the folder name +1 and create new one when the file limit is reached for the mentioned folder. And my code is: import os import glob all_subdirs = [d for d in os.listdir('/root/visual- studio/testfolder/testsubdir/') if os.path.isdir(d)] latest_subdir = max(all_subdirs, key=os.path.getmtime) print(latest_subdir) The script is saved to testfolder and when I run the script it only gives testfolders last modified directory. But I want to get the testsubdirs latest directory. When I run the script below for testsubdirs I get this error: Traceback (most recent call last): File "/root/visual-studio/testfolder/test.py", line 40, in &lt;module&gt; latest_subdir = max(all_subdirs, key=os.path.getmtime) ValueError: max() arg is an empty sequence
has answer: http://stackoverflow.com/a/49368871
has comment: http://stackoverflow.com/comment/85734304
accepted answer: http://stackoverflow.com/a/49367874
type: Question

http://stackoverflow.com/comment/105337387
comment on: http://stackoverflow.com/a/49405175
type: Comment
score: 2
has text: Why is only `X1i[1]` being returned by the generator but not `X2i[1]` and `Xi2[1]`?
type: AnswerComment

http://stackoverflow.com/comment/85690658
comment on: http://stackoverflow.com/q/49345360
type: Comment
type: QuestionComment
has text: When you `sudo`, it doesn't use your current environment, it uses a stripped-down environment defined in your `/etc/sudoers`, which usually does not include your `PATH`. There are additional details depending on your specific platform.
score: 1

http://stackoverflow.com/comment/85786159
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49392157
has text: This works perfectly. Something I failed to mention was tie breakers when two rows contain the same number of NULLs. How would you drop one of them?

http://stackoverflow.com/comment/85873019
has text: @ahey I've added an example using `imp` on Python 2.7, check it out.
score: 1
comment on: http://stackoverflow.com/a/49434295
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85684036
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49341905
type: QuestionComment
has text: Yes, I've been reading the source code. Not familiar with the Python landscape so I can't tell if just curl requests are being made or some tool is being used for headless browser automation

http://stackoverflow.com/comment/85879339
type: Comment
type: QuestionComment
has text: @martineau Let's be honest, as it stands, this question is extremely unclear
comment on: http://stackoverflow.com/q/49435728
score: 0

http://stackoverflow.com/q/49331108
score: 0
possible better answer: http://stackoverflow.com/a/49331147
answer count: 3
has comment: http://stackoverflow.com/comment/85664657
has answer: http://stackoverflow.com/a/49331147
tagged with: selenium
has title: Extracting text using selenium
has body: Below is an excerpt of the html code: Category1 "Text1 I want" Category2 "Text2 I want" I know I can extract Text1 and Text2 by using: find_element = browser.find_elements_by_xpath("//div[@class='Class2']") element = [x.text for x in find_element] text1 = element[0] text2 = element[1] But if the structure of the html is changed, elements will be changed accordingly. Is there any way for me to extract Text1 and Text2 by referring to Category1 and Category2, respectively? Thank you.
type: Question
accepted answer: http://stackoverflow.com/a/49331453
tagged with: python
has answer: http://stackoverflow.com/a/49331453
has answer: http://stackoverflow.com/a/49342178
has comment: http://stackoverflow.com/comment/85664564
type: AnsweredQuestion

http://stackoverflow.com/q/49364186
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
downvote count: 0
has body: On this page I would like Selenium for Python to grab the text contents of the "Investment Objective", excluding the header. I want to use XPath. The nodes look like this: INVESTMENT OBJECTIVE The Fund seeks to track the performance of an index composed of 25 of the largest Dutch companies listed on NYSE Euronext Amsterdam. To retrieve the text, I'm using: string = driver.find_element_by_xpath(xpath).text If use I the this XPath for the top node: xpath = '//div[@class="carousel-content column fund-objective"]' It will work, but it includes the header INVESTMENT OBJECTIVE — which I want to exclude. However, if I try to use /text() to address the actual text content, it seems that Selenium for Python doesn't let me grab it whilst using the .text to get the attribute: xpath = '//div[@class="carousel-content column fund-objective"]/text()' Note that there seems to be multiple nodes with this XPath on this particular page, so I'm specifying the correct node like this: xpath = '(//div[@class="carousel-content column fund-objective"]/text())[2]' My interpretation of the problem is that .text doesn't allow me to retrieve the text contents of the XPath sub-node text(). My apologies for incorrect terminology.
tagged with: selenium
has answer: http://stackoverflow.com/a/49364624
has answer: http://stackoverflow.com/a/49364353
favorite count: 0
type: Question
has title: Selenium for Python: Get text() of node that is shared with another element, via XPath
linked to: http://stackoverflow.com/q/15920496
tagged with: python
has answer: http://stackoverflow.com/a/49364437
possible better answer: http://stackoverflow.com/a/49364437
accepted answer: http://stackoverflow.com/a/49364624
score: 2
tagged with: xpath
upvote count: 2

http://stackoverflow.com/a/50772141
score: 7
has comment: http://stackoverflow.com/comment/96467829
downvote count: 1
upvote count: 8
answers question: http://stackoverflow.com/q/49373535
type: Answer
has body: You could just try: conda install -c conda-forge tabula-py It works fine for me.

http://stackoverflow.com/q/49357413
tagged with: split
has answer: http://stackoverflow.com/a/49357486
accepted answer: http://stackoverflow.com/a/49357486
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: numbers
score: 0
answer count: 1
tagged with: string
has title: How to split a number into sign, integer and fractional?
type: Question
has body: sorry if my formatting is a bit weird. I am not quite used to formatting code on this site. I'm given a decimal number in a string format. I want to be able to split this number up into its sign, integer part and the fractional part. Example: INPUT: -1223.231 OUTPUT: sign: - integer: 12 fraction: 231 My code below works for only fractional negative or positive numbers. I run into indexing errors when I try to use my code on a whole number such as 1234 or -1234. I believe the issue is when I try to split on a whole number I can't. To clarify I would like the output of a whole number to look like this: INPUT: 1234 OUTPUT: sign: + integer: 1234 fraction: 0 Any help on how I could make my code also split up whole numbers? Thanks in advance. decimal_string = '-1223.231' if(decimal_string[0]=="-"): sign="-" splitValue = decimal_string.split('.') print("sign: " + sign + " integer: " + splitValue[0][1:] +" fraction: " + splitValue[1]) elif(decimal_string=="0"): print("sign: + integer: " + decimal_string[0:] + " fraction: 0") else: sign="+" splitValue = decimal_string.split('.') int_part = int(splitValue[0]) decimal_part = int(splitValue[1]) print("sign: " + sign + " integer: " + splitValue[0] +" fraction: " + splitValue[1])

http://stackoverflow.com/comment/85636465
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49316872
has text: run your code, it works fine: $ python3 pyqtqkeyevent.py QWidget::setLayout: Attempting to set QLayout "" on SurfViewer "", which already has a layout Right click Left click A pressed

http://stackoverflow.com/a/55688380
downvote count: 0
answers question: http://stackoverflow.com/q/49314270
upvote count: 2
type: Answer
score: 2
has body: here's an append example: table = dbf.Table('sample.dbf', 'cod N(1,0); name C(30)') table.open(mode=dbf.READ_WRITE) row_tuple = (1, 'Name') table.append(row_tuple)

http://stackoverflow.com/q/49282888
favorite count: 0
has title: For loop in C breaks early for no obvious reason - possibly related to a function pointer (call back)
type: Question
has comment: http://stackoverflow.com/comment/85569954
has comment: http://stackoverflow.com/comment/85568892
score: 1
has comment: http://stackoverflow.com/comment/85569234
tagged with: python
has comment: http://stackoverflow.com/comment/85568516
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/85569596
has comment: http://stackoverflow.com/comment/85568557
has comment: http://stackoverflow.com/comment/85569286
has comment: http://stackoverflow.com/comment/85583739
has comment: http://stackoverflow.com/comment/85568811
has comment: http://stackoverflow.com/comment/85573934
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85568737
tagged with: ctypes
has comment: http://stackoverflow.com/comment/85568768
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/49285676
has comment: http://stackoverflow.com/comment/85568663
has answer: http://stackoverflow.com/a/49285676
has comment: http://stackoverflow.com/comment/85569124
answer count: 1
downvote count: 0
has body: I am experimenting with a DLL written in C and callback functions written in Python. My DLL contains the following definition and routine: typedef int16_t (*conveyor_belt)(int16_t index); int16_t __stdcall DEMODLL sum_elements_from_callback( int16_t len, conveyor_belt get_data ) { int16_t sum = 0; int i; for(i = 0; i &lt; len; i++) { sum += get_data(i); } return sum; } I call the above from a Python script using ctypes: import ctypes DATA = [1, 6, 8, 4, 9, 7, 4, 2, 5, 2] conveyor_belt = ctypes.WINFUNCTYPE(ctypes.c_int16, ctypes.c_int16) @conveyor_belt def get_data(index): print((index, DATA[index])) return DATA[index] dll = ctypes.windll.LoadLibrary('demo_dll.dll') sum_elements_from_callback = dll.sum_elements_from_callback sum_elements_from_callback.argtypes = (ctypes.c_int16, conveyor_belt) sum_elements_from_callback.restype = ctypes.c_int16 test_sum = sum_elements_from_callback(len(DATA), get_data) print(('sum', 48, test_sum)) The output I get looks like this (most of the time): (0, 1) (1, 6) (2, 8) (3, 4) (4, 9) (5, 7) (6, 4) (7, 2) ('sum', 48, 41) From what I can tell, the for loop just does not iterate over all 10 elements of DATA as I would expect it to do ... It usually "breaks" after 8 elements, sometimes even only after 5 or 6. I can confirm that the length of DATA is correctly passed into the DLL routine. I am puzzled. Just in case this is a compiler (flag) issue, here is an excerpt from my makefile: CC = i686-w64-mingw32-gcc CFLAGS = -Wall -Wl,-add-stdcall-alias -shared -std=c99 LDFLAGS = -lm I am working with mingw (32 bit) on top of 64 bit Linux: user@box:~&gt; i686-w64-mingw32-gcc --version i686-w64-mingw32-gcc (GCC) 7.2.0 user@box:~&gt; uname -s -r -p Linux 4.4.114-42-default x86_64 For running the DLL and the Python script, I am using an official 32 bit release build of CPython 3.5.3 for Windows on top of 32 bit Wine: user@box:~&gt; wine --version wine-2.18 It's a robust combination which I have been using intensively for a while now. Using the call…
has comment: http://stackoverflow.com/comment/85571370
upvote count: 1
has comment: http://stackoverflow.com/comment/85568687
tagged with: callback
has comment: http://stackoverflow.com/comment/85573758

http://stackoverflow.com/a/50343238
has body: I'm going to say the easiest way would be to mock out Neo4j entirely. What I like to do is to simplify your entity classes to as little pure-python functionality as possible. Even if you're using some fancy ORM to access your data - for example in Django - I still prefer to create a pure-python class to represent my model and create a minimalistic dao method, which will be mocked-out during unit tests. That way I don't have to ever touch the database in my unit tests, which I think is how unit tests should behave. That being said, if you really want to have neo4j functionality in your tests, have a look at the IntegrationTestCase of the official neo4j-python-driver package. It looks like it is providing a base class to inherit your integration tests (because if you're pulling the DB into your tests, you're essentially doing Integration Tests) from, as it takes care of starting up and shutting down the server between test runs.
type: Answer
score: 6
downvote count: 1
has comment: http://stackoverflow.com/comment/125248880
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49348839
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49348839
has comment: http://stackoverflow.com/comment/125201697

http://stackoverflow.com/q/49380965
answer count: 2
tagged with: subprocess
upvote count: 2
linked to: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/85762631
has comment: http://stackoverflow.com/comment/85763129
accepted answer: http://stackoverflow.com/a/49380988
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49380988
possible better answer: http://stackoverflow.com/a/49381087
has title: Python script error :Unable to read csv file
has body: Im Trying to Process below tab csv file line by line .It raising error.Unable to trace where im wrong. Here is the file : /tmp/fa.csv 1 Close 6 Close 72 Close 99 Close 8 Close 4 Close 3 Close 103 Close 106 Close 107 Close 105 Close 220 Open 9.py import csv with open('/tmp/fa.csv') as f: rown = csv.reader(f,delimiter='\t') for row in rown: print row[1] Output: [root@localhost ~]# python 9.py File "9.py", line 3 rown = csv.reader(f,delimiter='\t') ^ IndentationError: expected an indented block
has answer: http://stackoverflow.com/a/49381087
downvote count: 3
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85762614
type: Question

acl
tag name: acl
type: Tag
tags question: http://stackoverflow.com/q/49430670

http://stackoverflow.com/q/49332545
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49333232
tagged with: discord.py
has answer: http://stackoverflow.com/a/49333232
has title: Absolutely baffling issue with Discord.py bot
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/13091357
has body: I'm at my wits end trying to debug and solve this error. Basically, I have a variable (maxID) that thinks its not initialized when it very clearly is both before and after checking. It only seems to do this in my add method, as it is just fine in all the other methods I've tried (I've left a debug print in my code that I can confirm DOES work in the ping method that proves that maxID has been initialized). Relevant code below: import discord import asyncio from discord.ext import commands class Quote: def __init__(self, id, msg): self.id = id self.msg = msg bot = commands.Bot(command_prefix = '-') q = open("maxID.txt","r") maxID = int(q.read()) q.close() print(maxID) temp = [0 for x in range(len(quotes))] for i in range(0, len(quotes)): temp[i] = Quote(ids[i],quotes[i]) quotes = temp @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') @bot.event async def on_message(message): await bot.process_commands(message) @bot.command(pass_context=True) async def ping(ctx): await ctx.channel.send('Pong!') print(maxID) @bot.command(pass_context=True) async def add(ctx, *, arg): quotes.append(Quote(maxID, arg)) maxID = maxID + 1 await ctx.channel.send('Added Quote #' + str(len(quotes))) Side note: Any time at all that maxID is mentioned in the above quote, outside of add, I can confirm works just fine with no issues that I can see. The exact error I get from the add method: Ignoring exception in command add: Traceback (most recent call last): File "C:\Users\Acemcbean\AppData\Roaming\Python\Python36\site-packages\discord\ext\commands\core.py", line 62, in wrapped ret = yield from coro(*args, **kwargs) File "C:\IzunaBot\run.py", line 51, in add quotes.append(Quote(maxID, arg)) UnboundLocalError: local variable 'maxID' referenced before assignment
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12382472
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/49353288
tagged with: kivy
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: textinput
has body: Using Kivy 1.10.0 with Python 2.7.9 I am trying to get the TextInput value entered by user when Button (my_button2) is clicked .And although I have been able to get this working with GridLayout it seems like the method I am using is not working with ScreenManager with BoxLayout . Error received is : AttributeError: 'ScreenTwo' object has no attribute 'inpt' when my_button2 After clicking 'Next Screen ' button , it takes me to page where user enters text value , and 'print' button should print it Please see below : import kivy from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.textinput import TextInput class ScreenOne(Screen): def __init__ (self,**kwargs): super (ScreenOne, self).__init__(**kwargs) my_box1 = BoxLayout(orientation='vertical') my_button1 = Button(text="Next Screen ",size_hint_y=None,size_y=100) my_button1.bind(on_press=self.changer) my_box1.add_widget(my_button1) self.add_widget(my_box1) def changer(self,*args): self.manager.current = 'screen2' class ScreenTwo(Screen): def __init__(self,**kwargs): super (ScreenTwo,self).__init__(**kwargs) layout = BoxLayout(orientation='vertical') self.add_widget(layout) inpt = TextInput(text="Some text ",size_y=50) layout.add_widget(inpt) my_button2 = Button(text="Print ") my_button2.bind(on_press=self.click) layout.add_widget(my_button2) Home_btn = Button(text="Back") Home_btn.bind(on_press=self.home) layout.add_widget(Home_btn) def click(self,my_button2): entered_value = self.inpt.text print entered_value def home(self,*args): self.manager.current = 'screen1' class TestApp(App): def build(self): my_screenmanager = ScreenManager() screen1 = ScreenOne(name='screen1') screen2 = ScreenTwo(name='screen2') my_screenmanager.add_widget(screen1) my_screenmanager.add_widget(screen2) return my_screenmanager if __name__ == '__main__': TestApp().run() second screen
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49353375
has answer: http://stackoverflow.com/a/49353375
has title: Getting TextInput value with ScreenManager in Kivy 1.10 and Python 2.7.9
tagged with: python

http://stackoverflow.com/a/49359453
has body: Using dict.setdefault to create dictionary with lists as values will make your job easier. d = {} with open('input.txt') as f: key = '' for row in f: if row.startswith(' '): d.setdefault(key, []).append(row.strip()) else: key = row print(d) Output: {'Time\n': ['NtGetTickCount', 'NtQueryPerformanceCounter', 'NtQuerySystemTime', 'NtQueryTimerResolution', 'NtSetSystemTime', 'NtSetTimerResolution', 'RtlTimeFieldsToTime', 'RtlTimeToTime'], 'System informations\n': ['NtQuerySystemInformation', 'NtSetSystemInformation', 'Enumerations', 'Structures']} A few things to note here: Always use with open(...) for file operations. If you want to check the first index, or the first few indices, use str.startswith() The same can be done using collections.defaultdict: from collections import defaultdict d = defaultdict(list) with open('input.txt') as f: key = '' for row in f: if row.startswith(' '): d[key].append(row) else: key = row
has comment: http://stackoverflow.com/comment/85719022
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49359186

http://stackoverflow.com/a/49695873
has body: Run &gt; Add Configuration... =&gt; Choose one of the two options. After doing this it will no longer prompt you.
has comment: http://stackoverflow.com/comment/109510143
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49312540
has comment: http://stackoverflow.com/comment/111089013
score: 55
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/109509615
upvote count: 56
accepted answer of: http://stackoverflow.com/q/49312540

http://stackoverflow.com/q/49319841
score: 1
has title: Where is imsave in scipy 1.0.0?
downvote count: 0
answer count: 1
upvote count: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/49319874
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49319874
has body: The function imsave() does not exist in scipy.misc package in scipy 1.0.0 (Python 3.5). Where is it? I am trying out a sample program using keras which in terms uses scipy.misc.save(). Tried searching for the alternate location all over the place, including the index of its reference manual but still can't find it. Is there a different package that one must install to circumvent this problem?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85773801
comment on: http://stackoverflow.com/q/49386412
score: 0
has text: Please edit your question and add the exception that you get. Also the code that you posted doesn't work, you forgot the ``def`` in the first class
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85646000
score: 0
comment on: http://stackoverflow.com/q/49321095
type: Comment
has text: @Mike-SMT: the statement _"If you run multiple Tk() instances you will not be able to pass data between them"_ is a bit too broad. You can definitely pass some data between them, it's just that they can't share references to the same tkinter variables and widgets.
type: QuestionComment

http://stackoverflow.com/q/49390029
has title: pandas group by function applied to a column
has answer: http://stackoverflow.com/a/49390113
tagged with: python
has body: In the Groupby documentation, I only see examples of grouping by functions applied to the index of axis 0 or to the labels of the columns. I see no examples discussing how to group by a label derived from applying a function to a column. I would think this would be done using apply. Is the example below the best way to do this? df = pd.DataFrame({'name' : np.random.choice(['a','b','c','d','e'], 20), 'num1': np.random.randint(low = 30, high=100, size=20), 'num2': np.random.randint(low = -3, high=9, size=20)}) df.head() name num1 num2 0 d 34 7 1 b 49 6 2 a 51 -1 3 d 79 8 4 e 72 5 def num1_greater_than_60(number_num1): if number_num1 &gt;= 60: return 'greater' else: return 'less' df.groupby(df['num1'].apply(num1_greater_than_60))
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49390329
type: UnansweredQuestion
score: 7
downvote count: 0
has answer: http://stackoverflow.com/a/49390165
upvote count: 7
favorite count: 0
type: Question
tagged with: group-by

http://stackoverflow.com/comment/85897962
has text: @Rakesh If I have a dynamic word, how should I write the regex? re.sub(r"\b+"word"+"\b", 'Paul_1', data) or re.sub(r"\b+"word"+"r\b", 'Paul_1', data)?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49391031
type: Comment

http://stackoverflow.com/comment/85679052
has text: This is just an example if the string variable can be used as a list or not, now on how to use it ,the scope(if throughout the code), that remains for the user to improvise on ,this is just a hardcoded version
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49339378
type: AnswerComment

http://stackoverflow.com/q/49310458
tagged with: python
linked to: http://stackoverflow.com/q/38134012
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/29357379
duplicate of: http://stackoverflow.com/q/38134012
favorite count: 0
type: Question
has title: replace column values in my pandas by values of another pandas if the values is nan
has answer: http://stackoverflow.com/a/49310482
has comment: http://stackoverflow.com/comment/85622955
has body: I have two pandas, the first one has 2000 rows looks like: key B C D key1 11 nan nan key2 nan 33 88 key3 nan 44 99 key4 22 55 nan and the second has about 700 values key B C D key4 22 55 77 key2 55 42 63 key3 53 23 nan I wanna iterate my first data frame by keys and replace the nan values by the matching values if exist in the second pandas like this key B C D key1 11 nan nan key2 55 33 88 key3 53 44 99 key4 22 55 77 my two data frames contain strings I used numbers just for the sake of examples
type: UnansweredQuestion

http://stackoverflow.com/a/49280310
answers question: http://stackoverflow.com/q/49279950
has comment: http://stackoverflow.com/comment/85563375
has body: The issue has to do with python rounding the float for the string representation. Here's some sample code showing the issue: &gt;&gt;&gt; b = 5.78888888888888888888888888888 &gt;&gt;&gt; print("{0:.3f}".format(b)) 5.789 &gt;&gt;&gt; print(b) 5.78888888889 &gt;&gt;&gt; print("{0:.18f}".format(b)) 5.788888888888888751 &gt;&gt;&gt; print("{0:.24f}".format(b)) 5.788888888888888750727801 The later issues with accuracy have to do with the accuracy of binary floating points, but you can at least see how to change the length of the display. For your particular issue, you can try something along these lines: myList = ','.join(map(lambda x: "{0:.8f}".format(x), myList))
score: 0
has comment: http://stackoverflow.com/comment/85564502
type: Answer
has comment: http://stackoverflow.com/comment/85599372

http://stackoverflow.com/q/49428431
score: 0
has comment: http://stackoverflow.com/comment/85860497
has comment: http://stackoverflow.com/comment/85860000
has comment: http://stackoverflow.com/comment/85861989
linked to: http://stackoverflow.com/q/47426410
has comment: http://stackoverflow.com/comment/85864439
tagged with: multiprocessing
type: Question
has title: multiprocessing batches suddenly halts in python
has answer: http://stackoverflow.com/a/49431643
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85859473
has body: I am using gensim word2vec to return the most similar text from a corpus matching the query text. For instance, here are some relevant lines of code that start things off: model = gensim.models.KeyedVectors.load_word2vec_format('/users/myuser/method_approaches/google_news_requirements/GoogleNews-vectors-negative300.bin.gz', binary=True) instance = WmdSimilarity(processed_set, model, num_best=10) And then I have this very simple function which runs the instance when passed to the multiprocessor: def get_most_similar_for_a_given_text(instance,text,output): i=instance[text] output.put(i) And then I have a batch multiprocessing script def get_most_similar_for_all_texts_in_set(processed_set, instance): output = mp.Queue() # Setup a list of processes that we want to run processes = [mp.Process(target=get_most_similar_for_a_given_text, args=(instance, text, output)) for text in processed_set] num_cores = mp.cpu_count() Scaling_factor_batch_jobs = 3 number_of_jobs = len(processes) num_jobs_per_batch = num_cores * Scaling_factor_batch_jobs num_of_batches = int(number_of_jobs // num_jobs_per_batch)+1 print('\n'+'Running batches now...') for i in tqdm.tqdm(range(num_of_batches)): # although the floor/ceilings look like things are getting double counted, for instance with ranges being 0:24,24:48,48.. etc.. this is not the case, for whatever reason it doesn't work like that if i&lt;num_of_batches-1: # true for all but last one floor_job = int(i * num_jobs_per_batch) # int because otherwise it's a float and mp doesn't like that ceil_job = int(floor_job + num_jobs_per_batch) # Run processes for p in processes[floor_job : ceil_job]: p.start() for p in processes[floor_job : ceil_job]: p.join() for p in mp.active_children(): p.terminate() print(floor_job,ceil_job) else: # true on last job, which picks up the missing batches that were lost due to rounding in the num_of_batches/num_jobs_per_batch formulas floor_job = int(i * num_jobs_per_batch) # Run processes for p in processes[floor_…
tagged with: word2vec
tagged with: python
has comment: http://stackoverflow.com/comment/85866799
answer count: 1
linked to: http://stackoverflow.com/q/11996632

lstm
tags question: http://stackoverflow.com/q/49299761
tags question: http://stackoverflow.com/q/49288651
tags question: http://stackoverflow.com/q/49407713
tags question: http://stackoverflow.com/q/49362931
tags question: http://stackoverflow.com/q/49282948
tags question: http://stackoverflow.com/q/49328326
tags question: http://stackoverflow.com/q/49411333
tags question: http://stackoverflow.com/q/49368318
tags question: http://stackoverflow.com/q/49360786
tags question: http://stackoverflow.com/q/49283435
tags question: http://stackoverflow.com/q/49377809
type: Tag
tags question: http://stackoverflow.com/q/49342925
tags question: http://stackoverflow.com/q/49432175
tag name: lstm

http://stackoverflow.com/comment/85781267
type: Comment
type: QuestionComment
has text: Thanks for the input, everyone.
comment on: http://stackoverflow.com/q/49326213
score: 0

http://stackoverflow.com/q/49358904
has body: Odoo service is started by systemctl start odoo. I am usin Centos. When I want to update my changed *.py code I used to do like this: 1. systemctl stop odoo Then I update my module and database by useing this: 2. ./odoo.py -c openerp-server.conf -u &lt;my_module_name&gt; -d &lt;database_name&gt; 3. stop service by ctrl + c 4. systemctl start odoo But it's realy long and uncomfortable way to update changes. Is there a shorter way to do the same operations in shorter way?
possible better answer: http://stackoverflow.com/a/68029502
type: Question
has answer: http://stackoverflow.com/a/68029502
has title: Odoo service restart and update using systemctl
tagged with: odoo
accepted answer: http://stackoverflow.com/a/49360465
tagged with: odoo-9
tagged with: start-stop-daemon
tagged with: python
linked to: http://stackoverflow.com/q/29225994
tagged with: systemctl
favorite count: 0
upvote count: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/49360465

http://stackoverflow.com/comment/85681974
type: QuestionComment
comment on: http://stackoverflow.com/q/49340169
has text: `x` is an array, a view of `arr`, and has to be modified in-place to affect the value in `arr`.
score: 1
type: Comment

http://stackoverflow.com/a/49343073
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85686574
answers question: http://stackoverflow.com/q/49342680
has comment: http://stackoverflow.com/comment/85686561
type: Answer
has body: If you really do want to edit the source of script2, you can do that—via normal string methods, or regex, or, better, tokenizing or parsing the file. But really, you almost certainly don't want to do that. If you want some kind of persistent storage across runs of your program, you probably want a separate file. For fancy cases, you may want to use a database like dbm or sqlite3, but here, you just have a list of names, so you can probably store them one per line in a simple text file. There are two tricky bits, but both are pretty easy: If you've never run script1, there won't be a file yet. So you'll want to handle that case. You need to make sure to write newlines ('\n') after each name, and then strip them back off on the other end. script1.py: name = input('\n Please enter your name:') with open('names.txt', 'w') as f: f.write(name + '\n') script2.py: try: with open('names.txt') as f: names = [line.rstrip() for line in f] except FileNotFoundError: names = [] If you wanted to have a "starting list" of names that worked even before ever calling script1, you'd add a names = ['Name1', 'Name2'] line about theopen, and the change thenames = […]tonames.extend(…)`. But it sounds like you don't want that, so I've made it start with an empty list—the only names are the ones you added to the text file. One more thing: This look for names.txt in the current working directory. So if you run your script from some other directory, it won't find the file. If you want to find it in a specific location instead, like /Users/Pergamon256/.config/my-app/names.txt, that's pretty easy. If you want "wherever is the normal place for my operating system", that's a bit trickier; there are libraries on PyPI that do it for you. If you want the same directory that the scripts are in, there are good answers on SO showing how to do that.
accepted answer of: http://stackoverflow.com/q/49342680
score: 0
has comment: http://stackoverflow.com/comment/85686545

http://stackoverflow.com/comment/85738355
has text: @JonClements Thank you. That was it. Still trying to figure out how to generate multiple `dataframe`'s though.
score: 0
comment on: http://stackoverflow.com/q/49366437
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49289794
downvote count: 0
has comment: http://stackoverflow.com/comment/85600738
answers question: http://stackoverflow.com/q/49289685
type: Answer
has comment: http://stackoverflow.com/comment/85582858
accepted answer of: http://stackoverflow.com/q/49289685
has body: Mathemagic by @Tim. consts = [340.3, 334.4, 328.4, 322.2, 316.0, 309.6, 303.6, 295.4, 295.5] def soundbarrier(y): return consts[ -1 if (not (0 &lt; y &lt; 12192) or y % 1524 == 0) else y // 1524 ] In [1]: soundbarrier(1500) Out[1]: 340.3 In [2]: soundbarrier(10000) Out[2]: 303.6 In [3]: soundbarrier(100) Out[3]: 340.3 In [4]: soundbarrier(1524) Out[4]: 295.5
has comment: http://stackoverflow.com/comment/85582853
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85719515
type: Comment
has text: that a typo here,it doesn't help in the main code.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49359687

http://stackoverflow.com/q/49368516
type: Question
tagged with: numpy
tagged with: opencv
duplicate of: http://stackoverflow.com/q/33859531
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85750714
has title: Problems with installing Numpy in Python 2.7.5
tagged with: python
has comment: http://stackoverflow.com/comment/85768100
score: 0
has body: I need to install the OpenCV library for Pyhton in a Windows 8.1 machine and when I run the line import cv2 (cv2 is a file from the OpenCV library which requires Numpy to be already installed) in Idle I get the error: **RuntimeError: module compiled against API version 0xa but this version of numpy is 0x7** I've already istalled the version 9 and the error returned, but I'm not findind an .exe file for the latest version of Numpy which seems to be 1.14 Any help?
answer count: 0
has comment: http://stackoverflow.com/comment/85767107
has comment: http://stackoverflow.com/comment/85739182
linked to: http://stackoverflow.com/q/33859531
has comment: http://stackoverflow.com/comment/85737937

http://stackoverflow.com/a/49359797
upvote count: 6
type: AcceptedAnswer
downvote count: 0
has body: You use lxml parser, which is HTML parser. To parse XML you should use xml parser: from bs4 import BeautifulSoup soup = BeautifulSoup(' ', 'xml') print(soup) # ^^^^^^ From BeautifulSoup documentation: Beautiful Soup presents the same interface to a number of different parsers, but each parser is different. Different parsers will create different parse trees from the same document. The biggest differences are between the HTML parsers and the XML parsers. Here’s a short document, parsed as HTML: BeautifulSoup("<b />") # Since an empty tag is not valid HTML, the parser turns it into a tag pair. Here’s the same document parsed as XML (running this requires that you have lxml installed). Note that the empty tag is left alone, and that the document is given an XML declaration instead of being put into an tag.: BeautifulSoup("<b />", "xml") # <?xml version="1.0" encoding="utf-8"?> # Source: Differences between parsers, emphasis mine.
answers question: http://stackoverflow.com/q/49359684
accepted answer of: http://stackoverflow.com/q/49359684
type: Answer
score: 6

http://stackoverflow.com/comment/85824066
type: AnswerComment
has text: NameError Traceback (most recent call last) <ipython-input-1-55d82acf567e> in <module>() 1 from pandas import read_csv 2 ----> 3 filename = pd.read_csv('C:/Users/asus/Desktop/memoire/sequences-code.csv') 4 data = pd.read_csv(filename, sep=';', header=None) NameError: name 'pd' is not defined
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49410882

http://stackoverflow.com/comment/85581222
type: Comment
has text: @jpp: OP's code works fine for me in Python 3.4.5
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49288923

http://stackoverflow.com/a/49548156
answers question: http://stackoverflow.com/q/49325401
type: Answer
has body: While your app is running Bad Things can happen, which we'd like to recover from. One example is Power Fail. There is no computing technique for arranging for instructions to execute on a device that is powered off. So we may need to reset some state upon restart. Your app already has this requirement; I'm just making it explicit. It is hard to reliably gain control just after each of the various Bad Things that might happen, as you found when you carefully considered several standard techniques. You weren't specific about the sort of items needing cleanup that you envision, but we could consider these cases: transient - TCP connections, flock, etc. permanent - disk files, side effects on distant hosts Rather than invoking your app directly, arrange for it to be run by a Nanny process which forks the app as a child. At some point the app will exit, the Nanny will regain control with all transient items having been tidied up by the OS, and then the Nanny can do any necessary cleanup on permanent items prior to an app restart. This is identical to the cleanup the Nanny will need to do on initial startup, for example after power fail events. The advantage of running your app under a parent process is that the parent can perform immediate cleanups after simple app failures such as SEGV. Cleaning up permanent items likely involves timeouts on timestamped resources. If your system is able to reboot within say 2 seconds of a brief power outage, you may find it necessary to deliberately stay Down (sleep) for long enough to ensure that distant hosts have reliably detected your transition to Down, prior to announcing a transition to Up. Techniques like Virtual Synchrony and Paxos can help you drive toward rapid convergence. summary Sometimes an app will unexpectedly die before running cleanup code. Take a belt-and-suspenders approach: put essential cleanup code in the (simpler, more reliable) parent process.
score: 0

http://stackoverflow.com/comment/85758849
comment on: http://stackoverflow.com/q/49379168
type: QuestionComment
has text: Welcome to StackOverflow! Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to try to solve your own problem first. Please update your question to show what you have already tried, showing the specific problem you are facing in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). For further information, please see [how to ask good questions](http://stackoverflow.com/help/how-to-ask), and take the [tour of the site](http://stackoverflow.com/tour).
type: Comment
score: 2

qemu
tag name: qemu
tags question: http://stackoverflow.com/q/49403677
type: Tag

http://stackoverflow.com/comment/85755126
comment on: http://stackoverflow.com/a/49359851
score: 0
type: Comment
type: AnswerComment
has text: Can you clarify what is *instance value* so I can improve my answer? I understood instance value to mean that for the current process and hence the answer.

http://stackoverflow.com/comment/85611256
type: Comment
type: QuestionComment
has text: @GPhilo Yes, I already put `tf.placeholder(tf.float32, shape=(None,1,2))`. May I add the problem below the main post to make my question clear?
comment on: http://stackoverflow.com/q/49302240
score: 0

http://stackoverflow.com/comment/93596523
type: Comment
has text: what if we don't have the NVIDIA ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51142648

http://stackoverflow.com/a/49427326
has comment: http://stackoverflow.com/comment/85855842
score: 3
has body: Why not follow the official doc? To install pip, securely download get-pip.py. 2 Then run the following: $ python get-pip.py from official doc of pip and the actual link to get-pip.py if you want to install for a specific python version on your machine python2.7 or python3.x instead of python.
answers question: http://stackoverflow.com/q/49427239
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49427239
type: Answer

http://stackoverflow.com/q/49280402
tagged with: python
has answer: http://stackoverflow.com/a/49280986
score: 1
tagged with: rgb
tagged with: image
answer count: 4
has answer: http://stackoverflow.com/a/49280658
type: Question
accepted answer: http://stackoverflow.com/a/49281320
has answer: http://stackoverflow.com/a/49281320
has comment: http://stackoverflow.com/comment/85563804
downvote count: 0
linked to: http://stackoverflow.com/q/10825217
has title: Python -- change the RGB values of the image and save as a image
upvote count: 1
possible better answer: http://stackoverflow.com/a/51981143
favorite count: 0
has answer: http://stackoverflow.com/a/51981143
type: AnsweredQuestion
tagged with: python-imaging-library
has body: I can read every pixel' RGB of the image already, but I don't know how to change the values of RGB to a half and save as a image.Thank you in advance. from PIL import * def half_pixel(jpg): im=Image.open(jpg) img=im.load() print(im.size) [xs,ys]=im.size #width*height # Examine every pixel in im for x in range(0,xs): for y in range(0,ys): #get the RGB color of the pixel [r,g,b]=img[x,y]

http://stackoverflow.com/comment/85796782
comment on: http://stackoverflow.com/a/49397481
type: Comment
has text: Thanks but this isn't what I was asking - I've omitted the data fine, it is not being provided to the Serializer at all. The issue is that the SQL that is generated adds NULL values to anything not provided, causing the SQL to fail.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85754273
has text: Yeah, that would work. However I still want to figure out why `cube()` doesn't work...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49374608
score: 0

http://stackoverflow.com/q/49341204
favorite count: 0
type: Question
tagged with: python
has body: I'm trying to build a very simple TELNET client in Python and I'm getting problem on the last part: sending/receiving data to/from the server. With the code I have, if no data arrives at the very beginnig, the loop get paused and I can't even send commands. Here the interested part of the code: # Infinite cycle that allows user to get and send data from/to the host while True: incoming_data = my_socket.recv(4096) if not incoming_data: print('Problem occurred - Connection closed') my_socket.close() sys.exit() else: # display data sent from the host trough the stdout sys.stdout.write(incoming_data) # Commands sent to the host command = sys.stdin.readline() my_socket.send(command) (I think the program kinda of works if I try to connect to some hosts that send data at the beginning.) The idea would be have two loops, running at the same time, getting data or sending data, but I can't get it to work. I can't use the telnet library and I don't want to use the select library (only sys and socket).
has answer: http://stackoverflow.com/a/49341506
accepted answer: http://stackoverflow.com/a/49341506
tagged with: telnet
type: AnsweredQuestion
score: 1
has title: Simple TELNET in Python - loop paused if no data coming
answer count: 1
downvote count: 0
tagged with: loops
upvote count: 1
tagged with: simultaneous

http://stackoverflow.com/a/49379186
score: -1
upvote count: 0
has body: You can use an iterator which will be handier in such situations. wb = load_workbook(pathToYourFile, use_iterators=True) sheet = wb.worksheets["Sheet1"] row_count = sheet.max_row for row in range(sheet.max_row): if(sheet.cell(row+1,1).value == None): break print(sheet.cell(row+1,1).value)
downvote count: 1
answers question: http://stackoverflow.com/q/49379088
type: Answer

http://stackoverflow.com/q/49418185
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85838122
score: 1
has comment: http://stackoverflow.com/comment/85838155
accepted answer: http://stackoverflow.com/a/49418272
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49418272
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python Terminal Keep closing, was working earlier
tagged with: python
has body: I coded this snippet below in python was working great I restarted my PC and now it instant closes the window no matter what I put! I would really need some help! from selenium import webdriver browser = webdriver.Chrome('C:\Users\Jimmy\Downloads\chromedriver.exe') browser.get('http://www.supremenewyork.com/shop/all') elem = browser.find_element_by_link_text('mustard') k=input("press close to exit") It says File "C:/Users/Jimmy/PycharmProjects/untitled/venv/test.py", line 3 browser = webdriver.Chrome('C:\Users\Jimmy\Downloads\chromedriver.exe') ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

http://stackoverflow.com/comment/85727383
has text: Is the nested list sorted by the first elements, jpp?
comment on: http://stackoverflow.com/q/49363247
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49383479
tagged with: google-oauth
has comment: http://stackoverflow.com/comment/85769032
type: UnansweredQuestion
tagged with: google-api
has comment: http://stackoverflow.com/comment/85771753
has answer: http://stackoverflow.com/a/49412307
has comment: http://stackoverflow.com/comment/85772091
tagged with: python
tagged with: google-directory-api
has body: I'm trying to add a gmail user to a group using google's api in python. Here's my code: from __future__ import print_function import httplib2 import os from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/admin-directory_v1-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/admin.directory.group' CLIENT_SECRET_FILE = 'client_secret1.json' APPLICATION_NAME = 'Directory API Python Quickstart' GROUP = 'customerservice@zego.com' def get_credentials(): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'admin-directory_v1-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('admin', 'directory_v1', http=http) groupinfo = {'email': 'david.bien@zego.com', 'role': 'MEMBER', } service.members().insert(groupKey=GROUP, body=groupinfo).execute() if __name__ == '__main__': main() Whenever I run this I get the following error: HttpError: &lt;HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/groups/customerservice %40zego.com/members?alt=json returned "Insufficient Permission"&gt; So far I have done…
has comment: http://stackoverflow.com/comment/85769931
answer count: 2
has answer: http://stackoverflow.com/a/49384455
upvote count: 2
score: 1
has title: Google API insufficient permissions
tagged with: google-api-python-client
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49413345
has body: Consider this Family model in Django: class Family(models.Model): EMPLOYEE = 'Employee' PARTNER = 'Partner' BIRTH_PARENT_CHOICES = ( (EMPLOYEE, EMPLOYEE), (PARTNER, PARTNER), ) employee_user = models.OneToOneField(User, blank=True, null=True, related_name='employee_family') partner_user = models.OneToOneField(User, blank=True, null=True, related_name='partner_family') employee_first_name = models.CharField(max_length=255, blank=True) employee_last_name = models.CharField(max_length=255, blank=True) employee_email = models.CharField(max_length=255, blank=True) employee_phone = models.CharField(max_length=255, blank=True) partner_first_name = models.CharField(max_length=255, blank=True) partner_last_name = models.CharField(max_length=255, blank=True) partner_email = models.CharField(max_length=255, blank=True) partner_phone = models.CharField(max_length=255, blank=True) point_of_contact = models.CharField(max_length=255, choices=BIRTH_PARENT_CHOICES) A Family consists of an employee and a partner, both of which have various attributes (user, first name, last name, email, phone). There is also a point_of_contact field which is either 'Employee' or 'Partner'. What I'd like to be able to do is to, on an instance family of Family, do something like family.point_of_contact.phone_number which would resolve to family.employee_phone_number if family.point_of_contact == Family.EMPLOYEE and family.partner_phone_number otherwise, and similarly for first_name, last_name, etc. As far as I can tell from https://docs.djangoproject.com/en/2.0/ref/models/fields/, however, it isn't possible to define additional attributes on Django fields. Is there some other way I could do this?
tagged with: python
has title: Adding additional attributes to a Django field
accepted answer: http://stackoverflow.com/a/49413482
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49413482
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49413732
possible better answer: http://stackoverflow.com/a/49413732
tagged with: django

http://stackoverflow.com/comment/85869321
has text: ah so i need to have a valid CA (this is not a .pem file? In the server that im trying to connect to, it has serverCA.pem and serverCA.cer). what is a valid CA (the .cer file?) and where do I put that information in python script?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49433496
type: QuestionComment

http://stackoverflow.com/a/49486004
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49431528
downvote count: 0
answers question: http://stackoverflow.com/q/49431528
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/130686302
has body: This is a really easy fix. Just change your models.py file like so: from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) username = models.CharField(max_length=100) birth_date = models.DateField(blank=True) gender = models.CharField(max_length=10, blank=True) password = models.CharField(max_length=1000) contact = models.CharField(max_length=10, blank=True) email = models.CharField(max_length=100) time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.username That way, your user model will inherit all of the AbstractBaseUser methods, including set_password. Look at this full example from the documentation for extra information.
has comment: http://stackoverflow.com/comment/85976684

http://stackoverflow.com/comment/85791639
type: AnswerComment
score: 0
type: Comment
has text: so when I run your code I am getting error Traceback (most recent call last): File "C:\Python27\convert_to_hex.py", line 51, in <module> n.write('{}\n'.format(hex(int(num)))) ValueError: zero length field name in format
comment on: http://stackoverflow.com/a/49394806

http://stackoverflow.com/comment/85870981
score: 0
type: AnswerComment
has text: You don't necessarily need all this stuff either: `hdu1 = fits.BinTableHDU.from_columns(fits.ColDefs([col1]))` Much of the manual construction of FITS table structures can be simplified for example by using [Table.as_array()](http://docs.astropy.org/en/stable/api/astropy.table.Table.html#astropy.table.Table.as_array), since `BinTableHDU.from_columns` accepts a multi-field Numpy array. So `BinTableHDU.from_columns(table.as_array())` works here (I think that's what `table_to_hdu()` is mostly doing as well).
type: Comment
comment on: http://stackoverflow.com/a/49387176

http://stackoverflow.com/a/49282253
has body: Data from Jez , method involve value_counts df.user_id.map(df.user_id.value_counts().gt(1).replace({True:'Frequent',False:'Single'})) Out[52]: 0 Frequent 1 Frequent 2 Frequent 3 Single 4 Frequent 5 Frequent 6 Single Name: user_id, dtype: object
has comment: http://stackoverflow.com/comment/85567108
answers question: http://stackoverflow.com/q/49282033
type: Answer
has comment: http://stackoverflow.com/comment/85567211
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49317852
answer count: 1
accepted answer: http://stackoverflow.com/a/49325167
tagged with: security
type: AnsweredQuestion
score: 0
tagged with: network-programming
has comment: http://stackoverflow.com/comment/85638950
has title: Unable to use scapy as a bridge among interfaces
tagged with: python
has body: I'm trying to perform a transparent MITM attack with scapy. I've got an Ubuntu machine with two network interfaces, connected each one to a machine. Those machines have same subnet addresses and operate correctly if directly connected. The objective is to be able to be totally transparent, using both interfaces with no IP address and in promisc mode. The implementation I'm using is the following: def pkt_callback(pkt): if pkt.sniffed_on == "enp0s3": sendp(pkt, iface="enp0s8", verbose=0) else: sendp(pkt, iface="enp0s3", verbose=0) def enable_bridge(): sniff(iface=["enp0s3", "enp0s8"], prn=pkt_callback, store=0) if __name__ == "__main__": conf.sniff_promisc=True enable_bridge() This is not all the code, but is the main routing part... I can see that packets arrive to both interfaces, but no pinging from one machine to another... Any idea of how to make this work? Thanks in advance. EDIT 1: The full implementation here: from scapy.all import * from utils import interfaces, addresses #from routing import * from packet_filters import is_mms_packet from attacks import performAttack import sys import os import time import datetime def writePacketInDisk(pkt): wrpcap("network_logs/network-log- "+datetime.date.today().strftime("%Y")+"-" +datetime.date.today().strftime("%B")+"- "+datetime.date.today().strftime("%d")+".pcap", pkt, append=True) def pkt_callback_PLC_OPC(pkt): ret = True # if is_mms_packet(pkt): # writePacketInDisk(pkt) #ret = performAttack(pkt) return ret def pkt_callback_OPC_PLC(pkt): ret = True # if is_mms_packet(pkt): # writePacketInDisk(pkt) #ret = performAttack(pkt) return ret def enable_bridge(): print "hello!!" bridge_and_sniff(interfaces["plc-ccb"], interfaces["opc"], xfrm12=pkt_callback_PLC_OPC, xfrm21=pkt_callback_OPC_PLC, count=0, store=0) #prn = lamba x: x.summary() print "bye!!" if __name__ == "__main__": conf.sniff_promisc=True enable_bridge() This is definitely not working... Is the code correct? May be my VM too slow for this task?
has answer: http://stackoverflow.com/a/49325167
type: Question
tagged with: man-in-the-middle
tagged with: scapy

http://stackoverflow.com/a/49499867
has comment: http://stackoverflow.com/comment/86058311
has comment: http://stackoverflow.com/comment/86005065
has comment: http://stackoverflow.com/comment/86004963
type: Answer
has comment: http://stackoverflow.com/comment/86194858
score: 4
upvote count: 4
has body: I might be missing something crucial, otherwise (almost) every statement / assumption in the question seems incorrect: It is possible to install / upgrade [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions using PIP GitHub is used to host the source code (mainly). The assets there are Mark Hammond's Win installers (since PyWin32 was hosted on SourceForge - long before PIP was born), I suppose they are only built for backward compatibility. There is a way to (build and) install directly from GitHub (or any other URL): [SO]: pip install from git repo branch PIP doesn't download the PyWin32 binary, but .whl (wheel) packages from [PyPI]: Links for pywin32 In order to demo all the above, I created a VirtualEnv, and based on that, a series of steps: Python and PIP executables locations / versions PIP test (list PyWin32 version using PIP) - no output (no PyWin32 installed) PyWin32 download and URL display PyWin32 install (an older version to test upgrade later) PIP test PyWin32 test (list PyWin32 version using PyWin32) PyWin32 upgrade PIP test PyWin32 test Output: (py36x64_test) e:\Work\Dev\StackOverflow\q049398198> sopr.bat ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [prompt]> :: 1. Locations [prompt]> where python pip c:\Work\Dev\VEnvs\py36x64_test\Scripts\python.exe c:\Work\Dev\VEnvs\py36x64_test\Scripts\pip.exe [prompt]> python -c "import sys;print(sys.version)" 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] [prompt]> pip -V pip 9.0.3 from c:\work\dev\venvs\py36x64_test\lib\site-packages (python 3.6) [prompt]> :: 2. PIP test [prompt]> pip list 2>nul | findstr pywin32 [prompt]> :: 3. Download [prompt]> pip download -vvv pywin32 2>nul | findstr /i download Downloading pywin32-223-cp36-cp36m-win_amd64.whl (9.0MB) Downloading from URL https://pypi.python.org/packages/9f/9d/f4b2170e8ff5d825cd4398856fee88f6c70c60bce0aa8411ed17c1e1b21f/pywin32-223-cp36-cp36m-win_amd64.whl#md5=2d211288ee000b…
answers question: http://stackoverflow.com/q/49398198
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49398198
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86199618
has comment: http://stackoverflow.com/comment/86097658

http://stackoverflow.com/comment/85619089
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49308245
type: Comment
has text: Since the error notifies that `tile` is a `tuple`, use `len(tile)` instead of `tile.size`.

http://stackoverflow.com/q/49379505
has comment: http://stackoverflow.com/comment/85760319
tagged with: python
score: -1
tagged with: python-3.6
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85759594
has body: im writting an app using python and sockets, here is piece of the server code: while True: c = random.choice(temp_deck) temp_deck.remove(c) if hakem == p1: p1.send(pickle.dumps(('{} for {}'.format(c,'you'),False))) p2.send(pickle.dumps(('{} for {}'.format(c,'other'),False))) else: p1.send(pickle.dumps(('{} for {}'.format(c,'other'),False))) p2.send(pickle.dumps(('{} for {}'.format(c,'you'),False))) if c in ['A♠','A♣','A♦','A♥']: if hakem == p1: p1.send(pickle.dumps(('You are Hakem!',False))) p2.send(pickle.dumps(('Other Player is Hakem!',False))) break else: p1.send(pickle.dumps(('Other Player is Hakem!',False))) p2.send(pickle.dumps(('You are Hakem!',False))) break if hakem == p1: hakem = p2 other = p1 else: hakem = p1 other = p2 this needs two clients to connect, everything is fine except clients don't receive full data: for example one gets: 3♠ for other 2♠ for you 10♣ for other 10♦ for you A♣ for other the other gets: 2♠ for you 10♣ for other 10♦ for you A♣ for other what should i do? client code: import socket import pickle s = socket.socket() host = socket.gethostname() port = 12345 s.connect((host, port)) while True: o = pickle.loads(s.recv(1024)) print(o[0]) if o[1] == True: s.send(pickle.dumps(input("&gt;"))) s.close
has comment: http://stackoverflow.com/comment/85759606
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85760294
has answer: http://stackoverflow.com/a/49379786
has title: Sockets in python
downvote count: 1
has comment: http://stackoverflow.com/comment/85759642
tagged with: sockets
has comment: http://stackoverflow.com/comment/99010833

http://stackoverflow.com/a/49352987
downvote count: 0
has body: I believe this is what you are looking for. I have added explanations to the code for each step. # create helper columns defining contiguous blocks and day df['block'] = (df['value'].astype(bool).shift() != df['value'].astype(bool)).cumsum() df['day'] = df['index'].dt.normalize() # group by day to get unique block count and value count session_map = df[df['value'].astype(bool)].groupby('day')['block'].nunique() hour_map = df[df['value'].astype(bool)].groupby('day')['value'].count() # map to original dataframe df['sessions'] = df['day'].map(session_map) df['hours'] = df['day'].map(hour_map) # calculate result res = df.groupby(['day', 'hours', 'sessions'], as_index=False)['value'].sum() res['duration'] = res['hours'] / res['sessions'] res['amount'] = res['value'] / res['sessions'] Result day sessions duration value amount 0 2003-01-01 6 2.5 127.9 21.316667
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86169662
type: Answer
has comment: http://stackoverflow.com/comment/86164111
answers question: http://stackoverflow.com/q/49352279
has comment: http://stackoverflow.com/comment/86164024
accepted answer of: http://stackoverflow.com/q/49352279
has comment: http://stackoverflow.com/comment/86169696
type: AcceptedAnswer

http://stackoverflow.com/a/49396077
answers question: http://stackoverflow.com/q/49393789
type: Answer
accepted answer of: http://stackoverflow.com/q/49393789
has body: Avoid calling update and sleep. Instead use after and mainloop. Your code should schedule your gameloop using after and enter the mainloop after setting up everything. Then keep scheduling the gameloop with after calls. Your actual problem is you have confused using self.x and self.y as a position in the setup but then use these as a relative move in the game loop. So when you first call GameUpdate you move the rectangle by half the canvas size and it immediately moves out of view. Below is a version that uses these as the 'man' position and asserts the position using coords each time around the game loop. import tkinter as tk GAME_WIDTH = 800 GAME_HEIGHT = 600 GAME_BG = 'green' MOVE_SPEED = 10 MAN_SIZE = 20 class Game(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # Trigger Of Other Functions self.x = GAME_WIDTH/2 self.y = GAME_HEIGHT/2 self.create_board() self.create_men() self.bind('&lt;Any-KeyPress&gt;',self.move) def create_board(self): self.board = tk.Canvas(width=GAME_WIDTH, height=GAME_HEIGHT, bg=GAME_BG) self.board.pack(padx=10, pady=10) def create_men(self): self.men = self.board.create_rectangle((self.x, self.y, self.x + MAN_SIZE, self.y + MAN_SIZE), fill='red', outline='black') def move(self, event=None): key = event.keysym print(key) if key=='Left': self.x = self.x - MOVE_SPEED elif key=='Right': self.x = self.x + MOVE_SPEED elif key=='Up': self.y = self.y - MOVE_SPEED elif key=='Down': self.y = self.y + MOVE_SPEED else: pass return def game_loop(self): self.board.coords(self.men, (self.x, self.y, self.x + MAN_SIZE, self.y + MAN_SIZE)) self.after(10, self.game_loop) def main(): game = Game(className="Snake") game.after(10, game.game_loop) game.mainloop() if __name__ == '__main__': main()
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49351290
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49342252
has body: Here's a version of your code that I think does what you. I think the main problem was with how you were initializing the gameboard variable: gameBoard=[[None]*8]*8 which I changed to: gameBoard=[[None]*8 for _ in range(8)] # Proper initialization. So it would create a new column of None values for each row instead of putting the same list in each one. This is a common Python newbie "gotcha". I also tried to clean-up, simplify, and organize the code structure to some degree. One notable change is I moved all those function definitions outside the main loop—as there's no reason to do that more than once and it just slows execution down. There are still a number of other optimizations that could be done, but since you aren't asking for a full code review (which wouldn't be appropriate here anyway—there's another site called Code Review for that kind of thing), I refrained from implementing any of them... import pygame newGame=True loggedIn=False miniGame=False black=(0,0,0) white=(255,255,255) red=(255,0,0) greyBackground=(203, 206, 203) # This sets the WIDTH and HEIGHT of each grid location width=65 height=65 radius=30 margin=0# This sets the margin between each cell xDistanceFromEdge=220 #gameBoard=[[None]*8]*8 gameBoard=[[None]*8 for _ in range(8)] # Proper initialization. windowSize=[960, 640] pygame.init() screen = pygame.display.set_mode(windowSize) pygame.display.set_caption("Draughts Game") done = False clock = pygame.time.Clock() # Added helper function. def square_colour(row, col): """ Determine colour of game board square from its position. """ return white if (row + col) % 2 == 0 else black # Makes upper-left corner white. def boardGui(black,white): for boardRow in range(8): for boardColumn in range(8): xCoordinate=((margin+width) * boardColumn + margin)+xDistanceFromEdge yCoordinate=(margin+height) * boardRow + margin currentColour = square_colour(boardRow, boardColumn) pygame.draw.rect(screen,currentColour,[xCoordinate,yCoordinate, width, height]) def pi…
upvote count: 1
has comment: http://stackoverflow.com/comment/85706053
has comment: http://stackoverflow.com/comment/85710085
answers question: http://stackoverflow.com/q/49342252
score: 1
has comment: http://stackoverflow.com/comment/85706365
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85703374
has comment: http://stackoverflow.com/comment/85828707
has comment: http://stackoverflow.com/comment/85709372
has comment: http://stackoverflow.com/comment/85705530
has comment: http://stackoverflow.com/comment/85827962

http://stackoverflow.com/comment/85636416
score: 1
comment on: http://stackoverflow.com/a/49317575
type: Comment
type: AnswerComment
has text: How is this answer specific to python 3.x?

http://stackoverflow.com/q/49406381
tagged with: python
tagged with: collaborative-filtering
has title: LightFM does the training set need to be the same size as the test set?
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: machine-learning
favorite count: 0
has body: I'm working on a pure collaborative filtering model in LightFM using a simple user-item matrix. When I have a training matrix that has more rows than the test matrix, I encounter this error: "Incorrect number of features in user_features" It seems this is caused by line 789 in lightfm.py: if not user_features.shape[1] == self.user_embeddings.shape[0]: raise ValueError('Incorrect number of features in user_features') Investigating this - it looks like it is being caused by line 778 in lightfm.py: n_users, n_items = test_interactions.shape Which suggests the size of the test dataset should match the train. And making them the same size does fix my error. How can I persuade LightFM to let me have train and test datasets of different sizes?
tagged with: recommendation-engine
has comment: http://stackoverflow.com/comment/85814243
type: Question
has comment: http://stackoverflow.com/comment/85818253
type: UnansweredQuestion

http://stackoverflow.com/comment/85861571
type: Comment
comment on: http://stackoverflow.com/a/49429835
type: AnswerComment
score: 0
has text: I tried it, and now I'm having this error: Snd_Mer_Vol_Output.columns Traceback (most recent call last): File "<ipython-input-40-91fbb9d8845a>", line 1, in <module> Snd_Mer_Vol_Output.columns AttributeError: 'NoneType' object has no attribute 'columns'

http://stackoverflow.com/q/49286472
has title: Mimic str() from R
upvote count: 1
has comment: http://stackoverflow.com/comment/85576343
has comment: http://stackoverflow.com/comment/85576412
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85577019
has comment: http://stackoverflow.com/comment/85576155
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85576047
tagged with: python
has comment: http://stackoverflow.com/comment/85576064
has body: str() in R can print a summarized form of an object in a nested way. https://www.r-bloggers.com/str-implementation-for-data-frames/ I am not able to find a way similar to str(). For example, pprint does not do so. The idea is to 1) show the content in a readable way, 2) but when it is too long, show some representatives). print can not do both 1 and 2. pprint can not do 2. d = {} import string for x in string.ascii_lowercase: d[x] = range(1000) print d import pprint pprint.pprint(d) Does anybody know something similar to str() in the sense that I mentioned above?
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/85576078
score: 0
answer count: 0

http://stackoverflow.com/q/49437070
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have written this code for binary search for an element in a list. The code reaches maximum recursion. I can't figure out why. def binary_search(alist, x, left = 0, right = None): right = right or len(alist) - 1 middle = left + (right - left) // 2 if x == alist[middle]: return middle elif right &lt; left: return -1 elif x &lt; alist[middle]: return binary_search(alist, x, left, middle - 1) elif x &gt; alist[middle]: return binary_search(alist, x, middle + 1, right) if __name__ == '__main__': a = [2, 3, 4, 5, 6,7,8,9,10,11] data = [1, 2, 3, 4, 5, 6, 7,8,9,10,11, 12] for x in data: print(binary_search(a, x), end = ' ')
answer count: 2
has title: Recursive Binary Search Tree in Python
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/49439740
tagged with: python
has comment: http://stackoverflow.com/comment/85876284
has comment: http://stackoverflow.com/comment/85876307
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/85876076
has answer: http://stackoverflow.com/a/49437267

http://stackoverflow.com/comment/85739122
has text: `foo` only has 1 item so use `foo[0].x`, where do you define `x` or `y` that you pass to `return_index`?
type: Comment
comment on: http://stackoverflow.com/q/49369089
type: QuestionComment
score: 2

http://stackoverflow.com/comment/85684052
has text: @BorisElGareh But either way, that doesn't change the fact that you're not going to get a useful `returncode` if you terminated the process; you're just going to get the signal back, negated (because, after all, you never gave the process a chance to do a normal `exit`, so there can't be any useful `returncode`).
score: 0
comment on: http://stackoverflow.com/a/49341666
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49439807
has answer: http://stackoverflow.com/a/49445367
possible better answer: http://stackoverflow.com/a/49445367
has answer: http://stackoverflow.com/a/49454397
accepted answer: http://stackoverflow.com/a/49454397
tagged with: python
has title: Scraping with selenium, can not get a button to click and load a hidden table with the data i want
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: selenium-chromedriver
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85885350
tagged with: selenium
favorite count: 0
type: Question
has body: I am trying to scrape a form that has nav tabs that display 4 different ways to search through the requested information. The URL loads into the tab that I want to search from and with the date fields automatically filled in. When a human user wants to look through the info they only have to click the search button that is in the selected tab, which enabled a loading screen and fills and enables a table below with the data I want to scrape. I am using python 3 and selenium currently. Button code : Search This is my code right now: #start of code after imports options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') dir_path = os.path.dirname(os.path.realpath(__file__)) chromedriver = dir_path + "/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver browser = webdriver.Chrome(chrome_options = options, executable_path = chromedriver) # LOGS INTO THE SITE browser.get('https://***.com/') username = browser.find_element_by_name('UserName') username.send_keys('***') password = browser.find_element_by_name('Password') password.send_keys('***') browser.find_element_by_css_selector('#sign-in').click() # LOGIN WORKS #GOES TO THE SCHEDUALS PAGE browser.get('https://***.com/Schedules') #I KNOW IT IS NAVIGATING TO THIS PAGE # I HAVE TRIED WAITING AND FOUND NO LUCK, TRYING TO CLICK THE BUTTON LEADS TO A HUGE LIST OF TRACEBACKS browser.find_element_by_css_selector('community-search').click() #WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, 'community-search'))).click #end of code Errors- Traceback (most recent call last): File "Project.py", line 29, in <module> browser.find_element_by_css_selector('community-search').click() File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 589, in find_element_by_css_selector return self.find_element(by=By.CSS_SELECTOR, value=css_selector) File "C:\ProgramData\Anaconda3\lib\site-packages\sele…

http://stackoverflow.com/comment/85874705
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49435804
has text: install from wheel file [from pypi](https://pypi.python.org/pypi/PyQt5#downloads)

http://stackoverflow.com/q/49287776
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49288040
score: 1
favorite count: 0
type: Question
tagged with: python-attrs
has title: Storing passed data in object twice with `attrs` package
has answer: http://stackoverflow.com/a/49422250
tagged with: python
accepted answer: http://stackoverflow.com/a/49422250
has body: I am creating a data provider class that will hold data, perform transformations and make it available to other classes. If the user creates and instance of this class and passes some data at instantiation, I would like to store it twice: once for all transformations and once as a copy of the original data. Let's assume the data itself has a copy method. I am using the attrs package to create classes, but would also be interested in best approaches to this in general (perhaps there is a better way of getting what I am after?) Here is what I have so far: @attr.s class DataContainer(object): """Interface for managing data. Reads and write data, acts as a provider to other classes. """ data = attr.ib(default=attr.Factory(list)) data_copy = data.copy() def my_func(self, param1='all'): """Do something useful""" return param1 This doesn't work: AttributeError: '_CountingAttr' object has no attribute 'copy' I also cannot call data_copy = self.data.copy(), I get the error: NameError: name 'self' is not defined. The working equivalent without the attrs package would be: class DataContainer(object): """Interface for managing data. Reads and write data, acts as a provider to other classes. """ def __init__(self, data): "Init method, saving passed data and a backup copy" self.data = data self.data_copy = data EDIT: As pointed out by @hynek, my simple init method above needs to be corrected to make an actual copy of the data: i.e. self.data_copy = data.copy(). Otherwise both self.data and self.data_copy would point to the same object.
tagged with: class
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49288040
answer count: 2

http://stackoverflow.com/a/49389468
type: Answer
has comment: http://stackoverflow.com/comment/85781957
accepted answer of: http://stackoverflow.com/q/49388492
has comment: http://stackoverflow.com/comment/85780715
answers question: http://stackoverflow.com/q/49388492
type: AcceptedAnswer
has body: The values of eis, ref and her switch to "25" because you are looping over the variable PrimaryServiceCategory, and the last value in that serie is "25". You are using eis, ref and her as the names of the iterator variable, so they change in every loop. I think this is an inefficient way to do it. It's better if you use groupby and transform: df['count'] = df.groupby(['id_profile','PrimaryServiceCategory']).transform('count')
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85780667

http://stackoverflow.com/comment/85872913
type: Comment
type: AnswerComment
has text: Not a bad solution, but concatenating strings in a loop is not exactly a good idea (because it's slow). A more efficient solution would use `''.join`.
comment on: http://stackoverflow.com/a/49435413
score: 0

http://stackoverflow.com/q/49340588
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/49340616
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49340619
tagged with: pandas
has body: I have a data frame that looks like this: a b c 0 Alabama[edit] NaN NaN 1 Auburn (Auburn University)[1] 2 Florence (University of 3 Jacksonville (Jacksonville State 4 Livingston (University of I'd like to add a column to the dataframe called 'State' that copies the value of column 'a' when column 'b' has a NaN value, otherwise it will just place a NaN value in the state column. I have tried: df['State'] = np.where(df['b'] == np.NaN, df['a'], np.NaN) df['State'] = df.loc[df['b'] == np.NaN, 'a'] However for some reason both of these do not seem to evaluate the np.NaN. If i modify the criteria to == '(Auburn' then it finds the row and correctly copies the value of column 'a' into 'State' If i use this function: df1 = df[df['b'].isnull()] then i get all the relevant rows but in a new dataframe which i was trying to avoid. Any help much appreciated. Thanks JP
has title: Pandas, select a single column where a second column has a NaN value
has answer: http://stackoverflow.com/a/49340619
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49340616
favorite count: 0

http://stackoverflow.com/comment/85589521
score: 0
type: AnswerComment
has text: The role of `start` argument of `sum` function looks like something determines the return type and starting value and type to be added. Initially it is set to be an integer zero, so normal summation works, but since I'm adding Sympy.Matrix type, the starting value should be also that type.
type: Comment
comment on: http://stackoverflow.com/a/49292371

http://stackoverflow.com/comment/85884129
score: 0
type: AnswerComment
has text: If I try to run your example I get the following error: ```--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-2-d3e0176b6e3f> in <module>() 7 ddf = dd.from_pandas(df, npartitions=2) 8 ----> 9 ddf.groupby('first_name').apply(func, x=3).compute() TypeError: apply() got an unexpected keyword argument 'x' ```
comment on: http://stackoverflow.com/a/49417706
type: Comment

http://stackoverflow.com/comment/85589252
type: QuestionComment
has text: @Panagiots Kanavos I did try to implement the `f.close()` inside the with open declaration (as you can see in updated code), but the error keeps coming. :-(
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49282193

http://stackoverflow.com/a/49329047
has body: The main problem comes from the FilterChoiceVar.get() is "All" expression which is never True. A good practice is to always use '==' instead of 'is' to compare strings. Here is my modified code, including some code cleaning: from tkinter import * AllCheck = False filterList = ["All","Not All"] def check_dropdown(*args): global AllCheck AllCheck = FilterChoiceVar.get() == "All" def scanBus(): check_dropdown() if ScanVar.get() and AllCheck: print("AllCheck in action!") GuiWindow = Tk() FilterChoiceVar = StringVar(GuiWindow) FilterChoiceVar.set("Not All") FilterChoice = OptionMenu(GuiWindow, FilterChoiceVar, *filterList) FilterChoice.grid(row=0, column=0) ScanVar = BooleanVar() ScanButton = Checkbutton(GuiWindow, text="scan", variable=ScanVar, command=scanBus, indicatoron=0) ScanButton.grid(row=1, column=0) GuiWindow.geometry('{}x{}'.format(100, 60)) GuiWindow.mainloop()
accepted answer of: http://stackoverflow.com/q/49328265
has comment: http://stackoverflow.com/comment/85661093
has comment: http://stackoverflow.com/comment/85669224
score: 3
answers question: http://stackoverflow.com/q/49328265
has comment: http://stackoverflow.com/comment/85673757
upvote count: 3
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49296912
has comment: http://stackoverflow.com/comment/85599095
has body: Pandas data structures implement this functionality for 1D (pd.Series), 2D (pd.DataFrame) and 3D (pd.Panel) data: import numpy as np import pandas as pd s = pd.Series(data=['One', 'Two', 'Three'], index=[1, 2, 3]) a = np.array([1, 2, 3]) b = s[a] print(b.values) ['One' 'Two' 'Three'] For higher-dimensional structures, you have xarray.
answers question: http://stackoverflow.com/q/49296660
score: 7
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/128935458
has comment: http://stackoverflow.com/comment/85598924
type: Answer

http://stackoverflow.com/comment/85807658
has text: Oops, thanks for clarity on that. I wasn't aware you could use file objects in that way.
comment on: http://stackoverflow.com/a/49402998
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85654471
score: 1
comment on: http://stackoverflow.com/q/49326410
type: Comment
has text: add `print(cdc_list)` at the end of your script, then try again.
type: QuestionComment

http://stackoverflow.com/comment/85697132
type: QuestionComment
has text: I cannot see data, but `df_1 = pd.read_csv("result4.csv", usecols=[1])` should working.
type: Comment
comment on: http://stackoverflow.com/q/49348647
score: 0

http://stackoverflow.com/q/49280875
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: graphviz
has comment: http://stackoverflow.com/comment/94952973
score: 2
tagged with: pycallgraph
answer count: 0
upvote count: 2
has body: Im trying to use the pycallgraph library for Python on my Windows commandline from pycallgraph import PyCall Graph from pycallgraph.output import GraphvizOutput with PyCallGraph(output=GraphvizOutput()): for i in range(0,11): print(str(i) + " times looped") After executing this i get the following error: 'The command "{}" is required to be in your path.'.format(cmd)) pycallgraph.exceptions.PyCallGraphException: The command "dot" is required to be in your path. I know that i need to install dot, but i don't know how to do it
downvote count: 0
has title: Python PyCallGraph.PyCallGraphException Graphviz
favorite count: 0
type: Question

http://stackoverflow.com/comment/85790016
type: Comment
has text: Possible duplicate of [Selenium using Python - Geckodriver executable needs to be in PATH](https://stackoverflow.com/questions/40208051/selenium-using-python-geckodriver-executable-needs-to-be-in-path)
type: QuestionComment
comment on: http://stackoverflow.com/q/49368211
score: 0

sorting
tags question: http://stackoverflow.com/q/49344301
tags question: http://stackoverflow.com/q/49348396
tags question: http://stackoverflow.com/q/49328936
tags question: http://stackoverflow.com/q/49374253
tags question: http://stackoverflow.com/q/49285116
tags question: http://stackoverflow.com/q/49296538
tags question: http://stackoverflow.com/q/49439103
tags question: http://stackoverflow.com/q/49394878
tag name: sorting
tags question: http://stackoverflow.com/q/49289863
tags question: http://stackoverflow.com/q/49377933
tags question: http://stackoverflow.com/q/49343394
tags question: http://stackoverflow.com/q/49326927
tags question: http://stackoverflow.com/q/49399555
tags question: http://stackoverflow.com/q/49368730
tags question: http://stackoverflow.com/q/49354702
tags question: http://stackoverflow.com/q/49391089
tags question: http://stackoverflow.com/q/49407565
type: Tag

http://stackoverflow.com/comment/85803166
comment on: http://stackoverflow.com/q/49400865
has text: You forgot `{}` in `.format`. But you could write `ax.set_title('Phase/Freq %s'fName)` for instance or simply `ax.set_title('Phase/Freq ' + fName)` instead.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49379399
has comment: http://stackoverflow.com/comment/85760819
score: 0
tagged with: python-import
answer count: 0
has comment: http://stackoverflow.com/comment/85763104
tagged with: python-packaging
has comment: http://stackoverflow.com/comment/85760057
has comment: http://stackoverflow.com/comment/85760209
has body: I am writing a Python package and I am observing different behaviour for circular imports depending on whether I use from x import y or import x.y in the submodules within the package. To be clear, I do not want to know how to avoid the circular import, I would just like to understand the behaviour. My package has the following structure: (__init__.py is empty) package/__init__.py package/module1.py package/module2.py If I use the from x import y form below, then I get an ImportError when I try to import package.module1. # module1.py from package import module2 # module2.py from package import module1 However, if I instead use the import x.y form, then I can import package.module1 without any problems. What is going on? # module1.py import package.module2 # module2.py import package.module1 I have observed this behaviour in Python 2.7.5 and 3.4.3. Edit: There is no error using from x import y for versions 3.5.2 and 3.6.4.
type: Question
type: UnansweredQuestion
has title: Different behaviour for circular import in submodules of package
has comment: http://stackoverflow.com/comment/85762987
tagged with: python-module
tagged with: python

http://stackoverflow.com/q/49290266
has answer: http://stackoverflow.com/a/49290555
answer count: 1
downvote count: 0
tagged with: histogram
upvote count: 21
linked to: http://stackoverflow.com/q/43872450
has title: python matplotlib histogram specify different colours for different bars
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85593027
tagged with: matplotlib
tagged with: python
score: 21
accepted answer: http://stackoverflow.com/a/49290555
has comment: http://stackoverflow.com/comment/85710495
has body: I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code). I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used. import numpy as np import matplotlib.pyplot as plt data = np.random.rand(1000) plt.hist(data,color = 'r')
type: Question

http://stackoverflow.com/q/49304262
type: AnsweredQuestion
tagged with: tkinter
upvote count: 0
has title: Save before closing python
answer count: 1
linked to: http://stackoverflow.com/q/111155
downvote count: 1
favorite count: 0
type: Question
has body: I am building a GUI with Tkinter at the moment. With the GUI I can create files, add certain lines to the files, delete lines, save and load files. My problem is, that i want to prevent the closing of the window if the current file wasn't saved. Is there a way to solve this problem?
duplicate of: http://stackoverflow.com/q/111155
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49304404
has answer: http://stackoverflow.com/a/49304404

http://stackoverflow.com/q/49372935
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85747968
type: Question
has comment: http://stackoverflow.com/comment/85756271
has title: Pandas groupby count values greater than given values in each group
tagged with: python
accepted answer: http://stackoverflow.com/a/49373105
has answer: http://stackoverflow.com/a/49373105
has body: I want to count how many values are greater than a given set of values in each group. For instance, the DataFrame df is like: print(df) item A B C 0 a -4 17 -15 1 a 19 -16 -3 2 a -18 -11 -13 3 b -2 9 7 4 b -9 -15 -14 5 b -20 2 -10 6 c -19 0 -10 7 c 11 3 4 8 d 5 0 -17 9 d 7 1 -1 and the condition c is another DataFrame, like print(c) item value 0 a 5 1 b -1 2 c 2 3 d 1 The desired result looks like count item A B C a 1 1 0 b 0 2 1 c 1 1 1 d 2 0 0 I searched questions about using the pandas.groupby() function with conditions, but the answers were based on "greater than one value", not for a set of values. The pseudo-code might write as following... I know it does not work properly... df.groupby("item")"A", "B", "C".apply(lambda x: x &gt; c["value"] if df["item"] == c["item"]).size() It would be greatly appreciated if any of you could help me. Many thanks.
tagged with: pandas

python-mss
type: Tag
tag name: python-mss
tags question: http://stackoverflow.com/q/49308345

http://stackoverflow.com/comment/85784278
type: Comment
has text: This is still efficient for this usecase because the goal is to stop at the first match, so we can linear search until that match and then just linear copy from there on, if I understand the problem. If so, it's one of the few cases where using `index` actually makes sense.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49391078

http://stackoverflow.com/q/49412064
tagged with: tracd
has answer: http://stackoverflow.com/a/49417090
accepted answer: http://stackoverflow.com/a/49417090
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has body: I'm running a TRAC server (tracd service) with 3 independant projects configured. Each project has an own password file in order to keep the user management independant. TRAC is started as a Windows service as described on https://trac.edgewall.org/wiki/0.11/TracStandalone It seems that starting the TRAC server does not work if the string length of the key 'AppParameters' in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\tracd\Parameters is too long. The maximum key lenght seems to be around 260 characters. The TRAC server can be started successfully using following 'AppParameters' key: C:\Python27\Scripts\tracd-script.py -p 80 --auth=',C:\Trac\Moisture\conf\.htpasswd,mt.com' --auth=',C:\Trac\Balances\conf\.htpasswd,mt.com' --auth=',C:\Trac\Weights\conf\.htpasswd,mt.com' C:\Trac\Moisture C:\Trac\Balances C:\Trac\Weights The TRAC server does not start with following 'AppParameters' key: C:\Python27\Scripts\tracd-script.py -p 80 --auth='Moisture,C:\Trac\Moisture\conf\.htpasswd,mt.com' --auth='Balances,C:\Trac\Balances\conf\.htpasswd,mt.com' --auth='Weights,C:\Trac\Weights\conf\.htpasswd,mt.com' C:\Trac\Moisture C:\Trac\Balances C:\Trac\Weights If I add a fourth project it is not possible to start the TRAC server anymore because the string is too long. Is this problem known? Is there a workaround?
tagged with: authentication
upvote count: 1
favorite count: 0
type: Question
tagged with: trac
has title: Starting TRAC server with multiple independant projects
tagged with: python

http://stackoverflow.com/comment/85828550
type: QuestionComment
comment on: http://stackoverflow.com/q/49412942
has text: I upvoted because you edited the question correctly
score: 0
type: Comment

http://stackoverflow.com/comment/85755222
type: Comment
has text: Welcome! You can [accept my answer](https://stackoverflow.com/help/accepted-answer) if it solved your problem. Thanks
comment on: http://stackoverflow.com/a/49333709
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85648983
has text: Well, there you go :) `print ([chr(ord(x) & 0xff)+chr(ord(x)>>8) for x in s])` (or something similar that works for your original input) shows `['Da', 'ta', 'Ba', 'se', 'De', 'sc']`. *Somewhere* in your workflow it gets assumed you are using 2-byte Unicode characters.
comment on: http://stackoverflow.com/q/49323210
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49433801
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49309679
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49309679
has body: Tensorflow supports dtype conversion like that. In operations, such as x + 1, the value 1 is going through tf.convert_to_tensor function that takes care of validation and conversion. The function is sometimes called manually under the hood, and when the dtype argument is set, the value automatically gets converted to this type. When you feed the array into a placeholder like that: session.run(..., feed_dict={x: data}) ... the data is explicitly converted to a numpy array of the right type via np.asarray call. See the source code at python/client/session.py. Note that this method may reallocate the buffer when the dtype is different and that's exactly what's happening in your case. So your memory optimization doesn't quite work as you expect: the temporary 32-bit data is allocated internally.
has comment: http://stackoverflow.com/comment/85870254

http://stackoverflow.com/comment/85722914
has text: along with above two statements these are remaning code slug,id,reason in cur.fetchall(): temp_list.append(str(slug)) logs_id = id temp_list.append('https://rtest.sdm.nsn-rdnet.net/logs/' + str(logs_id[logs_id_counter])) reason = str(reason) temp_list.append(str(reason)) templine = ",".join(temp_list) f_out1.write( templine + '\n' )
comment on: http://stackoverflow.com/a/49360809
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85630053
type: QuestionComment
has text: This is my first post ever, sorry for the inconvenience. I tried to add the picture to text area and stackoverflow said I am not allowed to do that until I get some level up? Thank you though
comment on: http://stackoverflow.com/q/49314033
score: 0
type: Comment

http://stackoverflow.com/a/49415581
has body: Not sure about the context of your data, but if it is not delimited by commas, try to do this inp = pd.read_csv('csvfile', delim_whitespace=True) then inp.to_csv('csvfile_new', sep=' ')
score: 0
answers question: http://stackoverflow.com/q/49414967
type: Answer

http://stackoverflow.com/comment/99852449
comment on: http://stackoverflow.com/q/49404349
score: 0
has text: If you already know the number of clusters you need why don't you use other algorithm like Gaussian Mixture model in which you can easily set the number of clusters? in HDBSCAN you can set min cluster size and based on the data structure it will return the number of clusters needed for structuring your data.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85781281
type: AnswerComment
score: 0
has text: yw~ :-) feel free to add :-)
comment on: http://stackoverflow.com/a/49389695
type: Comment

http://stackoverflow.com/q/49366548
favorite count: 0
has answer: http://stackoverflow.com/a/49366687
type: Question
has title: Delete JSON Objects Where Certain Keys Have Empty Values
accepted answer: http://stackoverflow.com/a/49366738
score: 3
tagged with: http://stackoverflow.com/tag/json
answer count: 5
has answer: http://stackoverflow.com/a/49366738
has answer: http://stackoverflow.com/a/49366815
has answer: http://stackoverflow.com/a/49366758
has comment: http://stackoverflow.com/comment/85733927
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/11277432
linked to: http://stackoverflow.com/q/1602934
downvote count: 0
tagged with: python
has body: I have a json as follows: [{ "Domain": "google.com", "A": ["172.217.22.46"], "AAAA": ["2a00:1450:4001:81e::200e"], "CAA": ["0 issue \"pki.goog\""], "MX": ["20 alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.", "10 aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com."], "NS": ["ns1.google.com.", "ns3.google.com.", "ns2.google.com.", "ns4.google.com."], "SOA": ["ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60"], "TXT": ["\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\"", "\"v=spf1 include:_spf.google.com ~all\""], "Country": ["United States"], "Hostname": ["'fra15s16-in-f46.1e100.net'"], "SSL": ["Google Internet Authority G2"], "WHOIS": [8400], "TTL": ["24"] }, { "Domain": "", "NS": ["a.root-servers.net.", "h.root-servers.net.", "g.root-servers.net.", "i.root-servers.net.", "d.root-servers.net.", "k.root-servers.net.", "c.root-servers.net.", "l.root-servers.net.", "e.root-servers.net.", "m.root-servers.net.", "f.root-servers.net.", "j.root-servers.net.", "b.root-servers.net."], "SOA": ["a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400"], "A": [], "SSL": ["None"], "WHOIS": [0], "TTL": [null] }, { "Domain": "facebook.com", "A": ["157.240.20.35"], "AAAA": ["2a03:2880:f11c:8183:face:b00c:0:25de"], "MX": ["10 msgin.vvv.facebook.com."], "NS": ["a.ns.facebook.com.", "b.ns.facebook.com."], "SOA": ["a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300"], "TXT": ["\"v=spf1 redirect=_spf.facebook.com\""], "Country": ["United States"], "Hostname": ["'edge-star-mini-shv-02-frt3.facebook.com'"], "SSL": ["DigiCert SHA2 High Assurance Server CA"], "WHOIS": [10227], "TTL": ["173"] }] Please note the second element, the one that has "Domain" : "", which I want to remove(there maybe multiple instances where "Domain" : "" is like that, this is only partial JSON) and return a valid json devoid of that whole object, so the output must look like: [{ "Domain": "google.com", "A": ["172.217.22.46"…
has comment: http://stackoverflow.com/comment/85733993
has answer: http://stackoverflow.com/a/49366702
possible better answer: http://stackoverflow.com/a/49366758

http://stackoverflow.com/q/49396094
has comment: http://stackoverflow.com/comment/85794124
has body: I'm writing the following as a test case in C++: using namespace boost::algorithm; static PyObject* strtest(PyObject* self, PyObject* args) { std::string s = "Boost C++ Libraries"; to_upper(s); PyObject * python_val = Py_BuildValue("s", s); return python_val; } The code compiles and imports, but produces what looks like a reference to a memory location. &gt;&gt;&gt; math_demo.strtest() ' X\x0e' I was expecting 'BOOST C++ LIBRARIES' as a return value What am I missing? Thanks
favorite count: 0
type: Question
tagged with: c++
score: 5
tagged with: boost
answer count: 1
has title: returning a variable string in Py_BuildValue
downvote count: 0
has answer: http://stackoverflow.com/a/49416005
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85819365
upvote count: 5
accepted answer: http://stackoverflow.com/a/49416005
tagged with: python

http://stackoverflow.com/q/49439459
has answer: http://stackoverflow.com/a/49468871
tagged with: pythonanywhere
tagged with: web2py
has body: I am a beginner and have been using web2py on the online webapp form in pythonanywhere. I wish to use the googlemaps api however I'm not sure how to install the modules. On my local python I just installed it through terminal, however I am not sure how to do it on pythonanywhere online. Any help would be appreciated :D.
type: Question
tagged with: python
answer count: 1
has title: How to import external module/library in web2py pythonanywhere
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49468871

http://stackoverflow.com/q/49416790
type: AnsweredQuestion
has body: I am trying, using Qt classes QWebEngineView, and QWebChannel to make a simple connection between HTML page and Python script. The goal is simply to execute foo() when the header is clicked. import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication from PyQt5.QtWebChannel import QWebChannel from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage html = ''' Header. ''' class HelloWorldHtmlApp(QWebEngineView): def __init__(self): super().__init__() # setup a page with my html my_page = QWebEnginePage(self) my_page.setHtml(html) self.setPage(my_page) # setup channel self.channel = QWebChannel() self.channel.registerObject('backend', self) self.page().setWebChannel(self.channel) self.show() @pyqtSlot() def foo(self): print('bar') if __name__ == "__main__": app = QApplication.instance() or QApplication(sys.argv) view = HelloWorldHtmlApp() view.show() app.exec_() The problem seems to be that the variable backend is not visible outside of the QWebChannel constructor. I tried to make backend an attribute of widnow to make it global but it did not work.
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49416885
upvote count: 10
favorite count: 0
type: Question
has title: PyQt QtWebChannel: calling Python function from JavaScript
accepted answer: http://stackoverflow.com/a/49416885
tagged with: qwebengineview
score: 10
tagged with: python
tagged with: qtwebchannel

http://stackoverflow.com/q/49353536
has body: This is my code: img = cv2.imread(some_path, 0) Original image: After running the code: Obviously losing a lot of transparency.
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49353611
favorite count: 0
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/49353611
tagged with: python
has title: How can I convert an image to grayscale without losing any transparency?

http://stackoverflow.com/comment/85770868
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49366952
has text: I had the post formatted incorrectly before. I fixed it now. Not sure why it doesn't work. Any help would be appreciated.

http://stackoverflow.com/a/75755900
answers question: http://stackoverflow.com/q/49425985
has body: If you want exactly default NULL in your SQL, you may define the column as follow: name = Column(String(32), server_default=sqlalchemy.sql.elements.TextClause('NULL'))
type: Answer
score: 0

http://stackoverflow.com/comment/85878399
score: 0
has text: @Code-Apprentice I just realized that myself . . . I have found a working solution for me, but I'll leave this question up in the hopes that it will be useful to someone else.
comment on: http://stackoverflow.com/q/49437751
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85739777
comment on: http://stackoverflow.com/q/49369364
type: QuestionComment
type: Comment
score: 4
has text: You're already using the `command` argument, so I think you already know how to do things in response to mouse clicks. So the question isn't "how do I open a youtube video in response to a mouse click?", it's "How do I make Python open a Youtube video?". In fact, this has nothing to do with Tkinter at all.

http://stackoverflow.com/a/49427712
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I'm guessing what you mean is have the number of nestings be variable according to a string like 'a.b.c': d = {"a":{"b":{"c":"value"}}} dotted = 'a.b.c' paths, current = dotted.split('.'), d for p in paths[:-1]: current = current[p] current[paths[-1]] = encrypt(current[paths[-1]]) this will modify the given dictionary d to be {"a":{"b":{"c":"whatever the encrypted value is"}}}
answers question: http://stackoverflow.com/q/49427002
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49427002

http://stackoverflow.com/comment/87499092
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49339355
score: 0
has text: I get the following error when I do that - ValueError: Dimension 0 in both shapes must be equal, but are 3 and 32. Shapes are [3,3,20,32] and [32,3,3,3]. for 'Assign_890' (op: 'Assign') with input shapes: [3,3,20,32], [32,3,3,3].

yelp
tags question: http://stackoverflow.com/q/49373125
type: Tag
tag name: yelp

http://stackoverflow.com/q/49411679
has body: Problem In my recurrent model (sequential binary classifier) at each time step t I need to perform the following input transformation: [32 x 4] --&gt; [32 x 100] So, if my sequence length is 3, I should have: [32 x 4] --&gt; [32 x 100] [32 x 4] --&gt; [32 x 100] [32 x 4] --&gt; [32 x 100] I do it by applying linear transform xW + b on [32 x 4] tensor at each time step t. My working Torch implementation of the model shows the mean of linear weigths change each epoch: Epoch #1 0.0012639100896195 0.0012639100896195 0.0012639100896195 Epoch #2 0.0039414558559656 0.0039414558559656 0.0039414558559656 Epoch #3 -0.0099147083237767 -0.0099147083237767 -0.0099147083237767 The backward pass updates the weights, everything works. However, when I attempt to do the same in Tensorflow the mean stay the same or updated very slightly at each epoch: Epoch: 1 &gt; lr update: 0.0497500005 #################### DEBUGGING #################### 0.051794354 Model/input_layer2/linear_weigth:0 0.06118914 Model/input_layer2_bias/linear_bias:0 Epoch: 2 &gt; lr update: 0.049500001 #################### DEBUGGING #################### 0.051794227 Model/input_layer2/linear_weigth:0 0.06118797 Model/input_layer2_bias/linear_bias:0 Epoch: 3 &gt; lr update: 0.0492500015 #################### DEBUGGING #################### 0.051794235 Model/input_layer2/linear_weigth:0 0.06118701 Model/input_layer2_bias/linear_bias:0 Tensorflow linear implementation is very simple: def linear(input) return tf.add(tf.matmul(input, self.linear_weight), self.linear_bias) expanded = [linear(batch_seq) for batch_seq in unstacked_input] Both self.linear_weight and self.linear_bias are trainable and are initialized as tf.Variables during graph construction. Both Torch and TF models use identical training datasets, hyperparameters. Torch and TF model size (number of params) are the same as well. Needless to say that Torch model trains and shows good results on test data while TF model does not train at all. Question: Since I am …
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85827255
has comment: http://stackoverflow.com/comment/85865889
tagged with: python
linked to: http://stackoverflow.com/q/48816873
favorite count: 0
score: 2
type: AnsweredQuestion
answer count: 1
tagged with: tensorflow
has title: Tensorflow does not update linear weights during backpropagation
type: Question
accepted answer: http://stackoverflow.com/a/49432044
has answer: http://stackoverflow.com/a/49432044
upvote count: 2

http://stackoverflow.com/q/49345876
has comment: http://stackoverflow.com/comment/85692093
linked to: http://stackoverflow.com/q/21581824
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49345937
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/8312829
possible better answer: http://stackoverflow.com/a/49345906
duplicate of: http://stackoverflow.com/q/45946228
has answer: http://stackoverflow.com/a/49345906
has comment: http://stackoverflow.com/comment/85691786
accepted answer: http://stackoverflow.com/a/49345937
tagged with: python
has comment: http://stackoverflow.com/comment/85691708
has comment: http://stackoverflow.com/comment/85692104
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85692095
has body: I was expecting vowel free string from the code below but it doesn't give me what I'm expecting. Help please. def disemvowel(word): words = list(word) for i in words: if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U": words.remove(i) return print(''.join(words)) disemvowel("uURII") I was expecting the output to be 'R' but I'm getting 'URI'.
has comment: http://stackoverflow.com/comment/85692071
has comment: http://stackoverflow.com/comment/85692123
has title: Removing vowels from the string python
linked to: http://stackoverflow.com/q/8312829
has comment: http://stackoverflow.com/comment/85691683
upvote count: 1

http://stackoverflow.com/q/49316237
tagged with: python
has comment: http://stackoverflow.com/comment/85665526
has answer: http://stackoverflow.com/a/49316854
tagged with: ocr
answer count: 2
has title: Enhancement of Image for OCR
score: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/85664477
downvote count: 1
has answer: http://stackoverflow.com/a/49343229
favorite count: 0
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/23506105
has body: [This is a sample image] I want to crop out the header Text for several other similar colored images like this for OCR. what are the most effective steps to preprocess the image for better recognition only for the header text.

http://stackoverflow.com/q/49348617
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
has body: I am doing some image processing in Python and I would like to plot 4 images (they are all 224x224x3 np arrays) in one figure, add some titles and save the whole figure as png. Obviously, I can do this using plt and subplot: f, axs = plt.subplots(2, 2) ax = axs[0, 0] ax.imshow(img1) ax.axis('off') ax.set_title('original') ax = axs[1, 0] ax.imshow(img2) ax.axis('off') ax.set_title('blur + noise') ax = axs[0, 1] ax.imshow(img3) ax.axis('off') ax.set_title('restored a') ax = axs[1, 1] ax.imshow(img4) ax.axis('off') ax.set_title('restored b') However this will apply scaling to the different images and I would like to display the images in their original resolution without any interpolation being applied. Is there any way to achieve this behaviour in plt? I found some other thread that asked a similar question, however it only answers how to display one single image without scaling. Thanks for your help, Max
type: Question
linked to: http://stackoverflow.com/q/44346033
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/49353996
has answer: http://stackoverflow.com/a/49353996
type: AnsweredQuestion
has title: Python: Showing multiple images in one figure WITHOUT scaling

http://stackoverflow.com/q/49313924
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49313976
has body: I can sum the first 310 rows in a 5 column pandas dataframe and get a tidy summary by using: df.[0:310].sum Is there an easy way whereby I can sum the first 310 rows in a certain column of my choosing? I just can't figure out how to combine a column selection and row slice selection in the expression. It would be ideal to specify the column by column name, but column index is fine too. In an attempt to sum the 1st 310 rows of the 5th column, I tried df.iloc[0:310, 4].sum but just got a printout of 310 rows from that column. Thank you.
score: 3
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 0
has title: Sum only certain rows in a given column of pandas dataframe
has answer: http://stackoverflow.com/a/49314256
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85608479
type: Comment
has text: Define what "unsuccessful" means. Have you verified that quotes are not getting stripped, or is the final result just not what you want?
comment on: http://stackoverflow.com/q/49303116
score: 0
type: QuestionComment

http://stackoverflow.com/q/49352561
tagged with: gamepad
upvote count: 2
has body: I'm working with Ubuntu in vm and I want to send joystick inputs with Python script to other program. Basically the same thing as https://pythonprogramming.net/direct-input-game-python-plays-gta-v/?completed=/open-cv-basics-python-plays-gta-v/ but with only joystick/gamepad. :)
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85713423
tagged with: joystick
tagged with: ubuntu
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/57962941
has comment: http://stackoverflow.com/comment/85708859
has title: Sending Joystick input to program using python
tagged with: input
tagged with: python
score: 2

http://stackoverflow.com/q/49364174
type: AnsweredQuestion
tagged with: python
score: -1
has body: We want to program multiple neural networks in Python with Tensorflow, which have to make use of the same weighting matrices and biases across those networks. We already saw examples of using the same variables in different layers but that is not the case here. Which method is most suitable to use in this situation?
type: Question
accepted answer: http://stackoverflow.com/a/49366181
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49366181
has title: Use same variables in multiple neural networks with tensorflow
downvote count: 2
answer count: 1
tagged with: neural-network
upvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/49356867
has body: I'm building a dedicated OAuth2 as a service for my application, where users will be both authenticating and authorizing themselves. I've the following concerns 1) Is OAuth2 TokenScope similar to Django Permissions? 2) If I want to make role-level hierarchy application, how do I go about building one with OAuth2?
score: 1
downvote count: 0
tagged with: django-permissions
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53847566
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Is OAuth2 TokenScope similar to Django Permissions?
tagged with: django-oauth

http://stackoverflow.com/a/49421649
has body: Don't. Simply move both .py files to the same directory and simply use: import my_file Alternatively, you can move your .py file to your site-packages folder.
has comment: http://stackoverflow.com/comment/85844238
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49421465
type: Answer
score: -1

http://stackoverflow.com/q/49397153
has comment: http://stackoverflow.com/comment/85796458
has comment: http://stackoverflow.com/comment/85798519
has comment: http://stackoverflow.com/comment/85796289
tagged with: python
has title: Check if something is raisable in any version
accepted answer: http://stackoverflow.com/a/49397259
has comment: http://stackoverflow.com/comment/85796614
possible better answer: http://stackoverflow.com/a/49397270
has comment: http://stackoverflow.com/comment/85796546
has answer: http://stackoverflow.com/a/49397259
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49397270
score: 3
answer count: 3
tagged with: exception
has comment: http://stackoverflow.com/comment/85796135
upvote count: 3
has comment: http://stackoverflow.com/comment/85796266
has comment: http://stackoverflow.com/comment/85796468
has answer: http://stackoverflow.com/a/49397260
has comment: http://stackoverflow.com/comment/85813916
has body: I was working on a project where we wanted to validate that a parameter could actually be raised as an exception if necessary. We went with the following: def is_raisable(exception): funcs = (isinstance, issubclass) return any(f(exception, BaseException) for f in funcs) This handles the following use cases, which meet our needs (for now): is_raisable(KeyError) # the exception type, which can be raised is_raisable(KeyError("key")) # an exception instance, which can be raised It fails, however, for old-style classes, which are raisable in old versions (2.x). We tried to then solve it this way: IGNORED_EXCEPTIONS = [ KeyboardInterrupt, MemoryError, StopIteration, SystemError, SystemExit, GeneratorExit ] try: IGNORED_EXCEPTIONS.append(StopAsyncIteration) except NameError: pass IGNORED_EXCEPTIONS = tuple(IGNORED_EXCEPTIONS) def is_raisable(exception, exceptions_to_exclude=IGNORED_EXCEPTIONS): funcs_to_try = (isinstance, issubclass) can_raise = False try: can_raise = issubclass(exception, BaseException) except TypeError: # issubclass doesn't like when the first parameter isn't a type pass if can_raise or isinstance(exception, BaseException): return True # Handle old-style classes try: raise exception except TypeError as e: # It either couldn't be raised, or was a TypeError that wasn't # detected before this (impossible?) return exception is e or isinstance(exception, TypeError) except exceptions_to_exclude as e: # These are errors that are unlikely to be explicitly tested here, # and if they were we would have caught them before, so percolate up raise except: # Must be bare, otherwise no way to reliably catch an instance of an # old-style class return True This passes all of our tests, but it isn't very pretty, and still feels hacky if we're considering things that we wouldn't expect the user to pass in, but might be thrown in there anyway for some other reason. def test_is_raisable_exception(self): """Test that an exception is raisable.""" self.assertTrue(is_raisable(Exc…
tagged with: python-2.x
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85796111
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85796527
has comment: http://stackoverflow.com/comment/85796285
has comment: http://stackoverflow.com/comment/85796236
has comment: http://stackoverflow.com/comment/85796191
downvote count: 0
has comment: http://stackoverflow.com/comment/85796331

http://stackoverflow.com/comment/85880825
score: 0
comment on: http://stackoverflow.com/q/49439158
type: Comment
type: QuestionComment
has text: What is your desired output? In actual output / text as part of your question, please, not description.

http://stackoverflow.com/comment/85577019
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49286472
type: Comment
has text: To add to @abarnert's comment: `repr` in Python is equivalent to `dput` in R.

http://stackoverflow.com/comment/85840087
type: Comment
type: AnswerComment
has text: What would happen if I re-created the projection layer... Would that have an effect on the accuracy of my model... I am using a bidirectional dynamic encoder and a decoder as the core of the model... I am trying to make a chatbot
score: 0
comment on: http://stackoverflow.com/a/49416567

http://stackoverflow.com/q/49291984
has answer: http://stackoverflow.com/a/49292601
type: Question
tagged with: python-3.x
has body: I am trying to add two modifications to the standard algorithm. My strings are text and case sensitive. Say I have a word "cage". The hamming distance between "cage" and "Cage" would be 0 (first letter). Any other letter would be 0.5. (say, "cage" and "cAge". Two, "cage" and "caKe" would be 1.5 (different letter=1 plus different caps =0.5), Three, "cake" and "caqe" would be 0 (consider k and q to be same letter). Same rules apply for longs sentences too. (say "Happy Birthday" and "happy BudthDay" distance = 1+1+0.5=2.5) I would like to pass in any set of words/sentences and modified algorithm instead of standard algorithm needs to be applicable. I have written a sample code in python for case 1 but unable to understand how to move forward with capitalization. def editDistance(str1, str2): if str1[1]==str2[1]: return editDistance(str1,str2) print editDistance(str1, str2, len(str1), len(str2)) PS: Any explanation in R would be great too.
has comment: http://stackoverflow.com/comment/85586568
tagged with: python
has comment: http://stackoverflow.com/comment/85586632
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has title: modify edit distance algorithm between two text strings in python
score: 0
tagged with: hamming-distance
accepted answer: http://stackoverflow.com/a/49292601
answer count: 1

http://stackoverflow.com/a/49382903
has body: I may be wrong but you are missing an in statement or say iteration in your list comprehension. my_list = [(1, 1), (1, 0)] correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in my_list] print(correct) out: [1, 0]
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49382766
type: Answer
answers question: http://stackoverflow.com/q/49382766
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85648888
comment on: http://stackoverflow.com/q/49323740
has text: @khelwood They should be, as it's all table data.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85656201
has text: From the [python 3 docs for `set`](https://docs.python.org/3/tutorial/datastructures.html#sets), the examples seem to indicate that items are not sorted. You have explicitly sort the values before the join here.
score: 0
comment on: http://stackoverflow.com/a/49327103
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49437653
has comment: http://stackoverflow.com/comment/85877252
downvote count: 0
has comment: http://stackoverflow.com/comment/85877364
has title: python arbitrary slicing using a function
score: 2
has answer: http://stackoverflow.com/a/49437755
tagged with: list
has answer: http://stackoverflow.com/a/49437703
tagged with: python
favorite count: 0
type: Question
answer count: 2
has body: I'm trying to make a function that can make an abitrary slice of a list eg: def slice(arr, a, b, step): return arr[a:b:step] The problem is, how to handle if a user wants the slice arr[5:] or arr[:5] in a nice way?
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/49399090
tagged with: python
tagged with: regex
type: Question
score: 2
upvote count: 3
has body: I am getting bad character range for the following pattern. why? Please correct it "^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)"
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49399137
favorite count: 0
type: AnsweredQuestion
has title: Bad character range in python
accepted answer: http://stackoverflow.com/a/49399137

http://stackoverflow.com/comment/85634840
comment on: http://stackoverflow.com/a/49316818
has text: too fast too furious your response! :)
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/49407127
downvote count: 0
score: 2
type: Answer
has body: np.searchsorted labels = np.array(['1-6 days', '7-14 days', '&gt;14 days']) bins = np.array([7, 14]) df.assign(Day_Group=labels[bins.searchsorted(df.days)]) days Day_Group 1 3.0 1-6 days 2 4.6 1-6 days 3 14.9 &gt;14 days 4 7.1 7-14 days 5 15.1 &gt;14 days 6 109.0 &gt;14 days
answers question: http://stackoverflow.com/q/49406669
upvote count: 2

http://stackoverflow.com/a/49355269
score: 3
has body: You can use rjust: &gt;&gt;&gt; def Left_padded(n, width): ... return str(n).rjust(width) &gt;&gt;&gt; Left_padded(54, 5) ' 54'
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49355224
downvote count: 1

http://stackoverflow.com/q/49301317
type: Question
has answer: http://stackoverflow.com/a/49346243
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85605140
tagged with: pybind11
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/85605668
score: 1
has title: Pybind11: Passing a Python list to C-style array
tagged with: arrays
answer count: 1
downvote count: 0
upvote count: 1
has body: I would like to pass a Python list to a constructor which takes C-style arrays. How should that work. The problem is that the C-style array is essentially a pointer. Furthermore, the array has dimension n x n, i.e. it is a multi-dimensional array. PYBIND11_MODULE(matrix_class_bind, m){ py::class_&lt;matrix_class&lt;double&gt;&gt;(m, "matrix_class") .def(py::init([](double x[3][3]){ matrix_class&lt;double&gt; new_class(x); return new_class;})); } On the python side it should be something like: import matrix_class_bind as mcb a = [[1,2,3], [3,4,5], [1,1,1]] mcb.matrix_class(a)
favorite count: 0

http://stackoverflow.com/a/49340417
has body: In short, you cannot patch the builtins func hasattr patch('builtins.hasattr', return_value=False) reason: used by mock.py if not _is_started(self): raise RuntimeError('stop called on unstarted patcher') def _is_started(patcher): # XXXX horrible return hasattr(patcher, 'is_local') to repeat the error: @mock.patch('__builtin__.hasattr') def test_mock_hasattr(self, mocked_hasattr): # as long as it is set to False, it will trigger mocked_hasattr.return_value = False to mock a builtins func inside models.py: # narrow the mock scope @mock.patch('orders.models.hasattr')
has comment: http://stackoverflow.com/comment/85693360
has comment: http://stackoverflow.com/comment/85696083
has comment: http://stackoverflow.com/comment/85698589
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49334774
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49334774
score: 2

http://stackoverflow.com/q/49318345
has answer: http://stackoverflow.com/a/49319260
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/73769781
tagged with: pandas
has comment: http://stackoverflow.com/comment/85640830
has answer: http://stackoverflow.com/a/73769781
favorite count: 0
type: Question
upvote count: 4
has title: Index sort order of a multi-index dataframe does not respect categorical index order
answer count: 2
accepted answer: http://stackoverflow.com/a/49319260
downvote count: 0
has body: A small dataframe with a two level multiindex and one column. The second column(level 1) of the index will sort in alphabetical order putting 'Four' before 'Three'. import pandas as pd df = pd.DataFrame({'A':[1,1,2,2], 'B':['One','Two','Three', 'Four'], 'X':[1,2,3,4]}, index=range(4)).set_index(['A','B']).sort_index() df X A B 1 One 1 Two 2 2 Four 4 Three 3 Clearly the second level of the index (B) is in alphabetical order so this can be replaced with a categorical index to force the correct ordering. df.index.set_levels(pd.CategoricalIndex(df.index.levels[1], categories=['One','Two','Three', 'Four'], ordered=True), level=1, inplace=True) With this done inspecting the index shows that level 1 is indeed a categorical index. But sorting the index does not put the rows in the desired order. df.sort_index() X A B 1 One 1 Two 2 2 Four 4 Three 3 Note: If the the dataframe has a simple index of 1 level only this works as expected.
tagged with: python
score: 4

http://stackoverflow.com/q/49355297
type: Question
tagged with: nonblocking
has answer: http://stackoverflow.com/a/49468070
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85737633
tagged with: asynchronous
has body: When it comes to IO read/write files from disks, it is almost blocking operations by default. I have been working on a project that uses such operations (read/write from disks) and uses the default numpy blocking IO here. This has been a great pick until I found out that I am dealing with really big datasets!! I have been trying to improve the execution time of my project. After doing a benchmark, I found out that IO operations are the bottleneck. Thus, I should now think of something else other than numpy default blocking IO. After reading for few days, I found out that I have three approaches to choose from that could reduce IO time: Non-blocking approach Multi-threading approach Multi-processing approach I would like to know which one of these approaches will be suitable to reduce the IO time, knowing that my IO operations are always performed on a disk (local disk). Plenty of libraries I came across such as twisted, asyncio, aiofiles, multiprocessing, and multithreading. Because I have never worked with IO asynchronous or events-driven networking before, I am not sure what to choose from the three approaches above!! Suggestions and thoughts from you guys are valuable to me. Thank you in advance EDIT: Special thanks to mobiusklein who brought the following points: Does your program need all its data loaded before it can begin? Yes, but sometimes the program needs only to load a portion of the data from a file. Can it start writing some data to disk before all of the work is complete? Yes, this is in fact what I am looking for. Does the "work" function ever release the GIL? I don't get this question but my program makes use of multiprocessors via the library mpi4py. However, IO operations are always done by a single processor.
score: 0
has title: Choosing the right approach to reduce IO operation
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/85710962
tagged with: multiprocessing

http://stackoverflow.com/comment/85732237
type: QuestionComment
has text: You can use `heapq.nlargest` and `heapq.nsmallest` instead of slicing to get your two halves, then use `heapq.heapify` to rebuild the queue from the two halves.
comment on: http://stackoverflow.com/q/49365432
score: 1
type: Comment

http://stackoverflow.com/a/49387302
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49386402
type: Answer
answers question: http://stackoverflow.com/q/49386402
has body: Based on my experience I would recommend Amazon Web Services: https://aws.amazon.com/. I would suggest for you to look about creating an EC2 Instance and run your code there. An EC2 Instance basically is some kind of server and you can automate your Python script there as well. Now, there's this tutorial that helped me a lot to have a clearer image about running Python script using AWS (specifically EC2): https://www.youtube.com/watch?v=WE303yFWfV4. For further informations about Cloud Services in Amazon and products, you can get informations here: https://aws.amazon.com/products/.

http://stackoverflow.com/comment/85783823
comment on: http://stackoverflow.com/a/49390970
type: Comment
score: 0
type: AnswerComment
has text: @Petr, general solutions as usually more useful over time. Hopefully others will find it useful. Cheers.

http://stackoverflow.com/q/49400543
has answer: http://stackoverflow.com/a/59808114
has comment: http://stackoverflow.com/comment/85802426
possible better answer: http://stackoverflow.com/a/59808114
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85817295
downvote count: 1
accepted answer: http://stackoverflow.com/a/49402986
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85816920
upvote count: 0
answer count: 2
has title: Using matplotlib to generate 3D surfaces from 2D matrices
has body: Using a 2d matrix in python, how can I create a 3d surface plot, where columns=x, rows=y and the values are the heights in z? I can't understand how to creat 3D surface plot using matplotlib. Maybe it's different from MatLab. example: from pylab import * from mpl_toolkits.mplot3d import Axes3D def p(eps=0.9, lmd=1, err=10e-3, m=60, n=40): delta_phi = 2 * np.pi / m delta_lmd = 2 / n k = 1 P0 = np.zeros([m + 1, n + 1]) P = np.zeros([m + 1, n + 1]) GAP = 1 while GAP &gt;= err: k = k + 1 for i in range(0, m): for j in range(0, n): if (i == 1) or (j == 1) or (i == m + 1) or (i == n + 1): P[i,j] = 0 else: A = (1+eps*np.cos((i+1/2)*delta_phi))**3 B = (1+eps*np.cos((i-1/2)*delta_phi))**3 C = (lmd*delta_phi/delta_lmd)**2 * (1+eps*np.cos((i)*delta_phi))**3 D = C E = A + B + C + D F = 3*delta_phi*((1+eps*np.cos((i+1/2)*delta_phi))-(1+eps*np.cos((i-1/2)*delta_phi))) P[i,j] = (A*P[i+1,j] + B*P[i-1,j] + C*P[i,j+1] + D*P[i,j-1] - F)/E if P[i,j] &lt; 0: P[i,j] = 0 S = P.sum() - P0.sum() T = P.sum() GAP = S / T P0 = P.copy() return P, k def main(): start = time.time() eps = 0.9 lmd = 1 err = 10e-8 m = 60 n = 40 P, k = p() fig = figure() ax = Axes3D(fig) X = np.linspace(0, 2*np.pi, m+1) Y = np.linspace(-1, 1, n+1) X, Y = np.meshgrid(X, Y) #Z = P[0:m, 0:n] #Z = Z.reshape(X.shape) ax.set_xticks([0, np.pi/2, np.pi, np.pi*1.5, 2*np.pi]) ax.set_yticks([-1, -0.5, 0, 0.5, 1]) ax.plot_surface(X, Y, P) show() if __name__ == '__main__': main() ValueError: shape mismatch: objects cannot be broadcast to a single shape And the pic pic by matplotlic And I also use MatLab to generate,the pic: pic by MatLab
has answer: http://stackoverflow.com/a/49402986
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85802546

http://stackoverflow.com/comment/85564421
comment on: http://stackoverflow.com/q/49280714
has text: Oh wow. What a mistake haha. I didn't even think about that... Thank you both so much. I will be fixing the above post, but now that I have fixed it and ran it, the script isn't looping, it only returns and prints the first proxy. Any suggestions?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49319836
type: AnsweredQuestion
has body: I just came across googletrans python package. This package translates quite well and seems to use google translation API. To my knowledge, google translation API is not free. What googletrans doing internally for the translations? Is it legal to use googletrans?
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Python googletrans
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49319979
accepted answer: http://stackoverflow.com/a/49319979
tagged with: googletrans
tagged with: python
has comment: http://stackoverflow.com/comment/85640574
tagged with: google-translate

http://stackoverflow.com/a/49435460
type: AcceptedAnswer
downvote count: 0
has body: You need to pass it to both functions as a parameter: class Testy(object): def mymet(self, x): print("This is the value of x in Testy %d: " % x) class Sandy(Testy): def run(self, x): print("This is value of x in Sandy: %d" % x) super(Sandy, self).mymet(x) if __name__ == "__main__": x = 4 test = Sandy() test.run(x)
answers question: http://stackoverflow.com/q/49435348
upvote count: 2
has comment: http://stackoverflow.com/comment/85873119
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85873408
accepted answer of: http://stackoverflow.com/q/49435348

http://stackoverflow.com/q/49359791
type: AnsweredQuestion
score: 0
has body: I've been trying to write a code for Fibonacci using memorization on Python. Here's my code def fib(n, memo): if memo[n] is not None: return memo[n] if n == 1 or n == 2: result = 1 else: result = fib_2(n-1, memo) + fib_2(n-2, memo) memo[n] = result return result def fib_memo(n): memo = [None] * (n + 1) return fib(n, memo) t = input("number ") print(fib_memo(t)) It returns:- TypeError: must be str, not int" on line 17- memo = [None] * (n + 1) I can't seem to understand the issue here.
has comment: http://stackoverflow.com/comment/85719743
has comment: http://stackoverflow.com/comment/85719720
favorite count: 0
has answer: http://stackoverflow.com/a/49359906
type: Question
upvote count: 2
downvote count: 2
tagged with: arrays
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49359906
has title: TypeError: must be str, not int; Python

flask-sqlalchemy
tags question: http://stackoverflow.com/q/49372413
tags question: http://stackoverflow.com/q/49413062
tags question: http://stackoverflow.com/q/49395490
tags question: http://stackoverflow.com/q/49391192
type: Tag
tags question: http://stackoverflow.com/q/49414667
tags question: http://stackoverflow.com/q/49333656
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/49409691
tags question: http://stackoverflow.com/q/49382913
tags question: http://stackoverflow.com/q/49396485
tags question: http://stackoverflow.com/q/49339600
tags question: http://stackoverflow.com/q/49357971
tags question: http://stackoverflow.com/q/49394150

http://stackoverflow.com/q/49333036
has comment: http://stackoverflow.com/comment/85673955
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: match
has comment: http://stackoverflow.com/comment/85760885
has answer: http://stackoverflow.com/a/49333666
has comment: http://stackoverflow.com/comment/85667862
has title: Check in python if self designed pattern matches
linked to: http://stackoverflow.com/q/8055727
answer count: 3
has body: I have a pattern which looks like: abc*_def(##) and i want to look if this matches for some strings. E.x. it matches for: abc1_def23 abc10_def99 but does not match for: abc9_def9 So the * stands for a number which can have one or more digits. The # stands for a number with one digit I want the value in the parenthesis as result What would be the easiest and simplest solution for this problem? Replace the * and # through regex expression and then look if they match? Like this: pattern = pattern.replace('*', '[0-9]*') pattern = pattern.replace('#', '[0-9]') pattern = '^' + pattern + '$' Or program it myself?
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49333816
tagged with: regex
has answer: http://stackoverflow.com/a/49336508
has comment: http://stackoverflow.com/comment/85667880
favorite count: 0
type: Question

http://stackoverflow.com/comment/85858334
has text: one way to debug would be to try to read `p.stdout` (standard output), and check return code returned by `p.wait()`. Also, try to get rid of `shell=True` if possible (try `where php` on windows and `which php` on Linux, those may be 2 different object types (.bat/.exe...)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49428562

http://stackoverflow.com/comment/85686185
comment on: http://stackoverflow.com/a/49281306
score: 0
has text: @Jean-FrançoisFabre MS Word? Nah. If an answer is too complicated to edit in-place I use emacs markdown-mode (configured for SO markdown) of course. But sadly, I don’t have that on my phone or tablet. And the iOS virtual keyboard doesn’t have a meta key, for some reason I can’t comprehend. :)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52828260
answers question: http://stackoverflow.com/q/49367716
has body: I had the same issue. I solved it by placing two dlls in the same folder as my .exe file. The dlls are "api-ms-win-downlevel-shlwapi-l1-1-0.dll" which can be downloaded from the internet and other one is "opencv_ffmpeg***_**.dll" which can be found in python site-packages if you have installed python-opencv via pip, where *** is the version and ** is 32 or 64 bit. After you have gathered these two files, compile the script using following options. pyinstaller -w script.py Now place the two dlls in dist/your_folder/ where the .exe is located. Also be careful of all the warnings related to missing dlls while compiling, if you see any warning related to missing dlls, place that dll in .exe folder afterward.
has comment: http://stackoverflow.com/comment/108117570
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85952104
comment on: http://stackoverflow.com/a/49462054
type: Comment
has text: Assist in that question in the link. https://stackoverflow.com/questions/49473984/how-do-i-automate-this-process-of-capturing-detected-faces-and-adding-to-the-dat
score: 0
type: AnswerComment

http://stackoverflow.com/a/73769781
score: 0
has body: If you check the index (level=1) after defining the dataframe and using set_levels(), you will see that its values are sorted lexicographically. print(df.index.levels[1]) output: CategoricalIndex(['Four', 'One', 'Three', 'Two'], categories=['One', 'Two', 'Three', 'Four'], ordered=True, dtype='category', name='B') You can see that ['Four', 'One', 'Three', 'Two'] is lexicographically ordered. Categorical index sorting fails with lexicographically ordered data. Several tricks can be used to solve this problem in these cases. You can first reset the index using reset_index(). Then you can make a CategoricalIndex and use it to categorize the column. order = ['One','Two','Three', 'Four'] df.reset_index(inplace=True) df['B'] = pd.CategoricalIndex(df['B'], order, ordered=True) df = df.sort_values(['A','B']).set_index(['A','B']) print(df.index.levels[1]) df output: CategoricalIndex(['One', 'Two', 'Three', 'Four'], categories=['One', 'Two', 'Three', 'Four'], ordered=True, dtype='category', name='B') X A B 1 One 1 Two 2 2 Three 3 Four 4 You can see that ['One', 'Two', 'Three', 'Four'] is lexicographically ordered. You can first create a CategoricalIndex and assign it to the level_1 of the MultiIndex. Afterward, you need to eliminate the lexicographical sort from the one-level index. You can use two swaplevel() -&gt; sort_index() -&gt; swaplevel() here as a trick. df.index = df.index.set_levels(pd.CategoricalIndex(df.index.levels[1], order, ordered=True), level=1) df.swaplevel(1,0).sort_index(level=0).swaplevel(1,0) df output: X A B 1 One 1 Two 2 2 Three 3 Four 4 Also you can first setting types then setting index.
type: Answer
answers question: http://stackoverflow.com/q/49318345

http://stackoverflow.com/a/51446805
type: Answer
has body: I have the same problem. I didn't found a loss function that made my model to converge. So I used 3 separate model for each label. with dice loss function I had good results for each label. Now I am checking ways to unite all 3 models predictions. In your model softmax is the right activation, and binary and categorial cross entropy are same since your data is binary.
score: 0
answers question: http://stackoverflow.com/q/49388477

http://stackoverflow.com/comment/85837526
type: AnswerComment
comment on: http://stackoverflow.com/a/49415614
has text: Thanks! I was actually considering switching before reading this.
type: Comment
score: 0

http://stackoverflow.com/a/49395645
type: AcceptedAnswer
score: 5
downvote count: 0
has body: robots.txt is a standard for web crawlers, such as those used by search engines, that tells them which pages they should index. To resolve the issue, you can either host your own version of robots.txt statically, or use a package like django-robots. It's odd that you're seeing the error in development unless you or your browser is trying to explicitly access it. In production, if you're concerned with SEO, you'll likely also want to set up the webmaster tools with each search engine , example: Google Webmaster Tools https://en.wikipedia.org/wiki/Robots_exclusion_standard https://support.google.com/webmasters/answer/6062608?hl=en
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49395533
answers question: http://stackoverflow.com/q/49395533

http://stackoverflow.com/a/49434596
score: 1
answers question: http://stackoverflow.com/q/49434319
type: Answer
has body: Except for the initial 20, this produces the same values np.arange(31)*2**(1/3) Your iterative version (slightly modified) def foo0(n): f = np.zeros(n) f[0] = 20 for i in range(1,n): f[i] = f[i-1]*2**(1/3) return f An alternative: def foo1(n): g = [20] for i in range(n-1): g.append(g[-1]*2**(1/3)) return np.array(g) They produce the same thing: In [25]: np.allclose(foo0(31), foo1(31)) Out[25]: True Mine is a bit faster: In [26]: timeit foo0(100) 35 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [27]: timeit foo1(100) 23.6 µs ± 83.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) But we don't need to evaluate 2**(1/3) every time def foo2(n): g = [20] const = 2**(1/3) for i in range(n-1): g.append(g[-1]*const) return np.array(g) minor time savings. But that's just multiplying each entry by the same const. So we can use cumprod for a bigger time savings: def foo3(n): g = np.ones(n)*(2**(1/3)) g[0]=20 return np.cumprod(g) In [37]: timeit foo3(31) 14.9 µs ± 14.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [40]: np.allclose(foo0(31), foo3(31)) Out[40]: True
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85871437
accepted answer of: http://stackoverflow.com/q/49434319

http://stackoverflow.com/comment/116966912
type: Comment
has text: @NicolasGervais If you use keras around version 2.0 you will see it actually outputs (n, 1, 1, c). They changed it in later versions.
type: AnswerComment
comment on: http://stackoverflow.com/a/49299921
score: 1

http://stackoverflow.com/comment/85993738
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49452712
type: AnswerComment
has text: Hi Anthony, I passed the `conn` from `conn=pool.acquire` to `pd.read_sql` but it didn't work. I've decided to use the cursor method found on the interwebs. That does work. I've noticed though, that there is a notable delay (~20 seconds) before the large query (only) begins, unlike in the figuration in the initial post. Is this expected? Can anything be done?

http://stackoverflow.com/a/49438166
answers question: http://stackoverflow.com/q/49408422
downvote count: 0
score: 1
upvote count: 1
has body: I managd to solve my own issue with friends help... So if anyone else has the same problem, here is the solution: The new model looks like this: # from __future__ import absolute_import # from __future__ import division # from __future__ import print_function import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from math import floor, ceil from pylab import rcParams columns = ["Gender", "Age", "StepsNum", "Still", "ContinuousStill", "Running", "Driving", "Cycling", "Sleeping", "Weather", "TargetWeight", "Calories", "DayOfTheWeek", "PartOfTheDay", "NotificationType", "UserInput"] columns_train = ["Gender", "Age", "StepsNum", "Still", "ContinuousStill", "Running", "Driving", "Cycling", "Sleeping", "Weather", "TargetWeight", "Calories", "DayOfTheWeek", "PartOfTheDay", "NotificationType"] userinput = [0,1] activites_df = pd.read_csv("E:\\MASTER\\PythonPrograms\\useractivityInt.csv", header = None, names=columns, dtype=float) #encode all strings def encode(series): #print(pd.get_dummies(series.astype(str))) return pd.get_dummies(series.astype(str)) def to_float(series): return pd.to_numeric(series, downcast='float') mydict_gender = {"Male": 1, "Female": 2} mydict_weather = {"Cloudy": 1, "Clear": 2, "Foggy": 3, "Rainy": 4, "Snowy": 5, "Icy": 6} mydict_partOfTheDay = {"Morning": 1, "Noon": 2, "Afternoon": 3, "Evening": 4, "Night": 5} mydict_notificationType = {"atHome": 1, "doExercises": 2, "goToBed": 3, "getUp": 4, "goToCycling": 5, "goToRunning": 6, "goToWork": 7, "StepsGoal": 8, "takeAWalk": 9} #treba da bude matrica! train_x = pd.DataFrame(activites_df, columns = columns_train, dtype=float) # train_x = activites_df train_y = encode(activites_df.UserInput) # train_y = activites_df.iloc[:,-1] # print(train_y) # train_y = pd.DataFrame(userinput, dtype=float) train_size = 0.9 #floor - zaokruzivanje.. tran_cnt je broj podataka u csvu train_cnt = floor(train_x.shape[0] * train_size) #iloc[0] - first row, iloc[:0…
type: Answer

http://stackoverflow.com/a/49325710
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49304900
has body: Your packet is correct and should work. I have just checked with Google's public DNS server 8.8.8.8, the packet I send is 53 bytes long, the answer I get is 107. The "recursion desired" bit is activated in Scapy by default (you can enter DNS().rd and check it returns 1), so there's nothing more you need to do here. The only weird thing I can see is that you are using the source port 53, and some firewalls may filter packets with source ports &lt; 1024. You can try with a random source port see if it works better.
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49304900

http://stackoverflow.com/q/49319601
has body: I'm looking for a dbus-python equivalent of dbus-send --system --type=signal When searching for dbus-python and sending signal, all the examples involve defining a dbus service clients can connect to (eg https://github.com/zyga/dbus-python/blob/master/examples/example-signal-emitter.py) How does dbus-python allow to just simply send a signal?
has comment: http://stackoverflow.com/comment/85640757
has comment: http://stackoverflow.com/comment/85640680
linked to: http://stackoverflow.com/q/22390064
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85640363
downvote count: 0
tagged with: python
tagged with: dbus-python
score: 2
has title: dbus-python - simple example for sending a (broadcast) dbus signal
tagged with: python-2.7

http://stackoverflow.com/a/49343576
has comment: http://stackoverflow.com/comment/85687418
has comment: http://stackoverflow.com/comment/85702632
answers question: http://stackoverflow.com/q/49342847
has comment: http://stackoverflow.com/comment/85750546
has body: In order for python to detect it you must place it in the following directory. C:\Python27\ or where ever python is located.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85702617

http://stackoverflow.com/comment/85764114
score: 0
has text: @DanielRoseman api docs: https://developers.hurriyet.com.tr/docs/versions/1.0/resources/article If it shouldn't have spaces or quotes how come the postman response me with json data?
comment on: http://stackoverflow.com/q/49379532
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85837390
type: QuestionComment
has text: @abarnert Can you elaborate on this part: "For a set of new functions you create, you can create the same kind of protocol—calling f on a function first calls its __arg__ method." In other words, it's obvious how to overload things with existing `__something__` methods, but it sounds like you're pointing to a more general approach?
score: 0
comment on: http://stackoverflow.com/q/49417747
type: Comment

http://stackoverflow.com/q/49344762
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85689866
has title: Python: Create new thread or process when button is clicked
tagged with: python
has comment: http://stackoverflow.com/comment/85690197
has answer: http://stackoverflow.com/a/49350761
tagged with: tkinter
upvote count: 2
score: 2
type: UnansweredQuestion
has body: In Python 3.6.4, what is a good approach for starting a new separate process or thread on every click of a button? I have written this code but it's not working the way I want it to. from multiprocessing import process import requests import threading from tkinter import * def download(): name=entry2.get() url=entry1.get() r = requests.head(url) if name: file_name = name else: file_name = url.split('/')[-1] try: file_size = int(r.headers['content-length']) part=file_size/4 start=0 end=part except: print ("Invalid URL") return print ('%s downloaded' % file_name) def thread(url): file_name=entry2.get() r=requests.get(url) data=r.content with open('file_name','rb+')as fp: data1=fp.read() with open('file_name',"wb+") as fp: data1=fp.write(data) print("its working3") if __name__=='__main__': p=process(target=download,args=()) p.start() p.join() root=Tk() frame=Frame(root,width=500,height=450,bg="lightpink") url1=Label(frame,text="enter url here") name=Label(frame,text="enter the name of the file") url1.grid(row=0,sticky=E) name.grid(row=1,sticky=E) entry1=Entry(frame) entry2=Entry(frame) entry1.grid(row=0,column=1) entry2.grid(row=1,column=1) button1=Button(frame,text="download" ,command=download) button1.grid(row=2,column=0) button3=Button(frame,text="quit",command=frame.quit) button3.grid(row=2,column=1) frame.grid() print("its working4") root.mainloop()
answer count: 1
downvote count: 0

iteration
tags question: http://stackoverflow.com/q/49344119
tags question: http://stackoverflow.com/q/49291876
type: Tag
tags question: http://stackoverflow.com/q/49319181
tags question: http://stackoverflow.com/q/49342252
tags question: http://stackoverflow.com/q/49308562
tags question: http://stackoverflow.com/q/49433314
tags question: http://stackoverflow.com/q/49363130
tag name: iteration

http://stackoverflow.com/comment/85680764
comment on: http://stackoverflow.com/q/49340297
type: Comment
has text: Do you have access to this mythical beat in your Python 2 environment? Browse the source for some clues to its origins.
type: QuestionComment
score: 2

http://stackoverflow.com/a/49336381
type: Answer
answers question: http://stackoverflow.com/q/49336353
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85677759
has body: This seems to be a rather old package, missing what it needs to be installed with pip. Take a look at this issue: https://github.com/pypa/pip/issues/4629#issuecomment-317844966 I quote: PythonMagick is on PyPi, but there are no source distribution, eggs, or wheels provided, so it can't be installed. PythonMagickWand as an egg, but only for Python 2.5! I see you are using OSX High Sierra, so your current version of Python 2 is 2.7. You could try building a virtualenv using pyenv and python 2.5, but maybe pgmagick would be a suitable replacement?
score: 1

http://stackoverflow.com/q/49417653
has title: How can I conver SQL select statement to Python pandas?
has answer: http://stackoverflow.com/a/49417715
type: Question
has body: I have my dataset 'df'. How can I group data based on conditions using pandas? In t-sql that would be: select Producer, sum(Premim) as Premium from df where EffectiveDate BETWEEN '2018-01-01' and '2018-03-01' AND PolicyType = 'New Business' AND SICCode IN (4210,4211,4213) GROUP BY Producer Order by Premium DESC What I tried: select top 10 Premium GroupBy PolicyNumber df['Premium'].groupby(df['PolicyNumber']).sum().head(10) Also tried: select * by range of EffectiveDate df[df["EffectiveDate"].isin(pd.date_range('2017-01-01', '2018-03-28'))] But how to compile everything in one block of code? UPDATE: Python data sample: import pandas as pd import numpy as np df = pd.DataFrame({'Producer': 'Prod1 Prod2'.split(), 'Premium': '1000 2000'.split(), 'EffectiveDate': '2018-01-01 2018-03-31'.split(), 'SICCode': '4120 4113'.split(), 'PolicyType': 'NewBusiness Renewal'.split() }) print(df) UPDATE: Data sample can be found here: https://www.dropbox.com/s/2jh8crbwkhkn82z/SampleData.xlsx?dl=0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85837170
tagged with: python
score: 0
tagged with: pandas
answer count: 1
tagged with: t-sql

http://stackoverflow.com/q/49318357
tagged with: http://stackoverflow.com/tag/pdf
tagged with: file-upload
downvote count: 1
favorite count: 0
type: Question
has body: I am using django-ckeditor==5.3.1 and django==1.11.2. I need to upload non-image file. I need to pdf files upload. But I can't not find solution for this (for example pdf icon in editor panel). Please hint where I can find this. My model: from ckeditor_uploader.fields import RichTextUploadingField class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = RichTextUploadingField() urls.py urlpatterns += [ url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] settings.py CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_ALLOW_NONIMAGE_FILES = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Simple', 'toolbar_Simple': [ ['Bold', 'Italic', 'Underline'], ['Link', 'Unlink'], ['Image', 'Update', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'uploadwidget'], ], 'autoParagraph': False, 'shiftEnterMode': 2, 'enterMode': 2, }, }
has answer: http://stackoverflow.com/a/49321301
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: ckeditor
has answer: http://stackoverflow.com/a/75151836
has title: Django ckeditor pdf files upload
answer count: 2
upvote count: 2
score: 1

http://stackoverflow.com/comment/85725063
type: Comment
score: 0
has text: kindly check the last edit , this is my exact scenario
type: AnswerComment
comment on: http://stackoverflow.com/a/49359884

http://stackoverflow.com/comment/85641948
type: Comment
type: QuestionComment
score: 0
has text: I have tried this: (cout << "Result is: " << *resultado << endl;) but the error still continue.
comment on: http://stackoverflow.com/q/49320251

http://stackoverflow.com/q/49414966
tagged with: python
has title: How can I add an extra field to a proxied model in Django?
has body: I'm specifically talking about the Tag model, which I have no much experience with. The code goes like this: @register_snippet class ArticleTag(index.Indexed,Tag): class Meta: proxy=True search_fields = [ index.SearchField('name', partial_match=True), index.SearchField('slug', partial_match=True), ] The Tag model has two fields, 'name' and 'slug'. But now I want to add a third custom field named 'type' that will be simply a CharField. I tried modifying it like this: @register_snippet class ArticleTag(index.Indexed,Tag): class Meta: proxy=True search_fields = [ index.SearchField('name', partial_match=True), index.SearchField('slug', partial_match=True), ] merge_to = models.CharField(max_length=500, blank=True, null=True) panels = [ FieldPanel('name'), FieldPanel('slug'), FieldPanel('type'), ] However the server yields: ERRORS: ?: (models.E017) Proxy model 'ArticleTag' contains model fields. How can I achieve what I am trying to do?
answer count: 2
score: 2
upvote count: 2
tagged with: wagtail
tagged with: django-taggit
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/63906485
has answer: http://stackoverflow.com/a/49417374
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86075184
score: 0
type: AnswerComment
has text: These type of errors pops only if you have given wrong csv info or wrong use of record rule@SalemHassan
type: Comment
comment on: http://stackoverflow.com/a/49532117

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/49334697

http://stackoverflow.com/q/49288021
has title: Numpy not working with AWS Lambda
favorite count: 0
has comment: http://stackoverflow.com/comment/85615538
tagged with: aws-lambda
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85618715
score: 3
has comment: http://stackoverflow.com/comment/85583620
has comment: http://stackoverflow.com/comment/85583301
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85638563
has body: I am trying to create bar charts (using Matplotlib) to be saved in an AWS S3 bucket. It works perfectly from my laptop but when I upload the code to AWS Lambda (with the right packages installed) I get an error. Here is the code: import matplotlib.pyplot as plt from boto3 import Session import io from datetime import date months = [date(2018, month, 1).strftime('%b') for month in range(1, 13)] filename = 'barplot.png' BUCKET = 'my_bucket_name' img_data = io.BytesIO() counts = [ [606, 124, 759, 998, 234], [762, 912, 639, 591, 135], [492, 92, 119, 1131, 999], ] plt.figure() plt.title('Fantastic Title Goes Here') plt.xlabel('Timeline') plt.ylabel('base count') x1 = [2.0, 4.0, 6.0, 8.0, 10.0] x2 = [x - 0.5 for x in x1] x3 = [x + 0.5 for x in x1] plt.xticks(x1, months) plt.bar(x3, counts[2], width=0.4, color="#ff0000", label="Bar 3 Label") plt.bar(x2, counts[1], width=0.4, color="#87CEEB", label="Bar 2 Label") plt.bar(x1, counts[0], width=0.4, color="#F4A460", label="Bar 1 Label") plt.legend() plt.axis([0.5, 25, 0, 1500]) # NOTE saving to a file: plt.savefig(filename) plt.savefig(img_data, format='png') img_data.seek(0) s3 = Session().client('s3') response = s3.put_object(Body=img_data, Bucket=BUCKET, ContentType='image/png', Key=filename, ACL='public-read') I am getting the following error: ImportError: cannot import name 'multiarray' Here's the error Traceback: Traceback(most recent call last): File "/var/task/support_functions/catch_exceptions.py", line 19, in wrapper return function(*args, **kwargs) File "/var/task/jokes/flow_jokes.py", line 13, in get_joke import support_functions.charts File "/var/task/support_functions/charts.py", line 1, in &lt; module &gt; import matplotlib.pyplot as plt File "/var/task/matplotlib/__init__.py", line 127, in &lt; module &gt; from . import cbook File "/var/task/matplotlib/cbook/__init__.py", line 35, in &lt; module &gt; import numpy as np File "/var/task/numpy/__init__.py", line 142, in &lt; module &gt; from . import add_newdocs F…
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85650299
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49336202
tagged with: anaconda
has title: Can't find python module [Anaconda]
tagged with: python
has comment: http://stackoverflow.com/comment/85674008
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has body: I've installed the new Anaconda 5.1. Before that, I had Anaconda 4 installed on my Windows 10 computer. However I'm only able to use the preinstalled anaconda modules like numpy, matplotlib. If I install a new module for example over pip I can't use it, because my IDE (Visual Studio Code, pyCharm or Jupyter Notebook) will not find it. If I open the python console directly, I can import any module. The IDEs use the correct python path. I've reinstalled anaconda a few times, but without any positive result. Anyone with the same problem have a solution?
has answer: http://stackoverflow.com/a/49336400

http://stackoverflow.com/a/49373580
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49373428
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49373428
score: 2
type: AcceptedAnswer
has body: In terms of speed that is little you can do. You could convert your Python script into a compiled extension, this increases speed of a Python script greatly. Cython can do this and once compile you then do as you have done already. Honestly you will notice little difference if you do this, and that is about the best you will do with that method. A better method is to turn it into an executable directly. What you are doing currantly is: The batch command starts and executes (this is slow by itself). This starts the Python interpreter. The Python interpreter loads the file and then starts. You should use a tool such as Cx_Freeze or Pyinstaller to convert your script into an executable, then it could be run just like any other appliocation. You could also use Cython to achieve this. You can use installers as well.

http://stackoverflow.com/q/49314615
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49314642
has body: how do i add up all the strings together in a list into a big string? For example: alist = ["Hi","How are YOU","THANK YOU"] How do i make it into: alist = ["Hi,How are YOU, THANK YOU"]
score: 1
upvote count: 1
has title: Making strings in a list into only a string in the list
favorite count: 0
has answer: http://stackoverflow.com/a/49314630
type: Question
possible better answer: http://stackoverflow.com/a/49314642
accepted answer: http://stackoverflow.com/a/49314630
tagged with: python

http://stackoverflow.com/comment/85963689
type: Comment
has text: Hey @datacentricity, I figured out my issue somewhat. I was running the pubsub client with a flask server and the flask servers reload feature would case the process to hang. The workaround for me was to only initialize the subscription and the async threads when the process runs and [not on every reload](https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49462983

http://stackoverflow.com/comment/85741921
comment on: http://stackoverflow.com/q/49368505
has text: Are you telling us you want to be able to add multiple records to the database from a single page? In that case you would need to use formsets.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49311212
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49311098
type: Answer
has body: Python functions generally don't "assign variable names", they just return values, and you can do whatever you want with those values. A value doesn't have a variable name.* Because a value can be stored in five different variables, or it can be stored in things that aren't variables, like the elements of a list. It doesn't care. So, what you almost certainly want to do is what @spectras suggested in a comment: Get rid of that first parameter, and then store the value in whatever variable you want: def make_special_tree(arg1, arg2): tree = Tree() other_stuff = things(arg1) modify_tree(tree, other_stuff, arg2) return tree # Two different trees with different names blah = make_special_tree(foo, bar) yoink = make_special_tree(foo, bar) # One tree with two names spam = make_special_tree(foo, bar) eggs = spam # A tree with no names at all cheese = [] cheese.append(make_special_tree(foo, bar)) If you really do want to create a global variable with a specified name, you can do that,** but it's a really bad idea, unless you're trying to do something unusual, like the way collections.namedtuple acts like a class statement. * A value can have a name by having, e.g., a name attribute. You can even change the definition of the Tree class to use that name attribute as part of its output representation. But this still has nothing to do with what variables you store it in. ** The least hacky way is globals()[name] = value.
score: 0
answers question: http://stackoverflow.com/q/49311098
has comment: http://stackoverflow.com/comment/85651534
has comment: http://stackoverflow.com/comment/85653174

http://stackoverflow.com/comment/85876597
comment on: http://stackoverflow.com/q/49435357
has text: I saw that module too while searching for my question. So, to the best of your knowledge, at the moment there is no existing dict analogue that works with numba and is strictly python? I haven't used numba too much so I'm not the most familiar with its state of development/best practices.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49405424
type: Question
has title: python web scraping, submit data and get output
has answer: http://stackoverflow.com/a/49506259
tagged with: python
accepted answer: http://stackoverflow.com/a/49506259
type: AnsweredQuestion
score: 1
has body: I have this website for search data (http://wedge3.hcauditor.org), This is an image on the start page. example Inputs- here first input box(House # Range) = 3419 and the second one is (empty) and third one(Street Name) = Wabash when we submit this data and we have this link, http://wedge3.hcauditor.org/view/re/0570005018800/2017/summary we can't create URL for searching data because of only change in this link Parcel ID(0570005018800) actually, I am new to the python web scrape, but I have good knowledge of urllib, beautifulsoup and requests modules. I need to know, can we do this with python and if it is which module use for this. I am using python 3.6
answer count: 1
downvote count: 0
tagged with: web-scraping
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49468226
accepted answer of: http://stackoverflow.com/q/49429971
downvote count: 0
type: Answer
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49429971
upvote count: 1
has body: Are you sure your xxxx.model.wv file was a saved full Word2Vec model object? That error suggests it was instead a EuclideanKeyedVectors – just the vectors, and not a full model with all properties like negative – so you might need to load it as that instead.

http://stackoverflow.com/q/49391846
answer count: 2
has answer: http://stackoverflow.com/a/49391951
upvote count: 2
tagged with: pivot
downvote count: 0
tagged with: python
has body: I have the feeling that there has to be a pretty straight-forward way to do this, but I can't find it. So, I have this data (notice that description column has a shared part between several): import pandas as pd data = {"description": ["AAAA:A", "AAAA:B", "AAAA:C", "AAAA:D", "BBBB:A", "BBBB:B"], "sequence": ["AAAAAAAAAAA", "AAAAAAABBBBBB", "AAAAAAAACCCCCCC", "AAAAAAAADDDDDDD", "BBBBBBAAAAA", "BBBBBBBBBBBBB"]} df = pd.DataFrame(data) print df # description sequence #0 AAAA:A AAAAAAAAAAA #1 AAAA:B AAAAAAABBBBBB #2 AAAA:C AAAAAAAACCCCCCC #3 AAAA:D AAAAAAAADDDDDDD #4 BBBB:A BBBBBBAAAAA #5 BBBB:B BBBBBBBBBBBBB And my final aim is to put together all the sequences for a single 4 letter description. Something like this: # description sequence_A sequence_B sequence_C sequence_D #0 AAAA AAAAAAAAAAA AAAAAAABBBBBB AAAAAAAACCCCCCC AAAAAAAADDDDDDD #1 BBBB BBBBBBAAAAA BBBBBBBBBBBBB NaN NaN Right until now, I've gotten to this point: df = df.apply(lambda row: pd.Series({"description": row["description"].split(":")[0], "sequence_{}".format(row["description"].split(":")[1]): row["sequence"]}), axis=1) print df # description sequence_A sequence_B sequence_C sequence_D #0 AAAA AAAAAAAAAAA NaN NaN NaN #1 AAAA NaN AAAAAAABBBBBB NaN NaN #2 AAAA NaN NaN AAAAAAAACCCCCCC NaN #3 AAAA NaN NaN NaN AAAAAAAADDDDDDD #4 BBBB BBBBBBAAAAA NaN NaN NaN #5 BBBB NaN BBBBBBBBBBBBB NaN NaN I'm guessing that I need to df.groupby("description") and then do one more step there, but I'm missing that last point.
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/49391955
tagged with: pandas
has answer: http://stackoverflow.com/a/49391955
tagged with: dataframe
has title: Collapse rows of python dataframe that share one column's value
accepted answer: http://stackoverflow.com/a/49391951
favorite count: 0
type: Question

http://stackoverflow.com/comment/85689081
score: 0
type: AnswerComment
has text: Aww, missed that one. I've updated my answer. It's a quick trick but works.
comment on: http://stackoverflow.com/a/49333132
type: Comment

http://stackoverflow.com/a/49309473
score: 31
upvote count: 31
has comment: http://stackoverflow.com/comment/94670610
has comment: http://stackoverflow.com/comment/118196056
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49308530
answers question: http://stackoverflow.com/q/49308530
has comment: http://stackoverflow.com/comment/102514086
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94670316
has body: Consider interpolate (Series - DataFrame). This example shows how to fill gaps of any size with a straight line: df = pd.DataFrame({'date': pd.date_range(start='2013-01-01', periods=10, freq='H'), 'value': range(10)}) df.loc[2:3, 'value'] = np.nan df.loc[6, 'value'] = np.nan df date value 0 2013-01-01 00:00:00 0.0 1 2013-01-01 01:00:00 1.0 2 2013-01-01 02:00:00 NaN 3 2013-01-01 03:00:00 NaN 4 2013-01-01 04:00:00 4.0 5 2013-01-01 05:00:00 5.0 6 2013-01-01 06:00:00 NaN 7 2013-01-01 07:00:00 7.0 8 2013-01-01 08:00:00 8.0 9 2013-01-01 09:00:00 9.0 df['value'].interpolate(method='linear', inplace=True) date value 0 2013-01-01 00:00:00 0.0 1 2013-01-01 01:00:00 1.0 2 2013-01-01 02:00:00 2.0 3 2013-01-01 03:00:00 3.0 4 2013-01-01 04:00:00 4.0 5 2013-01-01 05:00:00 5.0 6 2013-01-01 06:00:00 6.0 7 2013-01-01 07:00:00 7.0 8 2013-01-01 08:00:00 8.0 9 2013-01-01 09:00:00 9.0

http://stackoverflow.com/comment/85782902
comment on: http://stackoverflow.com/a/49388763
type: Comment
has text: Right ok so I've found the files!!! (About a million of them from all my tests) I did a HD search like you suggested, went a bit deeper. They were created in some random **HIDDEN** folder which wasn't even specified in the absolute file path I wrote! So how on earth did they end up somewhere else even with an absolute path specified?? Because I can't even access them right now without a search.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85752664
type: Comment
comment on: http://stackoverflow.com/q/49375176
has text: I don't notice anything unusual happening when I resize the window. What platform are you seeing this on?
type: QuestionComment
score: 0

http://stackoverflow.com/q/49389054
has body: How do I get the number of dictionaries where value satisfies a given condition? list_of_dict = [ {'seq_no': 10, 'file_path': 'file/path', 'rel_item': None}, {'seq_no': 22, 'file_path': 'file/path', 'rel_item': 0}, {'seq_no': 32, 'file_path': 'file/path', 'rel_item': 0}, {'seq_no': 90, 'file_path': 'file/path', 'rel_item': 0}, {'seq_no': 10, 'file_path': 'file/path', 'rel_item': None}, ] I would like to count the number of dictionaries where key rel_item=None.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85782847
score: 0
has title: Count number of dictionaries in list satistying condition on value
has answer: http://stackoverflow.com/a/49389484
has comment: http://stackoverflow.com/comment/85780295
has answer: http://stackoverflow.com/a/49389137
has comment: http://stackoverflow.com/comment/85779683
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85779646
type: Question
has comment: http://stackoverflow.com/comment/85891116
has comment: http://stackoverflow.com/comment/85779873
has answer: http://stackoverflow.com/a/49389213
possible better answer: http://stackoverflow.com/a/49389137
accepted answer: http://stackoverflow.com/a/49389112
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49389112
answer count: 4

http://stackoverflow.com/comment/85848856
type: QuestionComment
has text: You could create a single string for the Cypher query then [Graph.run](http://py2neo.org/v3/database.html#py2neo.database.Graph.run) it.
comment on: http://stackoverflow.com/q/49423946
score: 0
type: Comment

http://stackoverflow.com/comment/85678128
type: Comment
type: QuestionComment
has text: That doesn't make it a C question. Tags shall describe the question, Not the reader. Using unrelated tags ist considered spamming.
score: 0
comment on: http://stackoverflow.com/q/49295110

http://stackoverflow.com/comment/85625014
score: 0
comment on: http://stackoverflow.com/q/49311418
has text: You should return any objects that you may want, don't use global variables
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49342876
has comment: http://stackoverflow.com/comment/85686408
linked to: http://stackoverflow.com/q/28820820
tagged with: field
has comment: http://stackoverflow.com/comment/85687554
has comment: http://stackoverflow.com/comment/85686550
has title: Element cannot be sent to a field, website login, Python + Selenium
score: 1
has answer: http://stackoverflow.com/a/49345323
tagged with: python
has comment: http://stackoverflow.com/comment/85686131
has comment: http://stackoverflow.com/comment/85688581
has answer: http://stackoverflow.com/a/53126021
answer count: 3
tagged with: hidden
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has body: I used below scripts to log into the following website with a username and password. It used to work fine. However, I think recently Etsy set the username ( and maybe password too) to hidden type. So username cannot be sent to the Email address field. Here are the scripts. Anyone knows how to fix this particular case? The error message is: ElementNotVisibleException: Message: element not visible from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option('prefs', profile) chrome_options.add_argument('--kiosk-printing') self.driver = webdriver.Chrome('C:/Python27/chromedriver.exe',chrome_options=chrome_options) self.driver.get("https://www.etsy.com/signin") usernameFieldID = "username" passFieldID = "password" signButtonXpath = "//input[@value='Sign in']" usernameFieldElement = WebDriverWait(driver, 5).until(lambda driver:driver.find_element_by_name(usernameFieldID)) passFieldElement = WebDriverWait(driver, 5).until(lambda driver:driver.find_element_by_name(passFieldID)) signButtonElement = WebDriverWait(driver, 5).until(lambda driver:driver.find_element_by_xpath(signButtonXpath)) usernameFieldElement.send_keys("abc@abc.com") passFieldElement.send_keys("EtsyPass") signButtonElement.click()
upvote count: 1
has comment: http://stackoverflow.com/comment/85687005
favorite count: 0
has comment: http://stackoverflow.com/comment/85867256
has answer: http://stackoverflow.com/a/49356720
type: Question

http://stackoverflow.com/comment/85755916
type: QuestionComment
comment on: http://stackoverflow.com/q/49377576
has text: If you want help, you actually have to tell us what is wrong. Don't just say it doesn't work. What is happening? Any error messages? Any results?
type: Comment
score: 0

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/49355731
type: Tag

http://stackoverflow.com/q/49334778
type: Question
tagged with: apache-beam-io
has answer: http://stackoverflow.com/a/49404784
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
has body: I am new to apache beam and exploring python version of apache beam dataflow. I want to execute my dataflow tasks in certain order but it executes all tasks in parallel mode. How to create task dependency in apache beam python? Sample Code: (in this below code sample.json file contains 5 rows) import apache_beam as beam import logging from apache_beam.options.pipeline_options import PipelineOptions class Sample(beam.PTransform): def __init__(self, index): self.index = index def expand(self, pcoll): logging.info(self.index) return pcoll class LoadData(beam.DoFn): def process(self, context): logging.info("***") if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) pipeline = beam.Pipeline(options=PipelineOptions()) (pipeline | "one" &gt;&gt; Sample(1) | "two: Read" &gt;&gt; beam.io.ReadFromText('sample.json') | "three: show" &gt;&gt; beam.ParDo(LoadData()) | "four: sample2" &gt;&gt; Sample(2) ) pipeline.run().wait_until_finish() I expected it will execute in order one, two, three, four. But it is running in parallel mode. output of above code: INFO:root:Missing pipeline option (runner). Executing pipeline using the default runner: DirectRunner. INFO:root:1 INFO:root:2 INFO:root:Running pipeline with DirectRunner. INFO:root:*** INFO:root:*** INFO:root:*** INFO:root:*** INFO:root:***
tagged with: dataflow
has comment: http://stackoverflow.com/comment/85680899
score: 0
has title: How to create dependency between tasks in Apache beam python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85689973
linked to: http://stackoverflow.com/q/44315157

http://stackoverflow.com/a/49376170
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49375449
has comment: http://stackoverflow.com/comment/85753383
has body: The form data submitted via HTTP POST in the test method will make a invalid form. You need to send dates in like format (i.e. YYYY-MM-DD) as it will have been passed were the form submitted in a browser. def test_create_new_menu_view(self): expiration_date = timezone.now() + timezone.timedelta(days=2) self.client.post('/menu/new/', data={ 'expiration_date': expiration_date.strftime("%Y-%m-%d"), 'season': 'Spring 2018', 'created_date': timezone.now().strftime("%Y-%m-%d"), 'items': ['1'] }) self.assertEqual(Menu.objects.count(), 2)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49375449
has comment: http://stackoverflow.com/comment/85753431
upvote count: 2

http://stackoverflow.com/a/49402161
has comment: http://stackoverflow.com/comment/85808771
has body: Corrected Code: i=0 a=0 Matrix=[1 for i in range(1000)] while i&lt;1000: Matrix[i]=(1/1000)*((i*(1/1000)))**2 a=a+Matrix[i] i=i+1 print (a)
has comment: http://stackoverflow.com/comment/85856385
answers question: http://stackoverflow.com/q/49402041
has comment: http://stackoverflow.com/comment/85826861
type: Answer
has comment: http://stackoverflow.com/comment/85856420
accepted answer of: http://stackoverflow.com/q/49402041
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85856338
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85856414

http://stackoverflow.com/a/49607725
has body: I tried to reproduce the error on my computer and was successful when I ran the "error-producing" file _big_num_ctypes.py. Although, I do not have Visual Studio, the error stems from the missing crypto.dll file. We will deduce this step-by-step. Let's first examine the error causing code snippet in the file _big_num_ctypes.py: #imports from ctypes.util import find_library . . from .._ffi import LibraryNotFoundError, FFIEngineError try: # On Python 2, the unicode string here may raise a UnicodeDecodeError as it # tries to join a bytestring path to the unicode name "crypto" libcrypto_path = find_library(b'crypto' if sys.version_info &lt; (3,) else 'crypto') if not libcrypto_path: raise LibraryNotFoundError('The library libcrypto could not be found') . . except (AttributeError): raise FFIEngineError('Error initializing ctypes') I ran the file: C:\&gt;cd "C:\ProgramData\Anaconda3\Lib\site-packages\asn1crypto\_perf" C:\ProgramData\Anaconda3\Lib\site-packages\asn1crypto\_perf&gt;python _big_num_ctypes.py and had a Traceback for the library import: Traceback (most recent call last): File "_big_num_ctypes.py", line 27, in &lt;module&gt; from .._ffi import LibraryNotFoundError, FFIEngineError ValueError: attempted relative import beyond top-level package So, I changed the import path for.ffito: from asn1crypto._ffi import LibraryNotFoundError, FFIEngineError On the second run, the missing libcrypto library error appeared: asn1crypto._ffi.LibraryNotFoundError: The library libcrypto could not be found The exception is raised when the dll library named crypto could not be found at C:\Windows\System32 and/or SYSWOW64(for 64-bit) libcrypto_path = find_library(b'crypto' if sys.version_info &lt; (3,) else 'crypto') The purpose of find_library is to find a specified library and return a pathname. The behavior of this method varies with OS as described in the docs. If this method cannot find any packages, it returns None. &gt;&gt;&gt; from ctypes.util import find_library &gt;&gt;&gt;…
answers question: http://stackoverflow.com/q/49302516
score: 3
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/85740542
type: Comment
comment on: http://stackoverflow.com/q/49369778
has text: Have you tried to force garbage collection? https://stackoverflow.com/a/1316793/1042144
score: 1
type: QuestionComment

http://stackoverflow.com/a/49385850
score: 1
has comment: http://stackoverflow.com/comment/85773109
answers question: http://stackoverflow.com/q/49384156
has body: There are a couple of problems I can find which prevent your code from working: You should write template out, which is a list of lines, not template_file, which is a file object In Python, strings are immutable, meaning they cannot be changed. The replace function does not change the string, it returns a new copy of the string. Furthermore, replace will replace a substring with a new text, regardless of where that substring is. If you want to replace at a specific index, I suggest to slice the string yourself. For example: line2 = '0123456789ABCDEFG' element = '-ho-ho-ho-' line2 = line2[:5] + element + line2[16:] # line2 now is '01234-ho-ho-ho-G' Please do not use list as a variable name. It is a type, which can be used to construct a new list as such: empty = list() # ==&gt; [] letters = list('abc') # ==&gt; ['a', 'b', 'c'] The expression template_file[2][5:16] is incorrect: First, it should be template, not template_file. Second, the second line should be template[1], not template[2] since Python list are zero based The list_element variable is not declared in your code Solution 1 That being said, I find that it is easier to structure your template file as a real template with placeholders. I'll talk about that later. If you still insist to replace index 5-16 of line 2 with something, here is a solution I tested and it works: with open('template.txt') as template_file: template = template_file.readlines() elements = ['ABC', 'DEF', 'GHI', 'JKL'] for i, element in enumerate(elements): with open('output_%02d.txt' % i, 'w') as out_file: line2 = template[1] line2 = line2[:5] + element + line2[16:] for line_number, line in enumerate(template, 1): if line_number == 2: line = line2 out_file.write(line) Notes The code writes out all lines, but with special replacement applies to line 2 The code is clunky, nested deeply I don't like having to hard code the index numbers (5, 16) because if the template changes, I have to change the code as well Solution 2 If you have contro…
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/49345573
has title: How to send Selenium login credentials to PDFKit
type: UnansweredQuestion
has body: I am using Selenium, Python, ChromeDriver and PDFKit to convert the data in the browser to PDF. But seems like PDFKit is not getting the credentials from Selenium so it's coming as "unauthorised". Please find the code below. from selenium import webdriver import pdfkit from selenium.webdriver.chrome.options import Options import time from selenium.webdriver.common.by import By chrome_path = r"C:\chrome\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get("https://test.test.com/login") time.sleep(5) username = driver.find_element_by_id("username") password = driver.find_element_by_id("password") username.send_keys("admin") password.send_keys("admin") time.sleep(5) submit_button = driver.find_element_by_xpath('/html/body/div[2]/cd-authenticate/div/div/div/cd-login/div[1]/form/button') submit_button.click() time.sleep(5) pdfkit.from_url('https://test.test.com/comp/export?format=csv&amp;filters=start_time:2018-03-04T00%3A00%3A00Z+end_time:2018-03-15T18%3A29%3A59Z+node_name:abcdef','out.pdf')
tagged with: python
has comment: http://stackoverflow.com/comment/85703405
tagged with: selenium-chromedriver
score: 0
tagged with: pdfkit
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/85691215
has comment: http://stackoverflow.com/comment/85691357
type: Question

http://stackoverflow.com/a/49313053
downvote count: 0
has body: Instead of using compile, grab all digits in the IP and check its length: import re versions = ['9.130.46.32.6.2', '9.130.46.32.6.2.1'] new_versions = [i for i in versions if len(re.findall('\d+', i)) == 6] Output: ['9.130.46.32.6.2']
answers question: http://stackoverflow.com/q/49313024
type: Answer
accepted answer of: http://stackoverflow.com/q/49313024
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/49427682
score: 0
answers question: http://stackoverflow.com/q/49424084
type: Answer
has body: You can use first assemble the info per line in an extra column, and then use groupby.sum queries = df[KEY_COLUMN] + ' ' + df[KEY_FORMAT] + ', ' queries.index = df.set_index(index_labels).index DB Table Retail Orders ID INTEGER, Orders Place STRING, Dept Sales ID INTEGER, Sales Name STRING, dtype: object queries = queries.groupby(index_labels).sum().str.strip(', ') DB Table Dept Sales ID INTEGER, Name STRING Retail Orders ID INTEGER, Place STRING dtype: object def format_queries(queries): query_pattern = 'CREATE TABLE %s.%s (%s)' for (db, table), text in queries.items():# idx, table, text query = query_pattern % (db, table, text) yield query list(format_queries(queries)) ['CREATE TABLE Dept.Sales (ID INTEGER, Name STRING)', 'CREATE TABLE Retail.Orders (ID INTEGER, Place STRING)'] This way you don't need the lambda. I don't know whether this approach or the itertuples will be fastest

http://stackoverflow.com/a/49361007
type: Answer
has body: The numpy function np.arange gives out an array increasing from zero to 12288, which is why you have a gradient on your map. You can replace that line of code to m = np.zeros(hp.nside2npix(NSIDE)) if you want to treat blanks in your map as zeros, or to m = np.full(hp.nside2npix(NSIDE), np.nan) if you want to use NaN (not a number) value for the blank values on the map.
answers question: http://stackoverflow.com/q/49353537
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85733393
score: 1

http://stackoverflow.com/a/49349845
type: Answer
has body: Whenever using the parameter -i &lt;name&gt; to "import" a Python object into R, conversion rules are applied (see here). The default converter is ending up calling R's function data.frame, which will sanitize the column names (parameter check.names=TRUE by default, see https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/data.frame) to valid-yet-unquoted symbol names. In your example, CTB-102L5.4 would otherwise be parsed as the expression CTB - 102L5.4. This default behaviour is not necessarily desirable in every situation, and a custom converter can be passed to the R magic %%R. The documentation contains a short introduction to writing custom conversion rules (https://rpy2.github.io/doc/v2.9.x/html/robjects_convert.html). Assuming that your input is a pandas DataFrame, you could proceed as follows: 1- implement a variant of py2ri_pandasdataframe that does not sanitize names. Ideally by just setting check.names to FALSE, although currently not possible because of https://bitbucket.org/rpy2/rpy2/issues/455/add-parameter-to-dataframe-to-allow). def my_py2ri_pandasdataframe(obj): res = robjects.pandas2ro.py2ri_pandasdataframe(obj) # Set the column names in `res` to the original column names in `obj` # (left as an exercise for the reader) return res 2- create a custom converter derived from the ipython converter import pandas from rpy2.ipython import rmagic from rpy2.robjects.conversion import Converter, localconverter my_dataf_converter = Converter('my converter') my_dataf_converter.py2ri.register(pandas.DataFrame, my_py2ri_pandasdataframe) my_converter = rmagic.converter + my_dataf_converter 3- Use %%R with --converter=my_converter.
answers question: http://stackoverflow.com/q/49282218
type: AcceptedAnswer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49282218
downvote count: 0

memoization
type: Tag
tags question: http://stackoverflow.com/q/49328260
tag name: memoization
tags question: http://stackoverflow.com/q/49341568

http://stackoverflow.com/comment/85760334
has text: yes it is an integer. Just to clarify, If sum of column A (i.e., A1+A2) is 100. Out of 100, A1 represents 40 and A2 represents 60. I would like to output an additional column which shows that A1 represents 40% and A2 60%.
comment on: http://stackoverflow.com/a/49379784
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85839222
has text: Try doing a re-install on the requests package? pip install requests --force-reinstall
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49418808

http://stackoverflow.com/comment/85825211
score: 0
type: AnswerComment
type: Comment
has text: yeah, DV punishes (tried to...) the fact that it's probably solving a XY problem.
comment on: http://stackoverflow.com/a/49411638

http://stackoverflow.com/q/49342189
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49342446
favorite count: 0
has answer: http://stackoverflow.com/a/49342446
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/49342221
has body: Using pandas IndexSlice, is it possible to use a list of integers? I get KeyError: 'the label [xxxx] is not in the [columns]' when I use a list of integers (even when the values in the multiIndex level are formatted as strings): vals = np.random.randn(4) df = pd.DataFrame({'l1': ['A', 'B', 'C', 'B'], 'l2': ['9876', '6789', '5432', '1234'], 'l3': ['Y', 'X', 'Y', 'Y'], 'value': vals}) df.set_index(['l1', 'l2', 'l3'], inplace=True) idx = pd.IndexSlice # None of the following works df.loc[idx[:, 6789, :]] df.loc[idx[:, [6789, 1234], :]] df.reset_index(inplace=True) df.l2 = df.l2.astype('str') df.set_index(['l1', 'l2', 'l3'], inplace=True) df.loc[idx[:, '6789', :]]
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49342221
score: 2
type: AnsweredQuestion
has title: pandas IndexSlice does not accept integer list
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/49426359
has body: I am looking for some useful suggestions for keras cnn model. i have a very small dataset(144 images) which i am training through keras cnn i tried to add many layers and num_of_filters but the accuracy is not increasing even number of trained parameter was 111,453,342. Does large number of parameters represents more chance to get good accuracy? And below is my existing model it gives val_acc=0.56. How i can improve my model. inputs=Input(shape=(100,100,1)) x=Conv2D(28, (5, 5), padding='same')(inputs) x=SReLU()(x) x=MaxPooling2D(pool_size=(2,2), strides=(1, 1))(x) x=Conv2D(14, (4, 4), padding='same')(x) x=SReLU()(x) x=MaxPooling2D(pool_size=(2,2), strides=(1, 1))(x) x=Conv2D(7, (3, 3), padding='same')(x) x=SReLU()(x) x=MaxPooling2D(pool_size=(2,2))(x) x=Flatten()(x) x=Dropout(0.2)(x) x=Dense(512)(x) x=SReLU()(x) #x=keras.layers.GlobalMaxPooling2D()(x) x=Dropout(0.2)(x) x=Dense(num_classes)(x) output=Activation('softmax')(x) model=Model([inputs], output)
tagged with: python
tagged with: keras
type: AnsweredQuestion
has title: Cnn keras model what no of trained parameter represents and improve the model
tagged with: keras-layer
has comment: http://stackoverflow.com/comment/85854663
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49428797
has comment: http://stackoverflow.com/comment/85863768
answer count: 1
has comment: http://stackoverflow.com/comment/85861991
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49428797
score: 0

http://stackoverflow.com/comment/85620566
type: Comment
comment on: http://stackoverflow.com/q/49308962
score: 1
type: QuestionComment
has text: Replace `image` with `self.image` and `image = self.image`.

http://stackoverflow.com/comment/85702713
type: QuestionComment
score: 0
has text: @RobertGrossman I'm not sure how I can split the `data.groupby(level=0)` into parts since it's a pandas object. If you mean to split the data, then I would have to make sure it's split by ids, e.g. no id can be in any 2 datasets. This would require further data-prep or manual cutting (for example after sorting by id and then manually defining cut points). Then, I would either have to run multiple notebooks to run the loop or some sort of library to pararellize the process
comment on: http://stackoverflow.com/q/49317991
type: Comment

http://stackoverflow.com/q/49335623
has comment: http://stackoverflow.com/comment/85683599
tagged with: python
has answer: http://stackoverflow.com/a/49344999
has body: I create a project with scrapy and save data to my mongodb. It can work. Here is my code: # -*- coding: utf-8 -*- import scrapy from scrapy import Request import time # scrapy api imports from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings # I import a lots of spider file here. from Tainan.Madou import Madou # from ... import ... # from ... import ... # Spider Array: add spider into array CrawlersArray = [ Madou ] class MoviesSpider(scrapy.Spider): name = 'movies' allowed_domains = ['tw.movies.yahoo.com', 'movies.yahoo.com.tw'] start_urls = ['http://tw.movies.yahoo.com/movie_thisweek.html/'] process = CrawlerProcess(get_project_settings()) for spider in CrawlersArray: process.crawl(spider) process.start() Here is my Madou spide, i have a lots of spider just like Madou, if i don't add if __name__ == '__main__': i can run all of my spider # -*- coding: utf-8 -*- import scrapy from scrapy import Request from TainanItem import Tainan, MovieReleased # 麻豆戲院 class Madou(scrapy.Spider): name = 'Madou' allowed_domains = ['tw.movies.yahoo.com', 'movies.yahoo.com.tw'] start_urls = ['https://movies.yahoo.com.tw/theater_result.html/id=68'] global tainan, movieReleased tainan = Tainan() movieReleased = MovieReleased() global detailDict detailDict = {} global locationDetail locationDetail = {} global lonAndLatArray global cnNameArray, enNameArray, releasedTimeArray, versionTypeArray, movieStyleArray, moviePhotoArray, movieContentArray, nextPageHrefArray global movieDateArray, movieTimeArray, movieStillsArray, movieActorCnArray, movieActorPhotoArray cnNameArray = [] enNameArray = [] versionTypeArray = [] movieStyleArray = [] releasedTimeArray = [] moviePhotoArray = [] movieContentArray = [] nextPageHrefArray = [] movieDateArray = [] movieTimeArray = [] movieStillsArray = [] movieActorCnArray = [] movieActorPhotoArray = [] lonAndLatArray = [] global dataLen, countLen dataLen = 0 countLen = 0 def parse(self, response): global tainan global …
tagged with: scrapinghub
type: UnansweredQuestion
answer count: 1
has title: Deploy failed because multiple spiders with Scrapinghub
downvote count: 0
score: 1
upvote count: 1
tagged with: scrapy
has comment: http://stackoverflow.com/comment/85688235
favorite count: 0
type: Question

http://stackoverflow.com/comment/85712334
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49355681
has text: It looks like in your original code, you were only calculating the correlation with respect to a single column which you indexed with `c0`. With your method, you'd need two loops one for `c0 in range(0,30)` and within that loop another for `c in range(0,c0)` to get all pair-wise correlations.
score: 0

http://stackoverflow.com/q/49399979
type: Question
answer count: 2
has title: Django filter adding results from two tables
has comment: http://stackoverflow.com/comment/85801558
has comment: http://stackoverflow.com/comment/85801291
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85801848
favorite count: 0
possible better answer: http://stackoverflow.com/a/49409186
type: AnsweredQuestion
has body: I am trying to get results from two tables by filter. I want to get all the properties and if there is an agreement I also want to include the renters first and last name. Below is a simple model. class Property(models.Model): name = models.CharField(max_length=70, blank=True, verbose_name="Property Name") class Agreement(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name="prop") firstname = models.CharField(max_length=40, verbose_name="First Name") lastname = models.CharField(max_length=40, verbose_name="Last Name") Normally I get all the properties with properties = Properties.objects.all() Is there some way like below: properties = Properties.objects.all() \ .somemethod(get values of firstname and lastname from aggreement if related record exists.) I can loop at properties results and get the values from agreements. But I think this is not the preferred way as it will make many SQL calls.
has answer: http://stackoverflow.com/a/49409186
accepted answer: http://stackoverflow.com/a/49400173
score: 1
has answer: http://stackoverflow.com/a/49400173

http://stackoverflow.com/a/49309070
type: Answer
upvote count: 1
has body: Let's see if this works: Your setup: df = pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10003','10034', '10034'], 'Num1': [12,13,13,12,13,13,16,13], 'Num2': [121,122,122,124,125,126,127,128], 'admit': [20120506, 20120508, 20120510,20121010,20121010,20121110,20120516,20120520], 'discharge': [20120515, 20120508, 20120512,20121016,20121023,20121111,20120520,20120522]}) df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d') df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d') df.loc[df.groupby(['Key']).apply(lambda x : (x['admit']&lt;=x['admit'].shift(-1))&amp;(x['discharge'] &gt; x['admit'].shift(-1))).values,'flag']='Initial_Overlap' Let's fill 'overlap', check to see if 'admit' falls between the dates of the previous "Initial_Overlap". Use cumsum to group "Intial_Overlap" records to the next "Initial Overlap": df['flag'] = df.flag.fillna('Overlap')\ .where(df.groupby(df.flag.notnull().cumsum(), group_keys=False) .apply(lambda x: x.admit.between(x.admit.iloc[0], x.discharge.iloc[0]))) df1 = df[df.flag.isnull()] df2 = df[df.flag.notnull()] Outputs: print(df1) Key Num1 Num2 admit discharge flag 5 10003 13 126 2012-11-10 2012-11-11 NaN 6 10034 16 127 2012-05-16 2012-05-20 NaN 7 10034 13 128 2012-05-20 2012-05-22 NaN print(df2) Key Num1 Num2 admit discharge flag 0 10003 12 121 2012-05-06 2012-05-15 Initial_Overlap 1 10003 13 122 2012-05-08 2012-05-08 Overlap 2 10003 13 122 2012-05-10 2012-05-12 Overlap 3 10003 12 124 2012-10-10 2012-10-16 Initial_Overlap 4 10003 13 125 2012-10-10 2012-10-23 Overlap Edit: changed Flag to flag
has comment: http://stackoverflow.com/comment/85624389
has comment: http://stackoverflow.com/comment/85621226
has comment: http://stackoverflow.com/comment/85621192
score: 1
accepted answer of: http://stackoverflow.com/q/49308542
answers question: http://stackoverflow.com/q/49308542
has comment: http://stackoverflow.com/comment/85621049
type: AcceptedAnswer
downvote count: 0

grouping
tags question: http://stackoverflow.com/q/49397244
tag name: grouping
type: Tag
tags question: http://stackoverflow.com/q/49344761
tags question: http://stackoverflow.com/q/49396943
tags question: http://stackoverflow.com/q/49350675
tags question: http://stackoverflow.com/q/49386824

http://stackoverflow.com/comment/85709627
score: 0
type: Comment
type: QuestionComment
has text: Yup, we do this for free so the experts are very strict on MCVE.
comment on: http://stackoverflow.com/q/49354400

http://stackoverflow.com/q/49367992
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85737278
type: Question
has answer: http://stackoverflow.com/a/49368078
tagged with: dask
linked to: http://stackoverflow.com/q/20994716
has body: I'm following a tutorial that uses castra and dask to read in reddit comments. I have installed the latest versions of dask and pandas using anaconda and castra using pip. My pandas version is '0.22.0', and I have installed msgpack using pip install pandas-msgpack -U I am using Python 3.6. Trying to import castra gives me the following error: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-16-fcdf7be49118&gt; in &lt;module&gt;() 32 from pandas import Timestamp, NaT, DataFrame 33 from toolz import dissoc ---&gt; 34 from castra import Castra 35 from toolz import peek, partition_all 36 import time /Users/edefilippis/anaconda/lib/python3.6/site-packages/castra/__init__.py in &lt;module&gt;() ----&gt; 1 from .core import Castra 2 3 __version__ = '0.1.7' /Users/edefilippis/anaconda/lib/python3.6/site-packages/castra/core.py in &lt;module&gt;() 22 import pandas as pd 23 ---&gt; 24 from pandas import msgpack 25 26 ImportError: cannot import name 'msgpack'
tagged with: python
tagged with: castra
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85738290
has comment: http://stackoverflow.com/comment/85738424
tagged with: pandas
has comment: http://stackoverflow.com/comment/85737155
answer count: 1
upvote count: 1
has title: ImportError: cannot import name 'msgpack'
accepted answer: http://stackoverflow.com/a/49368078

http://stackoverflow.com/comment/85834672
score: 0
comment on: http://stackoverflow.com/q/49415834
type: QuestionComment
type: Comment
has text: Maybe you could be more empathetic. My uni was on strike and I wasn't being taught the most content rich part of the course. Stress is very high right now and my work haven't let me know if I can get off for study leave.

http://stackoverflow.com/comment/85657180
has text: No, but I am wanting it to get to that section only after the user has entered 1 for the second input. I totally just released that those print statements were part of the loop.I'll think on that now that I see that.
comment on: http://stackoverflow.com/q/49327629
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85687123
comment on: http://stackoverflow.com/a/49338464
type: Comment
type: AnswerComment
score: 1
has text: Thank you for this. Very well explained. Glad I came to this site.

http://stackoverflow.com/comment/85786047
has text: Both the first solutions seem like they could work. I need to use JSON lines otherwise my data gets scrambled. How would I go about wrapping/modifying the JsonLinesItemExporter? If you have a link to some documentation or an example that would be much appreciated.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49391892
type: Comment

http://stackoverflow.com/q/49282487
tagged with: python
has title: Python Eric IDE: Execute selection in console
has answer: http://stackoverflow.com/a/50881411
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
has body: This is such a simple question, but I cannot figure out the answer. I have installed the Eric 6 IDE for Python. It has an interactive console - great! How can I execute selected commands in the console? PyCharm has Shift+Ctrl+E, Spyder has Ctrl+Enter ... what is the corresponding command in Eric?
type: Question
tagged with: eric-ide
type: UnansweredQuestion
tagged with: ide

apache-spark-sql
tags question: http://stackoverflow.com/q/49377085
tags question: http://stackoverflow.com/q/49377703
tags question: http://stackoverflow.com/q/49299079
tags question: http://stackoverflow.com/q/49411495
tags question: http://stackoverflow.com/q/49353078
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/49339552
tags question: http://stackoverflow.com/q/49389950
tags question: http://stackoverflow.com/q/49289539
tags question: http://stackoverflow.com/q/49315127
tags question: http://stackoverflow.com/q/49396558
tags question: http://stackoverflow.com/q/49419678
tags question: http://stackoverflow.com/q/49399245
tags question: http://stackoverflow.com/q/49356624
tags question: http://stackoverflow.com/q/49382957
tags question: http://stackoverflow.com/q/49321165
tags question: http://stackoverflow.com/q/49290553
tags question: http://stackoverflow.com/q/49286434
tags question: http://stackoverflow.com/q/49374608
tags question: http://stackoverflow.com/q/49432950
tags question: http://stackoverflow.com/q/49305978
tags question: http://stackoverflow.com/q/49373453
tags question: http://stackoverflow.com/q/49421150
tags question: http://stackoverflow.com/q/49376887
tags question: http://stackoverflow.com/q/49361286
type: Tag
tags question: http://stackoverflow.com/q/49406922
tags question: http://stackoverflow.com/q/49321731

http://stackoverflow.com/comment/85825250
has text: And how to get a new height in the number of rows?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49411485

http://stackoverflow.com/comment/85749917
comment on: http://stackoverflow.com/a/49362973
type: Comment
has text: Thank you Tom. I just edited the code above. Please let me know if you have a solution. :) I appreciate everything.
score: 0
type: AnswerComment

firebase
tags question: http://stackoverflow.com/q/49348460
tags question: http://stackoverflow.com/q/49307000
tags question: http://stackoverflow.com/q/49343473
tags question: http://stackoverflow.com/q/49369867
type: Tag
tag name: firebase

http://stackoverflow.com/a/49392581
has comment: http://stackoverflow.com/comment/85827970
answers question: http://stackoverflow.com/q/49392489
type: AcceptedAnswer
has body: One way to do this is using apply function: Assuming your DataFrame is in variable df you can do: import pandas as pd df = pd.DataFrame(data={"Before": ["Injection", "Injection", "Production", "Production"], "After": ["Injection", "Production", "Injection", "Production"]}) def get_output(x): if x['Before'] == 'Injection' and x['After'] == 'Injection': return 'DTI' elif x['Before'] == 'Injection' and x['After'] == 'Production': return 'DTWF + DTP' elif x['Before'] == 'Production' and x['After'] == 'Injection': return 'DTWF + DTI' elif x['Before'] == 'Production' and x['After'] == 'Production': return 'DTP' df['Output'] = df.apply(get_output, axis=1)
has comment: http://stackoverflow.com/comment/85823785
has comment: http://stackoverflow.com/comment/85832767
accepted answer of: http://stackoverflow.com/q/49392489
score: 0
type: Answer

http://stackoverflow.com/q/49337774
type: Question
type: UnansweredQuestion
tagged with: pylint
has answer: http://stackoverflow.com/a/56070625
tagged with: python
has answer: http://stackoverflow.com/a/49345918
has comment: http://stackoverflow.com/comment/85676627
has title: How to enforce closing bracket lint rules in python
has answer: http://stackoverflow.com/a/58018078
answer count: 4
downvote count: 0
tagged with: indentation
tagged with: lint
has body: We're using flake8 and pylint to do our code style checks on a project. But the problem is, none of those do any checks for how lines are split. Since consistency is nice in a project it looks really weird that we find foo = long_function_name(var_one, var_two, var_three, var_four) foo = long_function_name( var_one, var_two, var_three, var_four) foo = long_function_name( var_one, var_two, var_three, var_four ) foo = { a, b} foo = { a, b, } in our codebase. Sometimes different ways of closing a thing is right next to each other like in the example above. Now is there a checker or a rule for pylint or flake or special checker that would just ensure: if you have a hanging indent, that the closing bracket, curly brackets or parentheses are always in a new line, and that we have a trailing comma above them. Consistency is key in a clean codebase, and we can't rely on devs to stick to rules if those aren't automatically checked. So I need a checker for the cases mentioned.
has answer: http://stackoverflow.com/a/62430982
score: 8
has comment: http://stackoverflow.com/comment/98827112
upvote count: 8
favorite count: 0

http://stackoverflow.com/comment/85578238
comment on: http://stackoverflow.com/a/49287082
type: AnswerComment
has text: Now it works, but I don't always getting a line in return of my imput. Working: enter text to search: moon That text is found at line(s) [8] Not working: enter text to search: dream That text is found at line(s) [] Can I solve this somehow?
score: 0
type: Comment

http://stackoverflow.com/comment/86205481
comment on: http://stackoverflow.com/a/49598461
score: 1
has text: Sorry, I am new here :) Here are links: 1. https://zhuanlan.zhihu.com/p/29229244 2.1 https://pan.baidu.com/s/1gfGhPLp 2.2 https://pan.baidu.com/s/1pLv8Mx1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49366702
has comment: http://stackoverflow.com/comment/85734089
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49366548
has body: Your issue is that you are deleting keys from the objects and not the whole objects. import json if __name__ == "__main__": json_data = "[{\r\n\t\t\"Domain\": \"google.com\",\r\n\t\t\"A\": [\"172.217.22.46\"],\r\n\t\t\"AAAA\": [\"2a00:1450:4001:81e::200e\"],\r\n\t\t\"CAA\": [\"0 issue \\\"pki.goog\\\"\"],\r\n\t\t\"MX\": [\"20 alt1.aspmx.l.google.com.\", \"30 alt2.aspmx.l.google.com.\", \"10 aspmx.l.google.com.\", \"40 alt3.aspmx.l.google.com.\", \"50 alt4.aspmx.l.google.com.\"],\r\n\t\t\"NS\": [\"ns1.google.com.\", \"ns3.google.com.\", \"ns2.google.com.\", \"ns4.google.com.\"],\r\n\t\t\"SOA\": [\"ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60\"],\r\n\t\t\"TXT\": [\"\\\"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e\\\"\", \"\\\"v=spf1 include:_spf.google.com ~all\\\"\"],\r\n\t\t\"Country\": [\"United States\"],\r\n\t\t\"Hostname\": [\"'fra15s16-in-f46.1e100.net'\"],\r\n\t\t\"SSL\": [\"Google Internet Authority G2\"],\r\n\t\t\"WHOIS\": [8400],\r\n\t\t\"TTL\": [\"24\"]\r\n\t}, {\r\n\t\t\"Domain\": \"\",\r\n\t\t\"NS\": [\"a.root-servers.net.\", \"h.root-servers.net.\", \"g.root-servers.net.\", \"i.root-servers.net.\", \"d.root-servers.net.\", \"k.root-servers.net.\", \"c.root-servers.net.\", \"l.root-servers.net.\", \"e.root-servers.net.\", \"m.root-servers.net.\", \"f.root-servers.net.\", \"j.root-servers.net.\", \"b.root-servers.net.\"],\r\n\t\t\"SOA\": [\"a.root-servers.net. nstld.verisign-grs.com. 2018031700 1800 900 604800 86400\"],\r\n\t\t\"A\": [],\r\n\t\t\"SSL\": [\"None\"],\r\n\t\t\"WHOIS\": [0],\r\n\t\t\"TTL\": [null]\r\n\t}, {\r\n\t\t\"Domain\": \"facebook.com\",\r\n\t\t\"A\": [\"157.240.20.35\"],\r\n\t\t\"AAAA\": [\"2a03:2880:f11c:8183:face:b00c:0:25de\"],\r\n\t\t\"MX\": [\"10 msgin.vvv.facebook.com.\"],\r\n\t\t\"NS\": [\"a.ns.facebook.com.\", \"b.ns.facebook.com.\"],\r\n\t\t\"SOA\": [\"a.ns.facebook.com. dns.facebook.com. 1521364737 14400 1800 604800 300\"],\r\n\t\t\"TXT\": [\"\\\"v=spf1 redirect=_spf.facebook.com\\\"\"],\r\n\t\t\"Country\"…
type: Answer

http://stackoverflow.com/q/49329385
answer count: 2
has answer: http://stackoverflow.com/a/49329612
tagged with: python
linked to: http://stackoverflow.com/q/15496051
type: AnsweredQuestion
score: 0
tagged with: sql
has comment: http://stackoverflow.com/comment/85663586
accepted answer: http://stackoverflow.com/a/49329612
has title: Make a function of SQL query with optional 'where' clauses
has body: Lets say I have a function that query some table company.workers, for example (pseudo code): def sql_query(dept, prof, hireDate): q = """SELECT * FROM company.workers WHERE department = {0} AND profession = {1} AND hire_date &gt; {2}""".format(dept, prof, hireDate) cur.execute(q) return cur What if I want to allow the user the query only on dept and prof, with hireDate being optional? This is the solution I came up with: def sql_query(dept, prof, *args): if args: q = """SELECT * FROM company.workers WHERE department = {0} AND profession = {1} AND hire_date &gt; {2}""".format(dept, prof, args[0]) else: q = """SELECT * FROM company.workers WHERE department = {0} AND profession = {1} """.format(dept, prof) cur.execute(q) return cur #the function could be called as so: sql_query('20', 'Engineer', (2017-12-10)) However I think this is subotimal. What if I want to allow several optional coloumns to query? If I make it two, I have 4 options to handle, which is a lot of else-if blocks to make. Is there a more efficient/elegant solution?
has answer: http://stackoverflow.com/a/49330467
type: Question
possible better answer: http://stackoverflow.com/a/49330467

http://stackoverflow.com/comment/85868470
score: 0
comment on: http://stackoverflow.com/a/49419002
type: Comment
has text: Or are you trying to print the string after UTF-8 decoding? Don't do that.
type: AnswerComment

http://stackoverflow.com/comment/85729158
score: 0
has text: @sascha, I tried all scipy optimizer that does not allow constraints and play with different tolerance setting. It all terminates close at the "joining point" of the piece wise functions
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49356117

read-write
tags question: http://stackoverflow.com/q/49329010
type: Tag
tag name: read-write

http://stackoverflow.com/a/49417561
upvote count: 1
answers question: http://stackoverflow.com/q/49396943
has comment: http://stackoverflow.com/comment/85837232
score: 1
type: Answer
has body: You can use the networkx library to determine clusters or sub-groups of graphs. Given from string import ascii_uppercase as uppercase import networkx as nx import matplotlib.pyplot as plt %matplotlib inline d = { 1: [4], 2: [3, 5], 3: [2, 5], 4: [1, 6], 5: [2, 3], 6: [4, 8], 7: [9, 10], 8: [6, 11], 9: [7, 10], 10: [7, 9], 11: [8] } Code G = nx.from_dict_of_lists(d) # Label sub-groups sub_graphs = list(nx.connected_component_subgraphs(G)) {val: label for label, sg in zip(uppercase, sub_graphs) for val in sg.nodes()} # {1: 'A', 2: 'B', 3: 'B', 4: 'A', 5: 'B', 6: 'A', 7: 'C', 8: 'A', 9: 'C', 10: 'C', 11: 'A'} Details For easier visualization, here are the labeled sub-groups (see also motivating code): # Printed subgroups for label, sg in zip(uppercase, sub_graphs): print("Subgraph {}: contains {}".format(label, sg.nodes())) # Subgraph A: contains [8, 1, 11, 4, 6] # Subgraph B: contains [2, 3, 5] # Subgraph C: contains [9, 10, 7] Although I would ultimately recommend a resulting dict of lists for cleaner grouping of data: {label: sg.nodes() for label, sg in zip(uppercase, sub_graphs)} # {'A': [8, 1, 11, 4, 6], 'B': [2, 3, 5], 'C': [9, 10, 7]} In addition, you can optionally plot these graphs: # Plot graphs in networkx (optional) nx.draw(G, with_labels=True)
downvote count: 0

http://stackoverflow.com/comment/85808227
comment on: http://stackoverflow.com/q/49398457
type: Comment
score: 0
has text: @JahKnows `INPUT_SIZE=384`
type: QuestionComment

http://stackoverflow.com/comment/85876242
type: QuestionComment
comment on: http://stackoverflow.com/q/49437153
has text: What do you expect the result to look like exactly? `{'key': [500, 1000]}`…? Hint, HINT, **HINT**
type: Comment
score: 2

http://stackoverflow.com/comment/85593027
type: Comment
has text: If you know how many bins there are and what color they should be then `hist` accepts a list of colors
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49290266

http://stackoverflow.com/comment/85846241
type: AnswerComment
has text: @Ekoar. That should not be a problem.
type: Comment
comment on: http://stackoverflow.com/a/49422686
score: 0

http://stackoverflow.com/a/49345445
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85691640
accepted answer of: http://stackoverflow.com/q/49343907
answers question: http://stackoverflow.com/q/49343907
upvote count: 10
score: 10
type: Answer
has body: In Windows processes are not forked as in Linux/Unix. Instead they are spawned, which means that a new Python interpreter is started for each new multiprocessing.Process. This means that all global variables are re-initialized and if you have somehow manipulated them along the way, this will not be seen by the spawned processes. A solution to the problem is to pass the globals to the Pool initilaizer and then from there make it global also in the spawned process: from multiprocessing import Pool def init_pool(the_list): global some_list some_list = the_list def access_some_list(index): return some_list[index] if __name__ == "__main__": some_list = [24, 12, 6, 3] indexes = [3, 2, 1, 0] pool = Pool(initializer=init_pool, initargs=(some_list,)) result = pool.map(access_some_list, indexes) print(result) In this setup, you will copy the globals to each new process and they will then be accessible, however, as always, any updates done from there on will not be propagated to any other process. For that you will need something like a proper multiprocessing.Manager. As an extra comment, from here it is clear that global variables can be dangerous, because it is hard to understand what values they will take in the different processes.

http://stackoverflow.com/q/49429666
tagged with: python
linked to: http://stackoverflow.com/q/394809
has answer: http://stackoverflow.com/a/49430003
accepted answer: http://stackoverflow.com/a/49430021
type: AnsweredQuestion
has body: I'm reading the codes about a TF official example about cifar10 on https://github.com/tensorflow/models/blob/master/official/resnet/cifar10_main.py and I have some questions: In the function input_fn, what does num_images = is_training and _NUM_IMAGES['train'] or _NUM_IMAGES['validation'] ... mean? How can we get the right size of data while training and validating through this function? In the function main, there's a similar one input_function = FLAGS.use_synthetic_data and get_synth_input_fn() or input_fn Again, I don't know how it works.
has title: Boolean expression in Tensorflow CIFAR-10 tutorial
answer count: 3
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
tagged with: conditional-operator
possible better answer: http://stackoverflow.com/a/49429961
type: Question
has answer: http://stackoverflow.com/a/49430021
has answer: http://stackoverflow.com/a/49429961
tagged with: boolean-expression

http://stackoverflow.com/comment/85619397
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49308534
type: QuestionComment
has text: Please copy and paste instead of a screen shot. It would be easier for us.

http://stackoverflow.com/comment/85637677
comment on: http://stackoverflow.com/q/49317885
type: Comment
type: QuestionComment
has text: Okay I've updated my json.load method to add parameter "object_pairs_hook=OrderedDict", but next ?
score: 0

http://stackoverflow.com/comment/85778378
has text: Because "Shoes in Hyderabad" and "Shoe shops in Hyderabad" are expected to return more or less the same kind of results if a google search is done.
comment on: http://stackoverflow.com/q/49388257
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49401065
accepted answer: http://stackoverflow.com/a/49401210
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49401210
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85803765
type: AnsweredQuestion
tagged with: python-2.7
has title: How function len replace text in Python
tagged with: python
has comment: http://stackoverflow.com/comment/85803847
tagged with: replace
type: Question
has body: How the code len(marker) in function replaced = line[:pos] + replacement + line[pos+len(marker):] has removed the value of the string marker in the output as its is used to find the length of the string. help me to understand. #Example 1 marker = "AFK" replacement = "away from keyboard" line = "I will now go to sleep and be AFK until lunch time tomorrow." pos = line.find(marker) replaced = line[:pos] + replacement + line[len(marker)+pos:] print replaced output I will now go to sleep and be away from keyboard until lunch time tomorrow.
has comment: http://stackoverflow.com/comment/85803621

http://stackoverflow.com/comment/85783363
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49390850
has text: @Mwspencer Yep, I just made a good guess here. I updated my answer with an update-able variable for future cases
type: Comment

http://stackoverflow.com/a/49434069
has body: &amp; is a bitwise and for operations e.g. In [5]: 1 &amp; 3 Out[5]: 1 "and" is what you are looking for, so the if line should be: if ("C" in row['key']) and (row['data2']=="NaN"):
answers question: http://stackoverflow.com/q/49433777
type: Answer
score: 0

http://stackoverflow.com/comment/85743288
type: Comment
type: AnswerComment
has text: I have posed my problem here please check it [link](https://stackoverflow.com/questions/49371157/what-is-the-kind-of-max-pooling-in-this-nlp-questionhierarchy-description)
comment on: http://stackoverflow.com/a/49365981
score: 0

http://stackoverflow.com/q/49319392
has title: How to upload data to Amazon Redshift
type: Question
tagged with: amazon-redshift
type: UnansweredQuestion
has body: I want to upload data to a Redshift automatically. I know how to access redshift and extract data. but I don't know how to load data into a table. I heard that you need a commit feature. I want to know how to commit or the name of the module (like pycopg2).
tagged with: python
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/49329561
score: 0
answer count: 1

http://stackoverflow.com/q/49386031
has comment: http://stackoverflow.com/comment/85775171
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/85778086
duplicate of: http://stackoverflow.com/q/43865989
has title: modelname.objects.all() displays error
has comment: http://stackoverflow.com/comment/85776147
has comment: http://stackoverflow.com/comment/85776514
answer count: 0
has body: I get an error whenever i try to access the data from database in the program. This is models.py from django.db import models class Files(models.Model): serno=models.IntegerField(primary_key=True) firstfile=models.CharField(max_length=1000) secondfile=models.CharField(max_length=1000) def __str__(self): return self.firstfile +' '+ self.secondfile This is views.py from .models import Files def getfile(request): data=Files.objects.all() return data This displays an error at objects in "Files.objects.all()" The error is Unresolved attribute reference 'objects' for class 'Files' This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items If I ignored that warning and continued with my program, the following happened Consider an example program example.py import os os.environ['DJANGO_SETTINGS_MODULE']='website.settings' import django django.setup() from plagiarism_check.views import getfile dbf1=getfile print(dbf1) I expect an output of the data in the database table "Files". But instead I get something like this &lt;function getfile at 0x0000000003DF1D08&gt; PS: I've tried to print Files.objects.all() in powershell and it worked. But I want to access them in my example.py
has comment: http://stackoverflow.com/comment/85778408
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85778837
has comment: http://stackoverflow.com/comment/85777893
tagged with: django
has comment: http://stackoverflow.com/comment/85773462
type: Question
has comment: http://stackoverflow.com/comment/85776449
linked to: http://stackoverflow.com/q/43865989
has comment: http://stackoverflow.com/comment/85778676

http://stackoverflow.com/comment/85913336
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49324798
has text: Solved. It is because that I forgot to configure the settings of robotstxt. According to the debug information, the spider was "Forbidden by robots.txt: <GET http://weixin.sogou.com>".

http://stackoverflow.com/a/49418309
has comment: http://stackoverflow.com/comment/85838582
accepted answer of: http://stackoverflow.com/q/49417023
answers question: http://stackoverflow.com/q/49417023
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85838545
score: 0
has body: Here is an example of how you can restructure your code. def translate(word, language): en_word = word.lower() lang = language.lower() if lang == "french": if en_word == "cat": return "chat" elif en_word == "dog": return "chein" elif lang == "german": if en_word == "cat": return "katze" elif en_word == "dog": return "hund" elif lang == "spanish": if en_word == "cat": return "gato" elif en_word == "dog": return "perro" myword = 'cat' mylanguage = 'french' res = translate(myword, mylanguage) print('The translation of {0} in {1} is {2}'.format(myword, mylanguage.title(), res)) Explanation Use elif instead of unnecessary repeated if statements. Have your function return a value instead of print. Use str.format to incorporate variables in your print statement outside your function.

http://stackoverflow.com/a/49442410
has comment: http://stackoverflow.com/comment/85900564
answers question: http://stackoverflow.com/q/49428449
upvote count: 2
downvote count: 0
type: Answer
has body: To spawn your enemies at random locations around your screen, it is very simple. There are two possible ways: First, you could modify the enemy init() to have self.x and self.y be randint, as shown below. self.x = random.randint(0, display_width) self.y = random.randint(0, display_height) This method works, but limits your ability to place enemies in specific locations, and will be anywhere, and can place enemies where you don't want them. The second way is basically the first way, but it is written when defining a new enemy redspider = enemy(random.randint(0, screen_width), random.randint(0, screen_height), 80, 84, 650) This also works but when defining each new enemy manually it will take more time. But, this allow you to still place enemies in certain locations when used later. Both of these have flaws because they are placed randomly, but you can create functions to limit where thee are placed. As for your with appending enemies in a list, you can do this: enemies = [] maxenemies = 10 for i in range(maxenemies): enemies.append(enemy(random.randint(0, screen_width), random.randint(0, screen_height), 80, 84, 650)) This pushes maxenemies amount of enemies into the enemies list, which can be drawn and used later. maxenemies is just optional, but would be something I would suggest to do for readability. Tell me if these suggestions work for you.
score: 2

http://stackoverflow.com/comment/85737606
comment on: http://stackoverflow.com/a/49363441
type: Comment
type: AnswerComment
has text: Consider accepting this as the answer if it solves your problem. Thanks
score: 0

http://stackoverflow.com/a/49331398
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85664918
answers question: http://stackoverflow.com/q/49331336
type: Answer
has body: Not sure if this is more elegant than what you are trying to avoid, but: dic01 = defaultdict(lambda: defaultdict(lambda: [0,0,0])) dic01['year2018']['jul_to_sep_temperature'][0] = 25 you can nest defaultdicts however you want by passing lambda functions
score: 2

http://stackoverflow.com/a/49394738
has body: It looks as though you end up with a list of values the same length as the dataframe. You can assign these values as a new column in the dataframe by simply doing df_price['new_column']=list_of_values This might be what you require.
type: Answer
has comment: http://stackoverflow.com/comment/85791587
score: 0
answers question: http://stackoverflow.com/q/49394616

http://stackoverflow.com/comment/85846868
type: Comment
has text: With which IDE you tested it? Someone can confirm that this is bug in VS-Code?
type: QuestionComment
comment on: http://stackoverflow.com/q/49409828
score: 0

http://stackoverflow.com/q/49432511
tagged with: pandas
has comment: http://stackoverflow.com/comment/85867945
tagged with: python
has comment: http://stackoverflow.com/comment/85866789
has title: TypeError: 'bool' object is not callable after resetting index on Pandas Dataframe
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85870854
has comment: http://stackoverflow.com/comment/85868881
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85868969
has body: Getting this error when trying to reset index for a simple pandas dataframe. My input is: df2 = a.reset_index(drop=True) Output TypeError Traceback (most recent call last) &lt;ipython-input-97-68f172e9a129&gt; in &lt;module&gt;() ----&gt; 1 df2 = a.reset_index(drop=True) 2 df2` TypeError: 'bool' object is not callable This doesn't usually happen when I reset indices and also couldn't find anything on here when the error involves a reset. Thanks
has answer: http://stackoverflow.com/a/49434689
has answer: http://stackoverflow.com/a/73272513

http://stackoverflow.com/q/49352918
favorite count: 0
tagged with: django-views
has body: In my Django/Python application I am passing multiple iterable objects from views.py to index.html. I am essentially trying to make a standard for loop in which you can get an item by its index. Once I am iterating through the first object, how can I get the respective index of another iterable in that same loop? Conditions: All of the arrays will always be equal in length, but their length will change on a daily basis. views.py name = ['John', 'Kim', 'Tim', 'Jill'] age = ['20', '30', '52', '27'] state = ['IN', 'IL', 'CA', 'TX'] city = ['Muncie', 'Champaign', 'Fresno', 'Dallas'] def index(request): args = {'names': name, 'ages': age, 'states': state, 'cities': city} return render(request, 'index.html', args) index.html {% extends 'base.html' %} {% load staticfiles %} {% block Data %} {% for name in names %} &lt;p&gt;{{ name }}&lt;/p&gt; &lt;p&gt;{{ age.forloop.counter0 }}&lt;/p&gt; &lt;p&gt;{{ state.forloop.counter0 }}&lt;/p&gt; &lt;p&gt;{{ city.forloop.counter0 }}&lt;/p&gt; {% endfor %} {% endblock %} As you can see, I thought I would use 'forloop.counter0' as my index. But it doesn't work that way apparently. Any suggestions on how to achieve this goal? Thanks in advance!
tagged with: python
has title: How to get the i'th item in an iterable object. Django/Python
has answer: http://stackoverflow.com/a/49352983
type: Question
tagged with: django-templates
answer count: 2
has answer: http://stackoverflow.com/a/49353073
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: django
upvote count: 1

http://stackoverflow.com/q/49395904
tagged with: list
has comment: http://stackoverflow.com/comment/85815068
downvote count: 0
has answer: http://stackoverflow.com/a/69583760
has title: How to optimise list operations? (CodeFights)
favorite count: 0
has answer: http://stackoverflow.com/a/49555437
type: Question
has answer: http://stackoverflow.com/a/49396200
accepted answer: http://stackoverflow.com/a/49396200
upvote count: 2
linked to: http://stackoverflow.com/q/43017251
has body: So I have a function that performs just fine on small lists. It's function is to check if removing one element from the sequence will make the sequence a strictly increasing sequence: def almostIncreasingSequence(sequence): length = len(sequence) for i in range(1, length): newSequence = sequence[:i-1] + sequence[i:] if checkIfSorted(newSequence, length): return True return checkIfSorted(sequence[:length-1], length) def checkIfSorted(sequence, length): for i in range(1, length - 1): if sequence[i-1] &gt;= sequence[i]: return False return True But I need it to work on lists up to 100,000 elements long. What sort of optimizations could I make for this to work faster? Right now, it's abysmally slow on lists of 100,000, working through a few thousand elements a second.
has answer: http://stackoverflow.com/a/49396647
possible better answer: http://stackoverflow.com/a/49396647
tagged with: python
has comment: http://stackoverflow.com/comment/86117549
answer count: 4
tagged with: optimization
score: 2
has comment: http://stackoverflow.com/comment/85832737
type: AnsweredQuestion

http://stackoverflow.com/comment/85825839
type: AnswerComment
has text: You can define `references = []` outside loop, on each iteration do `references.extend([link.get_attribute("href") for link in links])` and after loop you can write `"\n".join(references)` into text doc
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49410058

http://stackoverflow.com/a/49313706
has comment: http://stackoverflow.com/comment/85631242
downvote count: 0
upvote count: 1
score: 1
has body: Make sure you've installed pandas_datareader lib? Go to your terminal and type this : pip install pandas_datareader
has comment: http://stackoverflow.com/comment/85631164
type: Answer
answers question: http://stackoverflow.com/q/49313585

http://stackoverflow.com/a/49400140
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49376263
has body: finally i found my mistake , and it was just a typo, in my views.py views.py 'notifiy_url' : 'http://{}{}'.format(host, reverse('paypal-ipn')), # should be changed to 'notify_url' : 'http://{}{}'.format(host, reverse('paypal-ipn')), # also here i have set the logged in user 'payer': request.user,
type: Answer
accepted answer of: http://stackoverflow.com/q/49376263
downvote count: 0

http://stackoverflow.com/q/49343043
tagged with: python-3.x
downvote count: 5
type: UnansweredQuestion
score: -3
answer count: 1
has answer: http://stackoverflow.com/a/49343103
tagged with: python
has comment: http://stackoverflow.com/comment/85686441
has comment: http://stackoverflow.com/comment/85686316
has comment: http://stackoverflow.com/comment/85686614
tagged with: text
has title: How to reorder the text blocks of a text file?
has body: I have a text file like this: Label: A Text1 Text2 Label: B Text3 Text4 Label: C Text5 Text6 I would like to reorder the blocks of text in the inverse order, maintaining the original order within the blocks. Like this: Label: C Text5 Text6 Label: B Text3 Text4 Label: A Text1 Text2 The line with Label always contains the same text, I'm adding here the letters for a better explanation. Also, the Label is always at the same position and uses a full line. The only constrains are: Python 3.6 and no external modules. I can load the full file in memory, so no need for read the file line by line if you don't want. I know how to find the lines with the Label but I don't know how to select the block of text to change the order. Any idea?.
tagged with: text-files
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/49321445
has body: There is directory A, which contains several subdirectories of txt files. There is another directory B, which contains txt files. There are several txt files in A that have the same name in B but different content. Now I want to move the txt files in B to A and cover the files with the same name. My Code is as below: import shutil import os src = '/PATH/TO/B' dst = '/PATH/TO/A' file_list = [] for filename in os.walk(dst): file_list.append(filename) for root, dirs, files in os.walk(src): for file in files: if file in file_list: ##os.remove(dst/file[:-4] + '.txt') shutil.move(os.path.join(src,file),os.path.join(dst,file)) But when I run this, it did nothing. Can anyone help me about it?
has comment: http://stackoverflow.com/comment/85644222
favorite count: 0
type: Question
has title: How to replace the txt file in a directory
has comment: http://stackoverflow.com/comment/85644100
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/49321967
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49321967
score: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49396133
accepted answer of: http://stackoverflow.com/q/49386039
score: 2
upvote count: 2
downvote count: 0
has body: It is possible to handle this by posting using the signal/slot approach as you suggest (but would like to avoid) or by posting a custom event back to the Qt event loop via QApplication.instance().postEvent() both of these methods are fundamentally flawed because they rely on the Qt event loop functioning correctly (which may not be the case if part of your application has entered an error state). The only reliable way to show an exception in a graphical message box is to have your exception handler launch a new process that creates the message box. It's reasonably easy to write a standalone application that shows sys.argv[1] in the message box, and to launch that using subprocess.Popen from your excepthook handler. My colleagues and I have done this for a large Qt project, and it works very well. We've also gone to the effort of launching the message box using Tkinter (which ships by default with almost every Python install) rather than Qt, just in case the exception is caused by a missing or broken installation of Qt. It's open-sourced here.
has comment: http://stackoverflow.com/comment/85811057
type: Answer
has comment: http://stackoverflow.com/comment/85804038
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49386039

http://stackoverflow.com/a/49389127
answers question: http://stackoverflow.com/q/49388887
type: Answer
has body: You can try this: import re l = ['0 , hellp,\t2,\t BB , -\n', ' 1 ,\t \t knock \t , BB,N,- '] new_l = [','.join(filter(None, re.split('[\s,\t\n]+', i))) for i in l] Output: ['0,hellp,2,BB,-', '1,knock,BB,N,-']
score: 0

http://stackoverflow.com/q/49375744
has comment: http://stackoverflow.com/comment/85753077
has comment: http://stackoverflow.com/comment/85753085
has answer: http://stackoverflow.com/a/49375835
accepted answer: http://stackoverflow.com/a/49375835
has comment: http://stackoverflow.com/comment/85753143
favorite count: 0
has comment: http://stackoverflow.com/comment/85752698
type: Question
tagged with: python-3.x
has title: Abstraction Layer On Top of Sqlalchemy
has comment: http://stackoverflow.com/comment/85752982
has body: I am on a Python 3.6 project that uses Sqlalchemy where we want another layer of abstraction over Sqlalchemy. This will allow us to more easily replace Sqlalchemy with another library if desired. In this example it is the DbHelper class: dbhelper.py from dbconn import dbconn from models.animals import Dogs class DbHelper(): @staticmethod def get_dog_by_nickname(nickname): return dbconn.session.query(Dogs).get(nickname) main.py from dbhelper import DbHelper class Dog(): def __init__(self, nickname, breed, age): self.nickname = nickname self.breed = breed self.age = age @classmethod def using_nickname(cls, nickname): row = DbHelper.get_dog_by_nickname(nickname) return Dog(row.id, row.breed, row.age) dog = Dog.using_nickname('Tom') Question: Is there a better method than creating the DbHelper class for use as a container and having only staticmethod in it? I have read that this is not pythonic. Converting all the staticmethod functions in dbhelper.py to regular methods will populate the namespace when we do from dbhelper import *
has comment: http://stackoverflow.com/comment/85752855
has comment: http://stackoverflow.com/comment/85753019
tagged with: python
has comment: http://stackoverflow.com/comment/85752824
has comment: http://stackoverflow.com/comment/85753026
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/85752883
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85752999
downvote count: 0
has comment: http://stackoverflow.com/comment/85752998
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85752725
answer count: 1

http://stackoverflow.com/comment/85787967
type: AnswerComment
has text: Is there any way to get atributes of error? I tried to call strerror() but it returned "TypeError: 'member_descriptor' object is not callable"
comment on: http://stackoverflow.com/a/49393131
type: Comment
score: 0

http://stackoverflow.com/comment/85795697
has text: Can you set yourself a simpler problem to start? Suppose you had range(4): [0,1,2,3], and you wanted all of these sets of pairs. How many such sets are there? Can you do it on paper? How would you do it with range(5)?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49396895
type: Comment

http://stackoverflow.com/q/49428916
score: 1
has answer: http://stackoverflow.com/a/49428966
favorite count: 0
type: Question
tagged with: numpy
has title: How to create an array with dimension based on a variable?
tagged with: python
type: AnsweredQuestion
has body: I've got two variables: dim and terms. I'd like to use these variables to define an array. For example, If dim=2 and terms=4, I'd like m=np.zeros((4,4)) If dim=3 and terms=4, I'd like m=np.zeros((4,4,4)) If dim=3 and terms=3, I'd like m=np.zeros((3,3,3)) I tried defining the argument using a string but it doesn't accept that.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49428966
upvote count: 1

http://stackoverflow.com/comment/85672649
has text: Did either of the posted solution work for you?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49296660

http://stackoverflow.com/q/49364097
has answer: http://stackoverflow.com/a/49364382
has body: I have crawler that extract links from page only if the link text include given text and I'm writing the output to html file. Its working but I would like to add whole link text next to these links like this - "Junior Java developer - https://www.jobs.cz/junior-developer/" How can I do this? Thanks import requests from bs4 import BeautifulSoup import re def jobs_crawler(max_pages): page = 1 file_name = 'links.html' while page &lt; max_pages: url = 'https://www.jobs.cz/prace/praha/?field%5B%5D=200900011&amp;field%5B%5D=200900012&amp;field%5B%5D=200900013&amp;page=' + str(page) source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text) page += 1 file = open(file_name,'w') for link in soup.find_all('a', {'class': 'search-list__main-info__title__link'}, text=re.compile('IT', re.IGNORECASE)): href = link.get('href') + '\n' file.write('&lt;a href="' + href + '"&gt;'+ 'LINK TEXT HERE' + '&lt;/a&gt;' + '&lt;br /&gt;') print(href) file.close() print('Saved to %s' % file_name) jobs_crawler(5)
has answer: http://stackoverflow.com/a/49364551
tagged with: python
has comment: http://stackoverflow.com/comment/85728609
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/11716380
answer count: 2
has title: Extracting link text and writing to file
accepted answer: http://stackoverflow.com/a/49364551
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/85728641
type: Question
possible better answer: http://stackoverflow.com/a/49364382

http://stackoverflow.com/comment/85800096
score: 0
type: Comment
has text: as I mentioned in my first post, the only way to get this work, is by converting the line to string, and deleting the brackets. Using [1:-1], i.e: y = np.fromstring( str(lst[1])[1:-1], dtype=np.float, sep=',' )
comment on: http://stackoverflow.com/a/49397286
type: AnswerComment

http://stackoverflow.com/comment/85820082
score: 2
type: AnswerComment
has text: nice use of `else` on the `for` and a solid, basic approach. +1
comment on: http://stackoverflow.com/a/49409194
type: Comment

http://stackoverflow.com/comment/85885777
type: QuestionComment
has text: Did you check how many rows do yo have in the `songs` table? It looks like the code snippet you posted should be able to fetch the desired rows, most likely you only have one row in that table.
score: 0
comment on: http://stackoverflow.com/q/49438354
type: Comment

http://stackoverflow.com/q/49427320
accepted answer: http://stackoverflow.com/a/49429072
favorite count: 0
tagged with: networkx
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49429072
has body: I need a graph with N clusters, that somewhat represents the structure of social networks. I planned to go about this by creating N graphs with barabasi albert structure, and then connecting them by a single node. import networkx as nx a = nx.barabasi_albert_graph(10,2) b = nx.barabasi_albert_graph(10,2) nx.draw(a) nx.draw(b) what I want is them connected like this: But I cannot see or find any simple way of doing this, are there any networkX functionality that can do just this?
tagged with: python
has title: Joining two networkx graphs on a single edge
tagged with: graph
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85654848
has text: @DeliriousLettuce I can tell you one thing that it works similar to the calendar in https://www.kayak.com/
comment on: http://stackoverflow.com/q/49326346
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49419744
has answer: http://stackoverflow.com/a/49419800
tagged with: python
has comment: http://stackoverflow.com/comment/85840940
tagged with: list
score: 0
tagged with: strip
answer count: 3
has answer: http://stackoverflow.com/a/49419776
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: strip comma's from a file
type: UnansweredQuestion
has body: txt = open("document.txt").read() spt = txt.split() new_list = [] for i in spt: if i.endswith(','): w=i.rstrip(',') new_list.append(w) elif i.endswith('.'): w=i.rstrip('.') new_list.append(w) else: new_list.append(i) print(new_list) I'm trying to go through my "document.txt" word by word and strip any comma at the end of the word. This is a learning exercise for me. I know there are "better" shorter ways to do this but I'm trying to learn the in's and out's of python. I have seen a lot of code on here that touches on this question, but I'm still having a hard time getting it to compile Anything. Any help would be greatly appreciated.
has answer: http://stackoverflow.com/a/49421303

http://stackoverflow.com/comment/85869103
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49433496
has text: @ealeon, a CA store is used to decide if the server's certificate is signed by a valid CA (used to prove who the server is *to the client*). A client certificate is used to prove who the client is *to the server*, in conjunction with a paired private key.
type: Comment

http://stackoverflow.com/comment/85611311
type: Comment
comment on: http://stackoverflow.com/q/49302884
type: QuestionComment
score: 0
has text: I could do it with an apply and a loop and it's (off course slow).

http://stackoverflow.com/a/49388337
downvote count: 1
has comment: http://stackoverflow.com/comment/93533162
has comment: http://stackoverflow.com/comment/89834770
score: 5
has body: I just found this: Illegal instruction (core dumped) after running import tensorflow This problem seems to be caused by a set of instructions that are not hardware implemented in some older processors (AVX instruction set). Since they are not implemented in hardware, there's no real fix for this problem. If I understood it correctly, and a workaround is to downgrade tensorflow from 1.6.0 to 1.5.0, this also applies to the GPU version. It worked for me. I Will mark this as answered for now, but if anyone have any good idea how to get version 1.6.0 working, please let me know.
type: Answer
has comment: http://stackoverflow.com/comment/88451945
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49327879
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49327879

http://stackoverflow.com/comment/91086916
score: 0
has text: Did you ever make progress on this? I am encountering a similar issue! All the best, thanks.
comment on: http://stackoverflow.com/q/49331835
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49384141
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49383977
has body: From the documentation for sys.exit: Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. This means that the outer try except loop is catching the SystemExit exception and causing it to pass. You can add this exception to the outer block and call it again.
type: Answer
score: 1

http://stackoverflow.com/a/64031801
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/113228899
has body: Yes, python has a similar feature, assignment def MyPrint(name): print(name) return name FIRST_NAME = MyPrint("Moon") FAMILY_NAME = MyPrint("Sun") Note that C++ also has this feature.
upvote count: 0
downvote count: 3
answers question: http://stackoverflow.com/q/49291033

http://stackoverflow.com/q/49330843
has comment: http://stackoverflow.com/comment/85663741
linked to: http://stackoverflow.com/q/8011797
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85663743
has comment: http://stackoverflow.com/comment/85663756
upvote count: 3
score: -4
answer count: 1
downvote count: 7
favorite count: 0
type: Question
has body: In this example. from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line too, how? in_file = open(from_file) indata = in_file.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL- C to abort." raw_input() out_file = open(to_file, 'w') out_file.write(indata) print "Alright, all done." out_file.close() in_file.close() on line 8 to 9 can't I just write it like this? indata = open(from_file, 'r')
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49330893
tagged with: python
has title: What's the purpose of 'r'

http://stackoverflow.com/q/49354590
tagged with: python
has answer: http://stackoverflow.com/a/49358005
accepted answer: http://stackoverflow.com/a/49358005
type: Question
has title: How to convert numpy list to geoTIFF in python?
tagged with: numpy
answer count: 1
tagged with: geotiff
type: AnsweredQuestion
score: 0
has body: I haven't found answer on this simple question. Please help. How to convert Qcal (numpy list) to TIFF image ? Everything I've found doesn't really work. import math import numpy as np from osgeo import gdal substr1 = 'RADIANCE_MULT_BAND_10' substr2 = 'RADIANCE_ADD_BAND_10' substr3 = 'K1_CONSTANT_BAND_10' substr4 = 'K2_CONSTANT_BAND_10' RADIANCE_MULT_BAND_10 = 1 RADIANCE_ADD_BAND_10 = 1 K1_CONSTANT_BAND_10 = 1 K2_CONSTANT_BAND_10 = 1 with open('LC08_L1TP_180028_20170623_20170630_01_T1_MTL.txt') as file: for line in file: if substr1 in line: startIndex = line.find('=') RADIANCE_MULT_BAND_10 = float((line[startIndex+2:])) if substr2 in line: startIndex = line.find('=') RADIANCE_ADD_BAND_10 = float((line[startIndex + 2:])) if substr3 in line: startIndex = line.find('=') K1_CONSTANT_BAND_10 = float((line[startIndex + 2:])) if substr4 in line: startIndex = line.find('=') K2_CONSTANT_BAND_10 = float((line[startIndex + 2:])) ds = gdal.Open("B10.tif") Qcal = np.array(ds.GetRasterBand(1).ReadAsArray()) # Quantized and calibrated standard product pixel values (DN) for i in range(Qcal.shape[0]): for j in range(Qcal.shape[1]): Qcal[i][j] = RADIANCE_MULT_BAND_10 * Qcal[i][j] + RADIANCE_ADD_BAND_10 Qcal[i][j] = K2_CONSTANT_BAND_10 / math.log1p(K1_CONSTANT_BAND_10/Qcal+1)

http://stackoverflow.com/a/49436763
type: Answer
answers question: http://stackoverflow.com/q/49436367
has comment: http://stackoverflow.com/comment/85875714
downvote count: 5
has comment: http://stackoverflow.com/comment/117626803
upvote count: 1
has comment: http://stackoverflow.com/comment/85875827
has body: Yes, this is good OOP. You could inherit from the parent, and simply make methods in the parent class that you would call in an instance for the Cat or Dog class, so that you could add nothing to the Cat/Dog class: for example: class Animal(): def make_sound(self): print(self.sound) def make_dog_sound(self): print('bark') def make_cat_sound(self): print('meow') class Cat(Animal): pass class Dog(Animal): pass cat = Cat() cat.make_cat_sound() But what you did is also correct.
score: -4

utc
tags question: http://stackoverflow.com/q/49320170
tag name: utc
type: Tag
tags question: http://stackoverflow.com/q/49327464

http://stackoverflow.com/comment/85574699
comment on: http://stackoverflow.com/q/49283252
has text: I have updated the code!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85631388
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49314988
has text: provide complete traceback of an error
type: Comment

generator
type: Tag
tags question: http://stackoverflow.com/q/49404993
tag name: generator
tags question: http://stackoverflow.com/q/49415432
tags question: http://stackoverflow.com/q/49353955
tags question: http://stackoverflow.com/q/49344332
tags question: http://stackoverflow.com/q/49311084
tags question: http://stackoverflow.com/q/49362449
tags question: http://stackoverflow.com/q/49346154

http://stackoverflow.com/q/49331907
answer count: 1
has comment: http://stackoverflow.com/comment/85666057
score: -1
has answer: http://stackoverflow.com/a/52683793
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85666053
upvote count: 0
type: UnansweredQuestion
has title: how to run "custom_strategy" in Bitmex
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/85665833
tagged with: bitcoin
has body: currently I was working a bot in Bitcoin exchange Bitmex with python, Click here! I followed instruction and the sample program works!! but when I am trying to implement my own custom trading strategies and add some strategy code into custom_strategy.py. Run python custom_strategy.py in windows Powershell, nothing happened, no error information, no order has been placed in Testnet Bitmex. Can anyone help to me with this? did I do something wrong? $ python custom_strategy.py $ #nothing show my custom_strategy.py is quite simple: import sys from market_maker.market_maker import OrderManager class CustomOrderManager(OrderManager): buy_orders = [] sell_orders = [] ticker = self.exchange.get_ticker() buy_orders.append({'price': ticker["buy"], 'orderQty': 100, 'side': "Buy"}) sell_orders.append({'price': ticker["buy"]+50, 'orderQty': 100, 'side': "Sell"}) self.converge_orders(buy_orders, sell_orders) def run() -&gt; None: order_manager = CustomOrderManager() try: order_manager.run_loop() except (KeyboardInterrupt, SystemExit): sys.exit()

http://stackoverflow.com/a/49285964
type: Answer
answers question: http://stackoverflow.com/q/49284420
has comment: http://stackoverflow.com/comment/85610256
has comment: http://stackoverflow.com/comment/85610208
score: 0
has body: The issue, by design, with groupby is that only one series is passed. You need to perform some hacks to check Group_Id value when grouping by Person_Id. This seems to be expensive. Therefore, I find your solution efficient. However, if you really want to cut code and performance is not an issue, you can use df.groupby.apply as below. n = 100 person_id = np.random.randint(0,10,size=n) group_id = np.random.randint(0,3,size=n) score = np.random.rand(n) df = pd.DataFrame([person_id,group_id,score]).T df.columns = ['PERSON_ID','GROUP_ID','SCORE'] df = pd.concat([df]*1000) def original(df): score_summary = [] for person in df['PERSON_ID'].unique(): idx0 = (df['PERSON_ID'].values==person) &amp; (df['GROUP_ID'].values==0) score0 = np.mean(5.0*df.loc[idx0,'SCORE']+2) idx1 = (df['PERSON_ID'].values==person) &amp; (df['GROUP_ID'].values==1) score1 = np.mean(6.0*df.loc[idx1,'SCORE']+2) idx2 = (df['PERSON_ID'].values==person) &amp; (df['GROUP_ID'].values==2) score2 = np.mean(5.0*df.loc[idx2,'SCORE']+3) score_summary.append({'PERSON_ID':person, 'SCORE0': score0, 'SCORE1': score1, 'SCORE2': score2}) df_summary = pd.DataFrame(score_summary) return df_summary def jp(df): idx = {k: set(df[df['GROUP_ID'] == k].index) for k in (0, 1, 2)} d = {0: (5, 2), 1: (6, 2), 2: (5, 3)} def func(x): return tuple(d[k][0] * np.mean(x[x.index.isin(idx[k])]) + d[k][1] \ for k in (0, 1, 2)) return df.groupby(['PERSON_ID'])['SCORE'].apply(func).reset_index() %timeit original(df) # 39.7ms %timeit jp(df) # 78ms

http://stackoverflow.com/comment/85762363
type: QuestionComment
comment on: http://stackoverflow.com/q/49380736
score: 0
has text: Also, I can't reproduce your output. I get `False, True, False` as expected. Please post a [mcve] - remove the code that reads text from a file, and put the content of the file into the code instead. In the end we should get the same output as you just by copying your code and executing it.
type: Comment

http://stackoverflow.com/comment/85746999
type: Comment
type: QuestionComment
score: 0
has text: I got stuck again, so I will leave you to it. Good luck.
comment on: http://stackoverflow.com/q/49364409

http://stackoverflow.com/q/49290202
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85583551
has title: Does Python multiprocessing module need multi-core CPU?
has answer: http://stackoverflow.com/a/49290698
tagged with: python
has body: Do I need a multi-core CPU to take advantage of the Python multiprocessing module? Also, can someone tell me how it works under the hood?
upvote count: 3
score: 0
tagged with: cpu
downvote count: 3
answer count: 1

button
tags question: http://stackoverflow.com/q/49378827
tags question: http://stackoverflow.com/q/49323339
tags question: http://stackoverflow.com/q/49311773
tags question: http://stackoverflow.com/q/49338758
tag name: button
tags question: http://stackoverflow.com/q/49336415
type: Tag

http://stackoverflow.com/q/49431659
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85865293
has answer: http://stackoverflow.com/a/49431989
favorite count: 0
type: Question
has title: CSV Series is ambiguous Python
has body: I'm trying to filter my csv file. I have 3 columns and the first one is Espacio. I have an error with my sentence so I don't understand how can I do it because I ever filter my csv with this: import pandas as pd df = pd.read_csv('my.csv') if df['Espacio'] == '*': ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/85865170
linked to: http://stackoverflow.com/q/36921951

http://stackoverflow.com/comment/85734577
comment on: http://stackoverflow.com/a/49366677
score: 0
type: AnswerComment
has text: I'm never a fan of adding in unneeded libraries in a question where it wasn't explicitly asked for. See every C++ question I've asked where the answer was "Just use `Boost`...". OP may not be able to access external libraries. For instance I cannot access `pandas` on my config controlled work machine.
type: Comment

http://stackoverflow.com/a/49394806
has comment: http://stackoverflow.com/comment/85791639
type: AcceptedAnswer
has body: Another way to do it is using hex like so: filename = '1.txt' newfile = '2.txt' with open(filename, 'r') as f: numbers = f.read().splitlines() with open(newfile, 'w') as n: for num in numbers: n.write('{}\n'.format(hex(int(num))))
has comment: http://stackoverflow.com/comment/85791880
has comment: http://stackoverflow.com/comment/85792261
has comment: http://stackoverflow.com/comment/85792119
accepted answer of: http://stackoverflow.com/q/49394637
has comment: http://stackoverflow.com/comment/85791777
type: Answer
has comment: http://stackoverflow.com/comment/85792331
has comment: http://stackoverflow.com/comment/85791789
answers question: http://stackoverflow.com/q/49394637
has comment: http://stackoverflow.com/comment/85791975
has comment: http://stackoverflow.com/comment/85792062
score: 0

http://stackoverflow.com/comment/85825428
type: AnswerComment
has text: this is fantastic! One last question please. If you can't help I totally understand. So the final goal would be to use your code and the plots you created with subplots and have them in a table-like format. I checked what ImportanceOfBeingErnest did here: https://stackoverflow.com/questions/47779560/matplotlib-creating-a-table-with-line-plots-in-cells so the question for you is: could we have the graphs you have created as subplots column (col 6) and have in col 1 the name of the company, col 2 the avg, col 3 the value of the min, col 4 the value of the max, col 5 the curr. value?
comment on: http://stackoverflow.com/a/49366849
type: Comment
score: 0

http://stackoverflow.com/comment/85745738
has text: Let's just say that in the future I would like to edit the client list. Is it possible to not print client1, client2 and client3 if they already exist in the output.txt file and add client4 and client5 only? P.S. I don't want to "write" the file again because there will be additional lines without clients name, clients url and service.
type: Comment
comment on: http://stackoverflow.com/a/49367401
type: AnswerComment
score: 0

min
type: Tag
tags question: http://stackoverflow.com/q/49349782
tag name: min

selenium
tags question: http://stackoverflow.com/q/49321748
tags question: http://stackoverflow.com/q/49324021
tags question: http://stackoverflow.com/q/49346601
tags question: http://stackoverflow.com/q/49432864
tags question: http://stackoverflow.com/q/49434581
tags question: http://stackoverflow.com/q/49358679
tags question: http://stackoverflow.com/q/49412238
tags question: http://stackoverflow.com/q/49344994
tags question: http://stackoverflow.com/q/49353034
tags question: http://stackoverflow.com/q/49343858
tags question: http://stackoverflow.com/q/49288730
tags question: http://stackoverflow.com/q/49398660
tags question: http://stackoverflow.com/q/49436756
tags question: http://stackoverflow.com/q/49325855
tags question: http://stackoverflow.com/q/49352180
tags question: http://stackoverflow.com/q/49286760
tags question: http://stackoverflow.com/q/49407518
tags question: http://stackoverflow.com/q/49375222
tags question: http://stackoverflow.com/q/49361872
tags question: http://stackoverflow.com/q/49296620
tags question: http://stackoverflow.com/q/49411932
tags question: http://stackoverflow.com/q/49392658
tags question: http://stackoverflow.com/q/49339917
tags question: http://stackoverflow.com/q/49406625
tags question: http://stackoverflow.com/q/49402800
tags question: http://stackoverflow.com/q/49329719
tags question: http://stackoverflow.com/q/49345838
tags question: http://stackoverflow.com/q/49439807
tags question: http://stackoverflow.com/q/49395251
tags question: http://stackoverflow.com/q/49429403
tags question: http://stackoverflow.com/q/49439396
tags question: http://stackoverflow.com/q/49353974
tags question: http://stackoverflow.com/q/49289709
tags question: http://stackoverflow.com/q/49378987
tags question: http://stackoverflow.com/q/49303800
tags question: http://stackoverflow.com/q/49332935
tags question: http://stackoverflow.com/q/49341172
tags question: http://stackoverflow.com/q/49394329
tags question: http://stackoverflow.com/q/49384229
tags question: http://stackoverflow.com/q/49308714
tags question: http://stackoverflow.com/q/49439177
tags question: http://stackoverflow.com/q/49292221
tags question: http://stackoverflow.com/q/49378788
tags question: http://stackoverflow.com/q/49395395
tags question: http://stackoverflow.com/q/49435873
tags question: http://stackoverflow.com/q/49326346
tags question: http://stackoverflow.com/q/49342876
tags question: http://stackoverflow.com/q/49386564
tags question: http://stackoverflow.com/q/49308464
tags question: http://stackoverflow.com/q/49303798
tags question: http://stackoverflow.com/q/49298245
tags question: http://stackoverflow.com/q/49419858
tags question: http://stackoverflow.com/q/49308006
tags question: http://stackoverflow.com/q/49322891
tags question: http://stackoverflow.com/q/49367841
tags question: http://stackoverflow.com/q/49422023
tags question: http://stackoverflow.com/q/49381355
tags question: http://stackoverflow.com/q/49387871
tags question: http://stackoverflow.com/q/49331108
tags question: http://stackoverflow.com/q/49419621
tags question: http://stackoverflow.com/q/49389789
tags question: http://stackoverflow.com/q/49309668
tags question: http://stackoverflow.com/q/49290655
tags question: http://stackoverflow.com/q/49380885
tags question: http://stackoverflow.com/q/49354201
tags question: http://stackoverflow.com/q/49332306
tags question: http://stackoverflow.com/q/49347627
type: Tag
tags question: http://stackoverflow.com/q/49405337
tags question: http://stackoverflow.com/q/49409766
tags question: http://stackoverflow.com/q/49379075
tags question: http://stackoverflow.com/q/49305858
tags question: http://stackoverflow.com/q/49397802
tags question: http://stackoverflow.com/q/49398568
tags question: http://stackoverflow.com/q/49403203
tags question: http://stackoverflow.com/q/49401785
tags question: http://stackoverflow.com/q/49347498
tags question: http://stackoverflow.com/q/49362476
tags question: http://stackoverflow.com/q/49367450
tags question: http://stackoverflow.com/q/49364186

http://stackoverflow.com/a/49383134
has body: Cloud trail events which you see in console can be queried using cloud trail boto3 api Ref : http://boto3.readthedocs.io/en/latest/reference/services/cloudtrail.html#CloudTrail.Client.lookup_events However, it is advisable to enable logs and store in S3 while configuring cloud trail so that you can look for historical cloud trail logs. Cloud trail logs will be available in S3 which can accessed/downloaded using S3 apis Hope this helps !!!
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49377223

http://stackoverflow.com/comment/85648173
score: 0
comment on: http://stackoverflow.com/q/49322847
has text: " didn't found anything yet with that kind of XML file" => the point of formats like XML is that they are generic. IOW you can use just any available Python XML parser to do the job.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85839528
type: Comment
type: QuestionComment
has text: Image data is not utf-8 encoded text. Do not decode it as if it were.
comment on: http://stackoverflow.com/q/49418929
score: 0

http://stackoverflow.com/comment/85870434
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49432799
has text: You've shown us that copy & pasting them into a website says they're the same, but there may be subtle differences that the copy & paste process eliminates, or that that website ignores. If you're saying that diff says they're different then it should show you why it thinks they're different.

http://stackoverflow.com/q/49316812
has answer: http://stackoverflow.com/a/49322390
upvote count: 1
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/49355891
has title: Replace the missing months & year in date column using python
type: Question
accepted answer: http://stackoverflow.com/a/49317156
answer count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49317156
tagged with: date
tagged with: replace
possible better answer: http://stackoverflow.com/a/49322390
tagged with: pandas
type: AnsweredQuestion
has body: I have a dataframe with date column, some of the data are missing based on year and month. i have to display are the months for all the years in my dataset and the corresponding columns should display with zeros. My dataframe looks like this Date Churn Churnrate customerID 2008,01 726.0 0.542398 2763 2008,02 345.0 0.257751 1351 2012,11 NaN NaN 6 2013,01 3.0 0.002241 24 2013,02 10.0 0.007471 34 2013,03 25.0 0.018678 73 2013,04 25.0 0.018678 75 2013,05 14.0 0.010459 61 2013,06 19.0 0.014195 69 2013,07 27.0 0.020172 103 2013,08 22.0 0.016436 79 2013,09 19.0 0.014195 70 2013,10 28.0 0.020919 83 2013,11 22.0 0.016436 78 2013,12 19.0 0.014195 75 2014,01 17.0 0.012701 63 2014,02 21.0 0.015689 55 2014,03 7.0 0.005230 66 2014,04 24.0 0.017931 86 2014,05 18.0 0.013448 90 2014,06 14.0 0.010459 50 For example in the year 2018, i have only two month records, but i want to display all the 12 months with 0s in the corresponding columns My another dataframe looks like this Months Retention_Rate Customer_Count 0 2008/01 0.145916 133 1 2008/02 0.924663 762 2 2008/03 0.074544 67 3 2014/07 0.058684 45 4 2014/08 0.069786 61 5 2014/09 0.076130 64 6 2014/10 0.061856 60 7 2014/11 0.082474 69 I have used the same answer which is given below predicted_retention_rate = predicted_retention_rate.set_index('Months') idx =(pd.MultiIndex.from_product(predicted_retention_rate.index.str.split('/', expand=True).levels) .map('/'.join)) final_retention_rate_predicted = predicted_retention_rate.reindex(idx, fill_value=0).rename_axis('Months').reset_index() print (final_retention_rate_predicted) But some of the months are missing in this output Months Retention_Rate Customer_Count 0 2008/01 0.145916 133 1 2008/02 0.924663 762 2 2008/03 0.074544 67 3 2008/07 0.000000 0 4 2008/08 0.000000 0 5 2008/09 0.000000 0 6 2008/10 0.000000 0 7 2008/11 0.000000 0 8 2014/01 0.000000 0 9 2014/02 0.000000 0 10 2014/03 0.000000 0 11 2014/07 0.058684 45 12 2014/08 0.069786 61 13 2014/09 0.076130 64 14 2014/10 0.061856 60 …

http://stackoverflow.com/a/49420199
has body: Given from collections import OrderedDict, defaultdict lst = [ OrderedDict([ ("id", "1"), ("date", "20170101"), ("quantity", "10")]), OrderedDict([ ("id", "2"), ("date", "20170102"), ("quantity", "3")]), OrderedDict([ ("id", "3"), ("date", "20170102"), ("quantity", "1")]) ] Borrowing from more_itertools.map_reduce recipe: def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None): valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc ret = defaultdict(list) for item in iterable: key = keyfunc(item) value = valuefunc(item) ret[key].append(value) if reducefunc is not None: for key, value_list in ret.items(): ret[key] = reducefunc(value_list) ret.default_factory = None return ret Code map_reduce builds a defaultdict with customizable keys and values. The reducing function is applied to the final list of values. kfunc = lambda d: d["date"] vfunc = lambda d: int(d["quantity"]) rfunc = lambda lst_: sum(lst_) agg = map_reduce(lst, keyfunc=kfunc, valuefunc=vfunc, reducefunc=rfunc) agg # defaultdict(None, {'20170101': 10, '20170102': 4}) We use a list comprehension for the final result. [{"date": k, "sum_quantity": v} for k, v in agg.items()] # [{'date': '20170101', 'sum_quantity': 10}, {'date': '20170102', 'sum_quantity': 4}]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49325712

http://stackoverflow.com/comment/85710867
type: QuestionComment
comment on: http://stackoverflow.com/q/49355224
has text: @abarnert Like I said... learning every day... especially from your answers and comments (-;
score: 2
type: Comment

http://stackoverflow.com/a/49373623
accepted answer of: http://stackoverflow.com/q/49373333
type: Answer
answers question: http://stackoverflow.com/q/49373333
type: AcceptedAnswer
downvote count: 0
has body: First of all, you could create the array using a for loop nested inside such as grid = [(["*",]*6)for i in range(6)] Then to append just do grid[0][0] = 1 Maybe another idea for printing it out is rowFormat=("{:&lt;5}")*6 for i in range(len(grid)): print(rowFormat.format(*grid[i])) something like that. Hope that helps
score: 1
upvote count: 1

http://stackoverflow.com/comment/85740757
has text: Ah ok thanks, this makes sense. Would the operations otherwise be equivalent given the same initialization?
type: Comment
comment on: http://stackoverflow.com/a/49368851
type: AnswerComment
score: 0

http://stackoverflow.com/a/49355252
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49355114
type: Answer
has body: word_tokenize is expecting a string but file.readlines() gives you a list. Just convert the list to a string will solve the issue. import nltk from nltk import word_tokenize import re file = open('test.txt', 'r').readlines() text ='' for line in file: text+=line text = word_tokenize(text) string = str(text) # remove it if want to tag by words and pass text directly to post_tag:) nltk.pos_tag(string)
has comment: http://stackoverflow.com/comment/85710910
downvote count: 0

http://stackoverflow.com/comment/85596827
type: QuestionComment
has text: https://stackoverflow.com/questions/45110251/number-of-mysql-query-parameters-match-arguments-passed-to-execute-but-python-r and once that's fixed you'll run in to this https://stackoverflow.com/questions/23600286/python-mysql-connector-database-query-with-s-fails, because instead of a sequence of arguments, i.e. `(data, )`, you're passing an argument as the 2nd arg to `execute()`.
comment on: http://stackoverflow.com/q/49296489
score: 1
type: Comment

http://stackoverflow.com/comment/85797057
score: 0
comment on: http://stackoverflow.com/q/49397677
type: Comment
type: QuestionComment
has text: We're going to need to see some code, your expectations, your actual results, and your thoughts and failed attempts on addressing the situation.

http://stackoverflow.com/comment/85583891
score: 1
has text: You could also do `cur_char, next_char in zip(test, test[1:])` without any `itertools`. Edit: looks like the other answer beat me to it
comment on: http://stackoverflow.com/a/49290368
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49349250
has body: Any number that is a multiple of both 3 and 5 will make the first if condition true and will never be checked against the second if condition. You should flip the conditions: for i in range(0, 101): if i % 5 == 0 and i % 3 == 0 and i != 0: print('{} FiveThree'.format(i)) elif i % 3 == 0 and i != 0: print('{} Three'.format(i)) else: print("{}".format(i)) But this is wasteful. It checks i % 3 == 0 and i != 0 twice. I'm leaving the optimization as an exercise.
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49349200
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49349200

http://stackoverflow.com/a/49290436
has body: the i in that loop is a string,therefor you can't use it as an index change this part of the code to this: for i in range(0,len(test)): while(i+1&lt;len(test)): if test[i] in bad and test[i+1] in bad: print("it works")
downvote count: 1
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49290338

http://stackoverflow.com/q/49391089
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/85783675
type: AnsweredQuestion
score: 3
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/49391207
tagged with: pandas
upvote count: 3
has title: Pandas Groupby sort by Index
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I have negative values in my index column of my groupby. I need to sort these as numbers, not as text. Here is my group by and my attempt at sorting, which has been unsuccessful: df_counts = df.groupby('DAYSLATE')'DAYSLATE'.count() df_counts = df_counts.sort_index().astype(int) Here is my current output: DAYSLATE DAYSLATE_PCT CUMULATIVE CUM_PCT DAYSLATE -1 59 7.73% 59 7.73% -129 1 0.13% 60 7.86% -2 7 0.92% 67 8.78% -230 1 0.13% 68 8.91% -3 1 0.13% 69 9.04% 0 486 63.7% 555 72.74% 1 98 12.84% 653 85.58% 10 3 0.39% 656 85.98% 11 3 0.39% 659 86.37% 14 2 0.26% 661 86.63% 2 33 4.33% 694 90.96% 260 1 0.13% 695 91.09% 3 18 2.36% 713 93.45% 4 25 3.28% 738 96.72% 5 10 1.31% 748 98.03% 6 3 0.39% 751 98.43% 7 2 0.26% 753 98.69% 70 1 0.13% 754 98.82% 8 4 0.52% 758 99.34% 9 5 0.66% 763 100.0%
has comment: http://stackoverflow.com/comment/85783658
has answer: http://stackoverflow.com/a/49391207

http://stackoverflow.com/a/49417758
has comment: http://stackoverflow.com/comment/85853995
score: 0
has body: I think the best way to go about it is to overlay the triangles over the lines: import matplotlib.pyplot as plt import numpy as np values = np.random.normal(loc=0, scale=1, size=10) plt.plot( range(10), values, marker='^', markerfacecolor='red', markersize=15, color='red', linewidth=2) plt.show() The program outputs: If you really want the see through aspect, I suggest you somehow calculate where the lines overlap with the markers and only draw the lines inbetween: import numpy as np import matplotlib.pyplot as plt values = np.random.normal(loc= 0, scale=1, size=10) for i in range(9): start_coordinate, end_coordinate = some_function(values[i], values[i+1]) plt.plot([i, i+1], [start_coordinate, end_coordinate], *whatever_other_arguments) plt.scatter(range(10), values, *whatever_other_arguments) plt.show() The hard part here is of course calculating these coordinates (if you want to zoom in this won't work), but honestly, given the difficulty of this question, I think you won't find anything much better...
type: Answer
answers question: http://stackoverflow.com/q/49416776

http://stackoverflow.com/comment/85715445
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49349867
type: AnswerComment
has text: Thanks, I expected the program to loop through each row and give me 1 value when condition was satisfied. i.e. 100.0, 110.0, 120.0 in 3 loops. I expected the output to be, after first loop: `ce_strike_sell = 100.0`, 2nd loop: `ce_strike_sell = 110.0` and third loop: `ce_strike_sell = 120.0`. I am not sure if there is a way to do this as I am still very new to pandas.

http://stackoverflow.com/comment/85836240
comment on: http://stackoverflow.com/q/49417191
type: Comment
type: QuestionComment
score: 2
has text: Python has a built-in function to do what you want: https://docs.python.org/2/library/functions.html#max

http://stackoverflow.com/a/49945440
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/49377483
has body: Your formula is correct, but it works only for binary classification. The demo code in tensorflow classifies 3 classes. It's like comparing apples to oranges. One of the answers you refer to mentions it too: This formulation is often used for a network with one output predicting two classes (usually positive class membership for 1 and negative for 0 output). In that case i may only have one value - you can lose the sum over i. The difference between these two formulas (binary cross-entropy vs multinomial cross-entropy) and when each one is applicable is well-described in this question. The answer to your second question is yes, there is such a function called tf.nn.sigmoid_cross_entropy_with_logits. See the above mentioned question.
downvote count: 0
score: 6

arrays
tags question: http://stackoverflow.com/q/49317173
tag name: arrays
tags question: http://stackoverflow.com/q/49304338
tags question: http://stackoverflow.com/q/49337984
tags question: http://stackoverflow.com/q/49380182
tags question: http://stackoverflow.com/q/49384682
tags question: http://stackoverflow.com/q/49372813
tags question: http://stackoverflow.com/q/49340169
type: Tag
tags question: http://stackoverflow.com/q/49333795
tags question: http://stackoverflow.com/q/49279948
tags question: http://stackoverflow.com/q/49413602
tags question: http://stackoverflow.com/q/49363247
tags question: http://stackoverflow.com/q/49364721
tags question: http://stackoverflow.com/q/49434319
tags question: http://stackoverflow.com/q/49359791
tags question: http://stackoverflow.com/q/49290059
tags question: http://stackoverflow.com/q/49393125
tags question: http://stackoverflow.com/q/49395510
tags question: http://stackoverflow.com/q/49322017
tags question: http://stackoverflow.com/q/49282683
tags question: http://stackoverflow.com/q/49346050
tags question: http://stackoverflow.com/q/49412136
tags question: http://stackoverflow.com/q/49426584
tags question: http://stackoverflow.com/q/49375219
tags question: http://stackoverflow.com/q/49303765
tags question: http://stackoverflow.com/q/49397704
tags question: http://stackoverflow.com/q/49430215
tags question: http://stackoverflow.com/q/49377085
tags question: http://stackoverflow.com/q/49415834
tags question: http://stackoverflow.com/q/49410317
tags question: http://stackoverflow.com/q/49374698
tags question: http://stackoverflow.com/q/49301983
tags question: http://stackoverflow.com/q/49437156
tags question: http://stackoverflow.com/q/49370789
tags question: http://stackoverflow.com/q/49386958
tags question: http://stackoverflow.com/q/49391167
tags question: http://stackoverflow.com/q/49352994
tags question: http://stackoverflow.com/q/49386827
tags question: http://stackoverflow.com/q/49364969
tags question: http://stackoverflow.com/q/49417191
tags question: http://stackoverflow.com/q/49304496
tags question: http://stackoverflow.com/q/49353234
tags question: http://stackoverflow.com/q/49396243
tags question: http://stackoverflow.com/q/49345012
tags question: http://stackoverflow.com/q/49415432
tags question: http://stackoverflow.com/q/49427866
tags question: http://stackoverflow.com/q/49437807
tags question: http://stackoverflow.com/q/49301317
tags question: http://stackoverflow.com/q/49402817
tags question: http://stackoverflow.com/q/49352496
tags question: http://stackoverflow.com/q/49348763
tags question: http://stackoverflow.com/q/49306743
tags question: http://stackoverflow.com/q/49396526
tags question: http://stackoverflow.com/q/49418478
tags question: http://stackoverflow.com/q/49396311
tags question: http://stackoverflow.com/q/49291565
tags question: http://stackoverflow.com/q/49330080
tags question: http://stackoverflow.com/q/49371327
tags question: http://stackoverflow.com/q/49291681
tags question: http://stackoverflow.com/q/49417176
tags question: http://stackoverflow.com/q/49430785
tags question: http://stackoverflow.com/q/49293393
tags question: http://stackoverflow.com/q/49426254
tags question: http://stackoverflow.com/q/49359567
tags question: http://stackoverflow.com/q/49374253
tags question: http://stackoverflow.com/q/49360793
tags question: http://stackoverflow.com/q/49316345
tags question: http://stackoverflow.com/q/49342200
tags question: http://stackoverflow.com/q/49391245
tags question: http://stackoverflow.com/q/49365715
tags question: http://stackoverflow.com/q/49319204
tags question: http://stackoverflow.com/q/49288559
tags question: http://stackoverflow.com/q/49351897
tags question: http://stackoverflow.com/q/49403845
tags question: http://stackoverflow.com/q/49388555
tags question: http://stackoverflow.com/q/49348544
tags question: http://stackoverflow.com/q/49435915
tags question: http://stackoverflow.com/q/49326081
tags question: http://stackoverflow.com/q/49327692

http://stackoverflow.com/comment/85736807
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49367970
type: Comment
has text: I can't give you the details about why your module is being imported instead of the builtin one without more context

http://stackoverflow.com/a/49308066
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49307047
type: Answer
has comment: http://stackoverflow.com/comment/85646412
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49307047
has body: Although scikit-learn's AdaBoostClassifier allows for a base estimator of your choosing (see documentation), it requires the estimator to support sample_weight. Take a look at the source: if not has_fit_parameter(self.base_estimator_, "sample_weight"): raise ValueError("%s doesn't support sample_weight." % self.base_estimator_.__class__.__name__) Unfortunately, neither LinearDiscriminantAnalysis nor QuadraticDiscriminantAnalysis fall into this category. Here's a toy example: from sklearn.ensemble import AdaBoostClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split iris = load_iris() X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target) clf = AdaBoostClassifier(base_estimator=LDA()) clf.fit(X_train, y_train) You'll see a traceback like the following: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "//anaconda/lib/python2.7/site-packages/sklearn/ensemble/weight_boosting.py", line 411, in fit return super(AdaBoostClassifier, self).fit(X, y, sample_weight) File "//anaconda/lib/python2.7/site-packages/sklearn/ensemble/weight_boosting.py", line 128, in fit self._validate_estimator() File "//anaconda/lib/python2.7/site-packages/sklearn/ensemble/weight_boosting.py", line 429, in _validate_estimator % self.base_estimator_.__class__.__name__) ValueError: LinearDiscriminantAnalysis doesn't support sample_weight. This is a requirement you're not going to get around in scikit-learn. The documentation makes it clear that it's a hard requirement: "...Support for sample weighting is required, as well as proper classes_ and n_classes_ attributes." However, if your desire is simply to use an ensemble, you could always use bagging rather than boosting: from sklearn.ensemble import BaggingClassifier clf = BaggingClassifier(b…

http://stackoverflow.com/q/49342399
has title: HTTP Error 403: Forbidden using Python3 & How to change IP when Crawling
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85685368
has comment: http://stackoverflow.com/comment/85685603
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85685261
has comment: http://stackoverflow.com/comment/85685027
has comment: http://stackoverflow.com/comment/85687051
has comment: http://stackoverflow.com/comment/85688036
answer count: 0
has comment: http://stackoverflow.com/comment/85685683
upvote count: 2
type: UnansweredQuestion
has body: Below is my code. I want to get historical data from Google Finance, and I tried some methods to fix it. But it still doesn't work. I think it may be because Google Finance has blocked my IP. If so, is there any solution? url='http://finance.google.com/finance/historical?q=AMZN' headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','User-Agent':'Mozilla/5.0'} context = ssl._create_unverified_context() htmlll=urllib.request.Request(url,headers=headers) html = urllib.request.urlopen(htmlll,context=context).read().decode() datalist=html.splitlines() name = datalist[2].split('&gt;')[2].split(':')[0].replace('amp;','') print(name) And the error is as below Traceback (most recent call last): File "C:/Users/admin/Desktop/Price &amp; Volume Database/Global Intraday Pricing Data/Asia Intraday Pricing/test.py", line 30, in &lt;module&gt; html = urllib.request.urlopen(htmlll,context=context).read().decode() File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 162, in urlopen return opener.open(url, data, timeout) File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 471, in open response = meth(req, response) File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 581, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\admin\AppData\Local\Programs\Python\Python35- 32\lib\urllib\request.py", line 509, in error return self._call_chain(*args) File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 443, in _call_chain result = func(*args) File "C:\Users\admin\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 589, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden I have added header and the web address works. I cannot find what's wrong with it.Thank you so much for your help!
has comment: http://stackoverflow.com/comment/85686963
downvote count: 1
linked to: http://stackoverflow.com/q/22657548
tagged with: http-status-code-403
has comment: http://stackoverflow.com/comment/85685079

http://stackoverflow.com/comment/85711837
comment on: http://stackoverflow.com/q/49355681
type: Comment
type: QuestionComment
score: 0
has text: you can calculate the correlation of the first 30 columns with `data.iloc[:,0:30].corr()` and adding `.abs()` at the end will then take care of your ambivalence toward the sign.

http://stackoverflow.com/q/49303397
tagged with: python
tagged with: httpresponse
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/zip
has answer: http://stackoverflow.com/a/49319802
answer count: 1
downvote count: 0
tagged with: django
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: My goal is to parse a series of strings into a series of text files that are compressed as a Zip file and downloaded by a web app using Django's HTTP Response. Developing locally in PyCharm, my method outputs a Zip file called "123.zip" which contains 6 individual files named "123_1", "123_2 etc". containing the letters from my phrase with no problem. The issue is when I push the code to my web app and include the Django HTTP Response the file will download but when I go to extract it it produces "123.zip.cpzg". Extracting that in turn gives me 123.zip(1) in a frustrating infinite loop. Any suggestions where I'm going wrong? Code that works locally to produce "123.zip": def create_text_files1(): JobNumber = "123" z = zipfile.ZipFile(JobNumber +".zip", mode ="w") phrase = "A, B, C, D, EF, G" words = phrase.split(",") x =0 for word in words: word.encode(encoding="UTF-8") x = x + 1 z.writestr(JobNumber +"_" + str(x) + ".txt", word) z.close() Additional part of the method in my web app: response = HTTPResponse(z, content_type ='application/zip') response['Content-Disposition'] = "attachment; filename='" + str(jobNumber) + "_AHTextFiles.zip'"
accepted answer: http://stackoverflow.com/a/49319802
has title: Downloading Zip file through Django, file decompresses as cpzg
linked to: http://stackoverflow.com/q/67454

http://stackoverflow.com/comment/85785182
has text: Initialize the object in the test, not the setup. Then use the initialization values to test the `get_x` methods. e.g. `cc = CreditCard(1,2,3); self.assertEqual(cc.get_balance(), 1)` That way you are not relying on the non-public attribute name (`_balance`) for example..
type: Comment
comment on: http://stackoverflow.com/q/49391777
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85763794
score: 0
type: Comment
has text: It seems your projection is 90 degrees off from the other result. But I don't know why.
type: QuestionComment
comment on: http://stackoverflow.com/q/49364812

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/49380998
tag name: countvectorizer

http://stackoverflow.com/comment/85834404
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49415106
score: 0
has text: I don't think it is going to like that slash in the parameter. Try passing the parameter without the slash and either moving the file, or doing the directory navigation programmatically.

http://stackoverflow.com/comment/85857859
comment on: http://stackoverflow.com/q/49428252
score: 0
has text: @jcfollower link is exact. We can mark this as Duplicate
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85874428
type: QuestionComment
score: 0
has text: Never mind that last part, I misunderstood something. The error says it's at offset 966, not 6290. Can you show the code around that section?
comment on: http://stackoverflow.com/q/49435781
type: Comment

http://stackoverflow.com/q/49374064
score: 0
has comment: http://stackoverflow.com/comment/85749731
answer count: 0
has comment: http://stackoverflow.com/comment/85753519
has comment: http://stackoverflow.com/comment/85749391
type: Question
has body: My python skills are not sophisticated but how do I use numpy where to get the elements rather than the indices here? So in the example below (with mock data), I want the same results from where that the loop gives? import numpy as np #make some mock data test=np.ones((10,10)) for i in range(0,10): for j in range(0,10): test[i,j]=i*2.0+j for i in range(0,10): if 8.0&lt;=test[i,5]&lt;=18.0: print test[i,5] print np.where((test[:,5] &gt;= 8.0) &amp; (test[:,5] &lt;=18.0))
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85749474
tagged with: numpy
has title: python np.where equivalent

http://stackoverflow.com/comment/85830264
score: 0
type: Comment
has text: There is currently a bug in gRPC: https://github.com/grpc/grpc/issues/14523
type: QuestionComment
comment on: http://stackoverflow.com/q/49327193

http://stackoverflow.com/comment/85738344
type: Comment
type: QuestionComment
has text: The `__init__` does not return anything, so patching it will not allow you return your `MagicMock` from calling `Dispatcher`.
comment on: http://stackoverflow.com/q/49368705
score: 1

http://stackoverflow.com/comment/85833410
has text: @Aran-Fey now is clear enough I think.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49414428
score: 0

http://stackoverflow.com/a/49304658
has body: As commented, scaling and rounding your numbers might allow you to use intersect1d or the equivalent. And if you have just 2 columns, it might work to turn it into a 1d array of complex dtype. But you might also want to keep in mind what intersect1d does: if not assume_unique: # Might be faster than unique( intersect1d( ar1, ar2 ) )? ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate((ar1, ar2)) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] unique has been enhanced to handle rows (axis parameters), but intersect has not. In any case it uses argsort to put similar elements next to each other, and then skips the duplicates. Notice that intersect concatenenates the unique arrays, sorts, and again finds the duplicates. I know you didn't want a loop version, but to promote conceptualization of the problem here's one anyways: In [581]: a = np.array([(1.22, 5.64), ...: (2.31, 7.63), ...: (4.94, 4.15)]) ...: ...: b = np.array([(1.23, 5.63), ...: (6.31, 10.63), ...: (2.32, 7.65)]) ...: I removed a layer of nesting in your arrays. In [582]: c = [] In [583]: for a1 in a: ...: for b1 in b: ...: if np.allclose(a1,b1, atol=0.5): c.append((a1,b1)) or as list comprehension In [586]: [(a1,b1) for a1 in a for b1 in b if np.allclose(a1,b1,atol=0.5)] Out[586]: [(array([1.22, 5.64]), array([1.23, 5.63])), (array([2.31, 7.63]), array([2.32, 7.65]))] complex approximation In [604]: aa = (a*10).astype(int) In [605]: aa Out[605]: array([[12, 56], [23, 76], [49, 41]]) In [606]: ac=aa[:,0]+1j*aa[:,1] In [607]: bb = (b*10).astype(int) In [608]: bc=bb[:,0]+1j*bb[:,1] In [609]: np.intersect1d(ac,bc) Out[609]: array([12.+56.j, 23.+76.j]) intersect inspired Concatenate the arrays, sort them, take difference, and find the small differences: In [616]: ab = np.concatenate((a,b),axis=0) In [618]: np.lexsort(ab.T) Out[618]: array([2, 3, 0, 1, 5, 4], dtype=int32) In [619]: ab1 = ab[_,:] In [620]: ab1 Out[620]: array([[ 4.94, 4.15], [ 1.23, 5.63], [ 1.22, 5.64], [ 2.31, 7.63], [ 2.32, 7.65], [ 6.…
answers question: http://stackoverflow.com/q/49303679
score: 0
type: Answer

http://stackoverflow.com/comment/85620380
score: 0
type: Comment
type: AnswerComment
has text: changed now, this algorithm should work (though it is much less performant)
comment on: http://stackoverflow.com/a/49308849

http://stackoverflow.com/comment/85892543
score: 0
has text: Have you checked if the path of the chrome's binaries location is correct? If you list the paths contents, the actual chrome binaries are there?
comment on: http://stackoverflow.com/q/49436492
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85703949
type: QuestionComment
comment on: http://stackoverflow.com/q/49351882
type: Comment
score: 0
has text: Yes, my mistake. I went ahead and corrected the original post.

http://stackoverflow.com/q/49370642
favorite count: 0
type: Question
has body: I am trying to use my laptop's gpu to perform linear regression on a mock data set (Code part #1) using tensorflow (Code part #2). My problem is that, depending on how y_pred is defined in the cost function block, I get an InternalError when running that block on the gpu. Running it on the cpu however is fine. The traceback is shown at the end of this question (Traceback). So the question is: What is the reason for this InternalError? How can I fix this so I can use tf.matmul? Specs: The laptop is running Windows 10 64bit and has a GeForce 940MX card and Intel HD graphics 630. On the software side the laptop is running cuda 9.0 and the corresponding cudnn. Code part #1: import matplotlib.pylab as plt import tensorflow as tf import numpy as np # generate some linear train and test data X_train = np.linspace(0,1,100).reshape((-1,1)) t_train = X_train.dot([1]) t_train = t_train.reshape((-1,1)) X_test = np.linspace(0,1,150).reshape((-1,1)) t_test = X_test.dot([1]) t_tets = t_test.reshape((-1,1)) N, D = X_train.shape fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X_train, t_train, '.', label="train") ax.plot(X_test, t_test, '.', label="test") plt.legend() plt.show() Code part #2: tf.reset_default_graph() cpu = "/cpu:0" gpu = "/gpu:0" # placeholders and weights variable with tf.device(cpu): X = tf.placeholder(tf.float32, shape=(None,D), name="X") y = tf.placeholder(tf.float32, shape=(None,1), name="y") w = tf.Variable(tf.ones([D,1])*10, name="w") learning_rate = .1 # cost function with tf.device(gpu): y_pred = tf.matmul(X,w) # does not work #y_pred = X*w # works error = y_pred - y cost = tf.reduce_mean(tf.square(error)) # update rule with tf.device(cpu): gradient = tf.gradients(cost, [w])[0] update = tf.assign(w, w - learning_rate * gradient) init = tf.global_variables_initializer() n_epochs = 500 n_print = 50 with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): sess.run(update, feed_dict={X:X_train, y:t_train}) if epoch % n_print == 0: print("epo…
has title: tf.matmul in gpu-enabled tensorflow and 'InternalError: Blas GEMV launch failed'
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
upvote count: 1
score: 1
tagged with: python

http://stackoverflow.com/comment/85834125
type: QuestionComment
has text: No, you'd call it on `deck` before you deal.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49416016

http://stackoverflow.com/comment/85632005
has text: @SherwinChen you cannot use a completely unknown shape. The dimensionality of the placeholder must be known, see https://stackoverflow.com/questions/48978984/tensorflow-boolean-mask-with-dynamic-mask
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49312184
type: AnswerComment

http://stackoverflow.com/a/49310865
type: Answer
answers question: http://stackoverflow.com/q/49310466
has body: Even if you wish to save the figure, matplotlib is a good way to do it. matplotlib.pyplot.savefig(‘my_cv2hist.png’) would work for you, if it is to save the histogram as an image that you are looking for. imread will just work fine if you are trying to read it back as the way you are trying to do it in your example code.
has comment: http://stackoverflow.com/comment/85646011
score: 0

http://stackoverflow.com/q/49402212
has body: I am trying to make migrations for my models: from django.db import models TAKEN = ( (True, 'Yes'), (False, 'No') ) class Room(models.Model): name = models.CharField(max_length=32) number = models.IntegerField() taken = models.BooleanField(choices=TAKEN) description = models.CharField(max_length=128) ROOMS_CHOICE = (Room.objects.filter(taken=False)) class Reservation(models.Model): date = models.DateField() hours = models.IntegerField() choice = models.OneToOneField(Room, on_delete=models.CASCADE, choices=ROOMS_CHOICE) forms for the models: from django import forms from .models import TAKEN, ROOMS_CHOICE class NewRoomForm(forms.Form): name = forms.CharField(label='Name', max_length=32) number = forms.IntegerField(label='Room Number') taken = forms.ChoiceField(choices=TAKEN, label='Taken', widget=forms.Select) description = forms.CharField(label='Description', widget=forms.Textarea) class ReservationForm(forms.Form): date = forms.DateField(label='Date', widget=forms.SelectDateWidget) hours = forms.IntegerField(label='hours', max_value=8) choice = forms.ChoiceField(choices=ROOMS_CHOICE, label='room', widget=forms.Select) When I try to make migrations, an ProgrammingError appears: django.db.utils.ProgrammingError: (1146, "Table 'conference_room.conference_room' doesn't exist") I try to make a view where user can book a conference room from a available rooms (those that are not occupied - taken=False). I assume I made some mistakes during building OneToOne relation and writing choices based on the Room model, and that is why the error appeared. How can I rewrite my models and forms?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49402266
has comment: http://stackoverflow.com/comment/85805634
tagged with: python
has comment: http://stackoverflow.com/comment/85805719
has title: Django. How to make model choices from another model
score: 0
answer count: 1
tagged with: django
tagged with: web

http://stackoverflow.com/a/49313456
answers question: http://stackoverflow.com/q/49294369
type: Answer
score: 0
has body: Sorting on the rename resolved this: df_Done_Ccy_Grp = df_Done_Ccy_Grp.rename(columns={'state':'Done Trades'}, level=0) display(df_Done_Ccy_Grp.sort_values('Done Trades',ascending=False)) – Peter Lucas

http://stackoverflow.com/q/49346906
has comment: http://stackoverflow.com/comment/85704766
favorite count: 0
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85695862
tagged with: python
has title: Computing percentiles when given a distribution
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/85693799
has comment: http://stackoverflow.com/comment/85702871
accepted answer: http://stackoverflow.com/a/49348139
upvote count: 2
possible better answer: http://stackoverflow.com/a/49347495
has body: Let's say I have a vector of values, and a vector of probabilities. I want to compute the percentile over the values, but using the given vector of probabilities. Say, for example, import numpy as np vector = np.array([4, 2, 3, 1]) probs = np.array([0.7, 0.1, 0.1, 0.1]) Ignoring probs, np.percentile(vector, 10) gives me 1.3. However, it's clear that the lowest 10% here have value of 1, so that would be my desired output. If the result lies between two data points, I'd prefer linear interpolation as documented for the original percentile function. How would I solve this in Python most conveniently? As in my example, vector will not be sorted. probs always sums to 1. I'd prefer solutions that don't require "non-standard" packages, by any reasonable definition.
has answer: http://stackoverflow.com/a/49348139
has answer: http://stackoverflow.com/a/49347495
downvote count: 1

http://stackoverflow.com/q/49360888
has comment: http://stackoverflow.com/comment/109406538
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/79216656
has answer: http://stackoverflow.com/a/57371635
has comment: http://stackoverflow.com/comment/109419373
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/49362032
favorite count: 0
upvote count: 40
has body: I've recently started to use Google Colab, and wanted to train my first Convolutional NN. I imported the images from my Google Drive thanks to the answer I got here. Then I pasted my code to create the CNN into Colab and started the process. Here is the complete code: Part 1: Setting up Colab to import picture from my Drive (part 1 is copied from here as it worked as exptected for me Step 1: !apt-get install -y -qq software-properties-common python-software-properties module-init-tools !add-apt-repository -y ppa:alessandro-strada/ppa 2&gt;&amp;1 &gt; /dev/null !apt-get update -qq 2&gt;&amp;1 &gt; /dev/null !apt-get -y install -qq google-drive-ocamlfuse fuse Step 2: from google.colab import auth auth.authenticate_user() Step 3: from oauth2client.client import GoogleCredentials creds = GoogleCredentials.get_application_default() import getpass !google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} &lt; /dev/null 2&gt;&amp;1 | grep URL vcode = getpass.getpass() !echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} Step 4: !mkdir -p drive !google-drive-ocamlfuse drive Step 5: print('Files in Drive:') !ls drive/ Part 2: Copy pasting my CNN I created this CNN with tutorials from a Udemy Course. It uses keras with tensorflow as backend. For the sake of simplicity I uploaded a really simple version, which is plenty enough to show my problems from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.layers import Dropout from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator parameters imageSize=32 batchSize=64 epochAmount=50 CNN classifier=Sequential() classifier.add(Conv2D(32, (3, 3), input_shape = (imageSize, imageSize, 3), activation = 'relu')) #convolutional layer classifier.add(MaxPooling2D(pool_size = (2, 2))) #pooling layer classifier…
has answer: http://stackoverflow.com/a/62302511
accepted answer: http://stackoverflow.com/a/53119715
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70736859
has answer: http://stackoverflow.com/a/53119715
has answer: http://stackoverflow.com/a/65366945
has answer: http://stackoverflow.com/a/65939389
has answer: http://stackoverflow.com/a/56762084
has answer: http://stackoverflow.com/a/63154752
possible better answer: http://stackoverflow.com/a/49362032
has comment: http://stackoverflow.com/comment/101805744
linked to: http://stackoverflow.com/q/53338621
linked to: http://stackoverflow.com/q/49351071
tagged with: python
has comment: http://stackoverflow.com/comment/85723349
has title: Google Colab is very slow compared to my PC
score: 40
answer count: 11
tagged with: jupyter-notebook
type: Question
has answer: http://stackoverflow.com/a/59655945
linked to: http://stackoverflow.com/q/27710245

http://stackoverflow.com/comment/85705124
has text: I think this is great for both solving the original problem *and* coming up with your own solution
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49352359

http://stackoverflow.com/q/49386824
type: UnansweredQuestion
score: 1
tagged with: string
answer count: 1
has comment: http://stackoverflow.com/comment/85775112
tagged with: python-2.7
has body: Bear with me on this as I might not be explaining this too well. I have a simple regex: ^(The\s)?(cat\s)?(sat\s)?(on\s)?(the\s)?(mat\.)? To which the text The cat sat on the mat. passes successfully. Hurrah! However, what I'm after is a way to find out which groups the regex failed on. For example: The cat sat on the mat # fails on group 6 (no period) The cat sat on teh mat. # fails on group 5 (teh instead of the) The kat sat on the mat. # fails on group 2 (kat instead of cat) The latter example was otherwise fine except for that one group fail. My question is this: Is there a way in Python to determine if that string would have been otherwise successful on a group by group basis - without having to create iterations of the regex fir each group in part? regex101 now with added cats
has comment: http://stackoverflow.com/comment/85775210
has comment: http://stackoverflow.com/comment/85775125
has answer: http://stackoverflow.com/a/49387219
linked to: http://stackoverflow.com/q/5319922
tagged with: grouping
tagged with: python
tagged with: regex
has title: Reg ex partial fail
favorite count: 0
has comment: http://stackoverflow.com/comment/85775022
has comment: http://stackoverflow.com/comment/85775067
has comment: http://stackoverflow.com/comment/85774681
type: Question
has comment: http://stackoverflow.com/comment/85775054
downvote count: 0
has comment: http://stackoverflow.com/comment/85774807
upvote count: 1

http://stackoverflow.com/comment/85585730
has text: Does the table you truncate happen to be one of the airflow metadata tables? Otherwise there is a lot going on in this script so maybe it will be easier to fix if you reduce to a minimum DAG that reproduces the error?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49290546

http://stackoverflow.com/a/49436647
has body: By default, bonobo defines a filesystem "service" called fs that points to your local directory. This service is the default filesystem used by all readers and writers provided in bonobo core. I would avoid thinking of files locations as absolute, because it means that you make your software depend on a specific filesystem structure. Instead, think about "file containers" (which happens to be directories on your local filesystem, but that's an implementation detail), and think how files are organized within each "file container". Bonobo uses PyFilesystem2 to abstract those containers. The goal is to not hardcode anything about the system, and instead allow easily to configure your data pipeline at runtime. You can define more filesystem services to logically bind different paths to some business logic. In your case, let's say that /data is where "data" goes, you could define a filesystem service of your own that maps to this directory: import bonobo def get_services(): return { 'fs.data': bonobo.open_fs('/data'), } def get_graph(): return bonobo.Graph( bonobo.CsvReader('input.csv', fs='fs.data'), ... # etc ) ... if __name__ == '__main__': bonobo.run(get_graph(), services=get_services()) This will allow a nice separation of concerns, and will greatly enhance the portability of your transformation. Of course, you could also override the default filesystem: import bonobo def get_services(): return { 'fs': bonobo.open_fs('/data'), } And you can define more than one filesystem, someone may have: import bonobo def get_services(): return { 'fs.input': bonobo.open_fs('/input_data'), 'fs.output': bonobo.open_fs('/output_data'), } By having the service definitions separated from the actual graph implementation, you'll gain the ability to switch the filesystem depending on your surrounding env (dev laptop, production, compute cluster, ...). It allows for example to work with local files on the development boxes, and switch to AWS S3 storage on production. What would be even be…
answers question: http://stackoverflow.com/q/49428338
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/85664302
has text: It's a typo! Thanks for pointing that out.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49329997
type: Comment

http://stackoverflow.com/comment/85734514
comment on: http://stackoverflow.com/q/49366431
has text: Can you give more detail about d is just a filename not a path section of your comment. @brodeur
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/85885350
comment on: http://stackoverflow.com/q/49439807
type: QuestionComment
type: Comment
has text: Have you tried `browser.find_element_by_id('community-search')`
score: 0

http://stackoverflow.com/comment/85578080
type: Comment
has text: I do not understand what you're trying to achieve, but `if colour == "Red" or "red"` will always evaluate to True. If you want to check if colour is Red or red, use `if colour.lower() == "red"` or `if colour == "Red" or colour == "red"`
type: QuestionComment
comment on: http://stackoverflow.com/q/49287498
score: 3

hash
tags question: http://stackoverflow.com/q/49279597
type: Tag
tags question: http://stackoverflow.com/q/49346696
tags question: http://stackoverflow.com/q/49286393
tag name: hash

http://stackoverflow.com/q/49284583
has title: How to use unicode characters as variable in Python 3?
has body: I have been trying to figure out how to use non-ascii unicode characters as Python 3 variables but I'm not sure which ones work and which ones don't. Why does the σ work but ∆ does not? Is it possible to use ∆ as a character or is it impossible at the moment? # Version sys.version '3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]' σ = 10 print(σ ) # 10 ∆ = 20 # File "&lt;ipython-input-24-b5e030117292&gt;", line 1 # ∆ = 20 # ^ # SyntaxError: invalid character in identifier
type: Question
has answer: http://stackoverflow.com/a/49284653
upvote count: 2
answer count: 1
downvote count: 0
tagged with: python
tagged with: variables
tagged with: unicode
favorite count: 0
tagged with: object
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85572100
accepted answer: http://stackoverflow.com/a/49284653

http://stackoverflow.com/comment/85803220
has text: By the way, you're right about the time complexity, but "we have a nested for loop" isn't enough to prove that. For example, if the inner loop were `for i in range(2):`, it wouldn't be the same complexity, right? Or if the body of that loop were a recursive call to `complex`? It's only `O(N^2)` if both loop are of length `N`, and the work done in the inner loop is constant time; that's what you need to establish to answer a).
type: QuestionComment
comment on: http://stackoverflow.com/q/49400897
type: Comment
score: 0

http://stackoverflow.com/q/49393611
tagged with: linker
tagged with: macos
favorite count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/49394526
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49537770
has body: I load Python dynamically with dlopen and RTLD_LOCAL to avoid collisions with another library which by coincidence contains a few symbols with the same name. Executing my MVCE above on macOS with Xcode fails because it expects _PyBuffer_Type in the global namespace. Traceback (most recent call last): File "...lib/python2.7/ctypes/__init__.py", line 10, in &lt;module&gt; from _ctypes import Union, Structure, Array ImportError: dlopen(...lib/python2.7/lib-dynload/_ctypes.so, 2): Symbol not found: _PyBuffer_Type Referenced from: ...lib/python2.7/lib-dynload/_ctypes.so Expected in: flat namespace in ...lib/python2.7/lib-dynload/_ctypes.so Program ended with exit code: 255 But why? Does RTLD_LOCAL overwrite the two-level namespace? I used otool -hV to check that _ctypes.so was compiled with the Two-Level namespace option. From my understanding the symbol resolve needs the library name + the symbol name itself. Why does it expect _PyBuffer_Type in the flat namespace and/or why can't it find it? See TWOLEVEL by scrolling to the right &gt; otool -hV /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_ctypes.so Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC_64 X86_64 ALL 0x00 BUNDLE 14 1536 NOUNDEFS DYLDLINK TWOLEVEL Any idea whats going on here? MVCE Can be copied to a new Xcode project, simply compile and execute. #include &lt;/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h&gt; #include &lt;dlfcn.h&gt; int main(int argc, const char * argv[]) { auto* dl = dlopen("/System/Library/Frameworks/Python.framework/Versions/2.7/Python", RTLD_LOCAL | RTLD_NOW); if (dl == nullptr) return 0; // Load is just a macro to hide dlsym(..) #define Load(name) ((decltype(::name)*)dlsym(dl, # name)) Load(Py_SetPythonHome)("/System/Library/Frameworks/Python.framework/Versions/2.7"); Load(Py_Initialize)(); auto* readline = Load(PyImport_ImportModule)("ctypes"); if (readline == nullptr) { Load(Py…
tagged with: c++
has answer: http://stackoverflow.com/a/49537770
type: AnsweredQuestion
score: 2
tagged with: symbols
has title: Library expects symbol in flat namespace although compiled with two-level namespace
answer count: 1

http://stackoverflow.com/comment/85763104
comment on: http://stackoverflow.com/q/49379399
type: QuestionComment
score: 0
has text: I have tried some more python versions and found that the error does **not** occur in python versions 3.5.2 and 3.6.4. (However, it does occur in 2.7.12 and 2.7.14.)
type: Comment

http://stackoverflow.com/comment/85838235
score: 0
has text: { error: "bad_request", reason: "Invalid bookmark parameter supplied" }
comment on: http://stackoverflow.com/a/49409915
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49305060
has answer: http://stackoverflow.com/a/49305133
downvote count: 1
has answer: http://stackoverflow.com/a/49305177
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/613183
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49305177
has comment: http://stackoverflow.com/comment/85612337
has comment: http://stackoverflow.com/comment/85612435
tagged with: dictionary
linked to: http://stackoverflow.com/q/2844516
has body: I have dictionary in format "site_mame": (side_id, frequency): d=[{'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'www.laposte.net': (3, 119), 'www.google.com': (4, 5441), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] Is there a smart way to filter dictionary d by value so that I have only those positions, where frequency is less than 100? For example: d=[{'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] I don't want to use loops, just looking for smart and efficient solution...
has comment: http://stackoverflow.com/comment/85612344
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49305123
upvote count: 0
has comment: http://stackoverflow.com/comment/85612368
tagged with: filter
answer count: 3
has title: How to filter dictionary by value?
duplicate of: http://stackoverflow.com/q/2844516
has answer: http://stackoverflow.com/a/49305123

http://stackoverflow.com/comment/85575372
has text: Thanks for your prompt reply, but it still does not run in the background, it waits for one to complete before proceeding to other. Also, on your question "In your case, it sounds like you're running hundreds of processes, so you want to run some of them in parallel, but maybe not all of them at once?" ,running them parallely would be the solution but since then there would be a large number of processes ,all I am looking to implement is that as soon as it spinsup the subprocess it logs the interactive output to log file instead of waiting there ...
comment on: http://stackoverflow.com/a/49285473
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85662147
score: 0
type: Comment
type: QuestionComment
has text: To be clear, fnmatch ranges specify ranges of *characters*, not ranges of *numbers*. If you write `[14-65]`, that matches only one character, which may be any of the following: `1` - the digit 1; `4-6` - the digits 4 through 6, and `5`, the digit 5 (specified a second, duplicative time).
comment on: http://stackoverflow.com/q/49329784

http://stackoverflow.com/comment/85691285
has text: I am getting true except "s","i", and "e".
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49345744
type: QuestionComment

http://stackoverflow.com/comment/85718099
type: Comment
comment on: http://stackoverflow.com/a/49359019
score: 0
has text: `set()` is only invoked *once* in the `fromkeys()` call. The DC calls it *each time*.
type: AnswerComment

http://stackoverflow.com/a/49301234
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49300516
has body: You might find it enough to just remove all 2 or 3 character uppercase entries at the end as follows: import pandas as pd data = [ ['Name', 'Overall', 'Club'], ['L. Messi CF ST RW', 94, 'FC Barcelona'], ['Cristiano Ronaldo LW LM ST RM', 92, 'Real Madrid CF']] df = pd.DataFrame(data[1:], columns=data[0]) df['Name'] = df['Name'].replace(r'((\s+[A-Z]{2,3}))+$', '', regex=True) print(df) This would give you: Name Overall Club 0 L. Messi 94 FC Barcelona 1 Cristiano Ronaldo 92 Real Madrid CF

http://stackoverflow.com/q/49374608
linked to: http://stackoverflow.com/q/37975227
answer count: 2
downvote count: 0
tagged with: apache-spark
has title: pyspark dataframe cube method returning duplicate null values
has body: I have the following data (you can reproduce it by copying and pasting): from pyspark.sql import Row l = [Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=None)] l_df = spark.createDataFrame(l) Let's take a look at the schema of l_df: l_df.printSchema() root |-- value: boolean (nullable = true) Now I want to use cube() to count the frequency of each dist…
favorite count: 0
type: Question
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/85754273
has answer: http://stackoverflow.com/a/49382389
has answer: http://stackoverflow.com/a/51190062
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/85751332
tagged with: python-2.7

http://stackoverflow.com/q/49403645
tagged with: jquery
answer count: 1
type: Question
tagged with: javascript
tagged with: python
type: UnansweredQuestion
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/49403928
has body: I'm have been trying to get a single article on my website and have it swtich to another article on interval. I'm using flask to scrape the arcile title,image and text from 3 different source. Then I render a template with those elements in a list. See code: @app.route('/test') def hello_world(): offshorenergyfeed = feedparser.parse('https://feeds.feedburner.com/OffshoreEnergyToday?format=xml') offshorewindfeed = feedparser.parse('http://feeds.feedburner.com/OffshoreWindNews?format=xml') rechargefeed = feedparser.parse('http://www.rechargenews.com/rss/') feedlinks = [offshorenergyfeed.entries[0]['link'],offshorewindfeed.entries[0]['link'],rechargefeed.entries[0]['link']] artikel_tekst = [] artikel_titel = [] artikel_image = [] for link in feedlinks: artikel = Article(link) artikel.download() artikel.parse() artikel_tekst.append(artikel.text) artikel_titel.append(artikel.title) artikel_image.append(artikel.top_image) return render_template('graph.html', artikel_tekst = artikel_tekst, artikel_titel = artikel_titel, artikel_image = artikel_image, ) Now I want to I want to display 1 article at the time and swtich it to another with an interval(lets say 5 minutes). For some reason I can only get it to work with the title switch. Text and Image won't switch with the given code: &lt;div id=newsarticle_container&gt; &lt;h1 id='titel'&gt;{{artikel_titel[0]}}&lt;/h1&gt; &lt;img id=plaatje src="{{artikel_image[0]}}"&gt; &lt;div id='tekst'&gt;{{artikel_tekst[0]}}&lt;/div&gt; &lt;/div&gt; &lt;script&gt; var titles = ["{{artikel_titel[0]}}", "{{artikel_titel[1]}}", "{{artikel_titel[2]}}"]; var images = ["{{artikel_image[0]}}", "{{artikel_image[1]}}", "{{artikel_image[2]}}"]; var text = ["{{artikel_tekst[0]}}", "{{artikel_tekst[1]}}", "{{artikel_tekst[2]}}"]; var counter = 0; var elem1 = document.getElementById("titel"); var elem2 = document.getElementById("plaatje"); var elem3 = document.getElementById("plaatje"); var inst = setInterval(change, 2000); function change() { elem1.in…
has title: I want to update an article every 5 minutes with javascript, can't get it to work

http://stackoverflow.com/q/49293183
upvote count: 1
tagged with: tensorflow
favorite count: 0
tagged with: redis
tagged with: python
type: Question
has body: I am trying to load a pretrained tensorflow model checkpoint while queuing the task in Redis. But it only shows "restoring checkpoint" and no response after that. Although the checkpoint is loaded successfully when called without queuing in redis.What could be possible reasons for this issue.Is there a way to check what is actually happening in redis? import os import tensorflow as tf import redis from rq import Worker, Queue, Connection import pandas as pd numDimensions = 300 maxSeqLength = 250 batchSize = 24 lstmUnits = 64 numClasses = 2 iterations = 100000 import numpy as np wordsList = np.load('wordsList.npy').tolist() wordsList = [word.decode('UTF-8') for word in wordsList] #Encode words as UTF-8 wordVectors = np.load('wordVectors.npy') #tf.Graph().as_default() # Removes punctuation, parentheses, question marks, etc., and leaves only alphanumeric characters import re strip_special_chars = re.compile("[^A-Za-z0-9 ]+") def cleanSentences(string): string = string.lower().replace("&lt;br /&gt;", " ") return re.sub(strip_special_chars, "", string.lower()) def getSentenceMatrix(sentence): arr = np.zeros([batchSize, maxSeqLength]) sentenceMatrix = np.zeros([batchSize,maxSeqLength], dtype='int32') cleanedSentence = cleanSentences(sentence) split = cleanedSentence.split() for indexCounter,word in enumerate(split): try: sentenceMatrix[0,indexCounter] = wordsList.index(word) except ValueError: sentenceMatrix[0,indexCounter] = 399999 #Vector for unkown words return sentenceMatrix def small(post): import tensorflow as tf tf.reset_default_graph() labels = tf.placeholder(tf.float32, [batchSize, numClasses]) input_data = tf.placeholder(tf.int32, [batchSize, maxSeqLength]) data = tf.Variable(tf.zeros([batchSize, maxSeqLength, numDimensions]),dtype=tf.float32) data = tf.nn.embedding_lookup(wordVectors,input_data) lstmCell = tf.contrib.rnn.BasicLSTMCell(lstmUnits) lstmCell = tf.contrib.rnn.DropoutWrapper(cell=lstmCell, output_keep_prob=0.25) value, _ = tf.nn.dynamic_rnn(lstmCell,…
answer count: 0
has title: I am trying to load a pretrained tensorflow model checkpoint while queing the task in Redis. But it only shows "restoring checkpoint"
type: UnansweredQuestion
score: 1
downvote count: 0

http://stackoverflow.com/comment/85821212
score: 0
type: Comment
type: QuestionComment
has text: @chepner if i try to explicitly import Solver it yields an import error. Does this mean something went wrong with the module installation?
comment on: http://stackoverflow.com/q/49409661

http://stackoverflow.com/comment/85826885
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49410058
has text: `f.write("\n".join(references))`. `f` is text doc, e.g. `f = open("/some/file.text", "w")`
type: Comment

http://stackoverflow.com/a/49307275
accepted answer of: http://stackoverflow.com/q/49304175
score: 1
type: Answer
has body: Typically a model of this size should not result in OOM. Since TF does a lot of lazy initialization, some OOMs won't be detected until the first request to initialize the data structure. In rare case certain graph can explode 10x in memory causing OOM. 1) Did you see the prediction error consistently? Due to the way Tensorflow schedules nodes the memory usage for the same graph might be different across runs. Make sure to run prediction multiple times and see if it's 429 every time. 2) Please make sure 151.1MB is the size of your SavedModel Directory. 3) You can also debug the peak memory locally, for instance using top when running gcloud ml-engine local predict or by loading the model into memory in a docker container and use docker stats or some other way to monitor memory usage. You can try tensorflow serving for debugging (https://www.tensorflow.org/serving/serving_basic) and post the results. 4) If you find the memory problem is persistent, please contact cloudml-feedback@google.com for further assistance, make sure you include your project number and associated account for further debugging.
answers question: http://stackoverflow.com/q/49304175
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49379448
linked to: http://stackoverflow.com/q/47062932
linked to: http://stackoverflow.com/q/44992860
downvote count: 0
possible better answer: http://stackoverflow.com/a/49379973
upvote count: 1
linked to: http://stackoverflow.com/q/4674473
favorite count: 0
type: AnsweredQuestion
has title: Value Error while running neural network code
tagged with: deep-learning
linked to: http://stackoverflow.com/q/43989934
score: 1
accepted answer: http://stackoverflow.com/a/49379997
tagged with: python
has answer: http://stackoverflow.com/a/49379997
has answer: http://stackoverflow.com/a/49379973
tagged with: tensorflow
has body: I am trying to create a neural network model to predict whether a signature is authentic or fake. I created the data set with 1044 signatures with authentic and fake signatures. This is the code for preprocessing the images DATA = '../DATASET/DATA/' IMG_BREDTH = 150 IMG_HEIGHT = 70 # helper functions def label_img(img): word_label = img.split('.')[-2] if (word_label == '1') or (word_label == '2'): return [1,0] elif word_label == 'F': return [0,1] def create_data_set(): data = [] for img in tqdm(os.listdir(DATA)): if img == '.DS_Store': continue label = label_img(img) path = os.path.join(DATA, img) img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_HEIGHT, IMG_BREDTH)) data.append([np.array(img), label]) shuffle(data) np.save('data.npy', data) return np.array(data) I then split the data into training and test set using this code data = create_data_set() train_x = data[:835, 0] train_y = data[:835, 1] test_x = data[835:, 0] test_y = data[835:, 1] train_x now contains 835 images and train_y contains the respective labels ([1,0] for authentic and [0,1] for fake). the shape of each image inside train_x is (150, 70). the shpae of train_y is (835, ) I then created the neural network with this code n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 2 batch_size = 100 x = tf.placeholder(tf.float32, [None, len(train_x[0])]) y = tf.placeholder(tf.float32) # neural network model def neural_network_model(data): hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_layer_3 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'biases': tf.Variable(tf.random_…
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/85799500
has text: IE should start default with zoom percentage as 100%. How did you landup with the deviation?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49398660

http://stackoverflow.com/q/49391072
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: loops
score: 1
has title: Iterating through Django Rest API and obtaining an error
has body: I have the following Django Rest API structure: [ { "title": "Project 1", "description": "API projects", "members": [ { "latest_activity": "15151020", "first_name": "AleX", "minutes_last_week": 0, "last_name": "Mol", "id": 23, "minutes_total": 30, "minutes_today": 0 }, { "latest_activity": "1515181664", "first_name": "Annie", "minutes_last_week": 0, "last_name": "Az", "id": 47, "minutes_total": 20, "minutes_today": 0 } ] }, { "title": "Project 2", "description": "Developer test (internal project", "members": [ { "latest_activity": "1511600", "first_name": "Ivan", "minutes_last_week": 0, "last_name": "XJJNX", "id": 18, "minutes_total": 10, "minutes_today": 0 }, { "latest_activity": "1516985", "first_name": "Lauren", "minutes_last_week": 0, "last_name": "Gom", "id": 39, "minutes_total": 560, "minutes_today": 0 } ] } ] What I want to do is iterate over this API, and obtain all the project names and developers that have been working in each project, so I developed the following function: def execute(): respuesta = requests.get('http://projd.herokuapp.com/api/v1/activities/?format=json', auth=('xxx','xxx')) upresponse = respuesta.json() for team in range(0, len(upresponse)-1):upresponse[team]["members"] print(team["first_name"]+" "+ team["last_name"] + " has been working in " + team["latest_activity"]) And I'm doing something wrong and I'm obtaining the following error: TypeError: 'int' object is not subscriptable. I can't understand why.
accepted answer: http://stackoverflow.com/a/49391629
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49391629
downvote count: 0
has comment: http://stackoverflow.com/comment/85783799
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/85783961
tagged with: django-rest-framework
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85886282
has text: @DinushaDilanka I had looked at several documentation on `pyspark` when you mentioned it today morning. But, to be honest you are being less helpful. In that link look at `7. Pandas vs PySpark DataFrame`, which suggests that there are several incompatibilities - thus this will cause a bit of a problem. I am trying to finish my project and this is less than helpful. If you can take the above code and shared file in dropbox how you propose on doing it - so I can apply the idea to my bigger program. Else, I doubt switching to pyspark in a day is possible. Thanks though !
score: 0
comment on: http://stackoverflow.com/q/49429368
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85658377
score: 0
has text: @Jean-FrançoisFabre is referring to https://en.wikipedia.org/wiki/Currying
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49328171

http://stackoverflow.com/q/49291355
score: 0
has body: I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt' I thought about using the method where you use the full path to open the file… but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise! with open('NYT-bestsellers.txt', 'r') as file: file = file.splitlines()
has comment: http://stackoverflow.com/comment/85585461
answer count: 1
tagged with: file
tagged with: directory
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49291678
has comment: http://stackoverflow.com/comment/85585437
tagged with: python
has title: How to fix: FileNotFoundError: [Errno 2] No such file or directory
tagged with: text

http://stackoverflow.com/a/49395811
has body: In general, it is good practice to use the with keyword when you are reading from a file, especially if you expect an Exception to occur. You can also enumerate to count the lines: with open(filename) as f: for line_num, line in enumerate(f): try: if (condition is met): do something else: do something else except Exception: print('Error: in line {:d} of file'.format(line_num)) It's best to not use Exception if you know the specific Exception you are expecting because it will catch all Exceptions, even those you don't expect.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49395512
upvote count: 1
score: 1

http://stackoverflow.com/comment/85706128
score: 0
has text: A better solution might be building a container (or a general-purpose VM image) that includes a minimal linux installation, including Python and your virtual environment. But then you still need to install a runner for that container (or VM) on Windows.
type: Comment
comment on: http://stackoverflow.com/q/49352930
type: QuestionComment

http://stackoverflow.com/q/49399517
tagged with: python
has comment: http://stackoverflow.com/comment/87320472
type: AnsweredQuestion
has title: Using WMI-Client-Wrapper to execute an exe and get output logs
has body: Objective: I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux. Problem: I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper. What I tried Python Code: import os import wmi_client_wrapper as wmic from socket import * import time wmic = wmic.WmiClientWrapper( host ="192.168.115.128", username = "LegalWrongDoer", password = "sasuke14" ) SW_SHOWNORMAL = 1 str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'" os.system(str) print("Folder sent") process_startup = wmic.Win32_ProcessStartup.new() process_startup.ShowWindow = SW_SHOWNORMAL process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup) process_startup.ShowWindow = SW_SHOWNORMAL if result == 0: print("Process started successfully") else: print("Sorry, but can't execute Process!") When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails. Further Traceback Calls: Traceback (most recent call last): File "WMIClient.py", line 22, in &lt;module&gt; process_startup = wmic.Win32_ProcessStartup.new() AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup' I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
score: 0
answer count: 1
type: Question
tagged with: linux
accepted answer: http://stackoverflow.com/a/50187596
has comment: http://stackoverflow.com/comment/87391303
has answer: http://stackoverflow.com/a/50187596

http://stackoverflow.com/comment/85637185
comment on: http://stackoverflow.com/q/49298271
type: QuestionComment
has text: what's your html5lib version ?
type: Comment
score: 0

http://stackoverflow.com/comment/85664925
comment on: http://stackoverflow.com/q/49331426
score: 0
type: Comment
type: QuestionComment
has text: it is its just because that data doesn't have a header so it automatically makes the header 0. There is no 0 in the data

http://stackoverflow.com/a/49428764
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85858739
has comment: http://stackoverflow.com/comment/85859092
has body: IIUC need convert values of A to set, then groupby and converted B values are added to s and cast back to lists, last add Group_name column: s = set(list(df['A'])) print (s) {11, 12} df = df.groupby('A')['B'].apply(lambda x: list(set(x) | s)).reset_index() #thanks asongtoruin for better solution df['Group_name'] = 'Group ' + (df.index + 1).astype(str) print (df) A B Group_name 0 11 [12, 11, 4, 5, 6] Group1 1 12 [11, 3, 12] Group2
type: Answer
accepted answer of: http://stackoverflow.com/q/49428435
score: 1
answers question: http://stackoverflow.com/q/49428435

http://stackoverflow.com/comment/85816664
comment on: http://stackoverflow.com/q/49407711
has text: the html code maybe useful
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85695224
comment on: http://stackoverflow.com/a/49346462
type: Comment
type: AnswerComment
has text: @FaqahatFareed then need `df = df.drop('acm_classification', 1).astype(str).add(df['acm_classification'].astype(str), axis=0); print (df)` ?
score: 0

http://stackoverflow.com/a/49367430
accepted answer of: http://stackoverflow.com/q/49365883
upvote count: 3
has body: To put it really simply, if they are in different LAN, meaning networks, you will need a layer 3 device (typically a router) to route the traffic between the devices. Say device A IP is 192.168.3.3/24 (subnet mask 255.255.255.0 /24) and device B is 192.168.4.4/24. If A wants to send to B, he won't know how to send this as the device will check it's subnet mask and see that the network portion is not the same. Thus you will need what we call a default gateway or a static route. To make it easier we will stick with a default gateway (and check the static route usage if you need this specifically). This means for the device: if you don't know where the other network is, send this packet to the default gateway (router) he will deal with this and find the way to the end device. Technically speaking it doesn't really matter to be on the WAN or LAN, in the end it's a different network and packet needs to be routed. One important point, you will need to know the IP at some point. Either you, the app or whatever. One previous comment mentioned the use of DNS, this can be a solution but you still need to know an IP address. In a way it's like saying I will send you a letter but I don't know your address. This won't be delivered.
downvote count: 0
answers question: http://stackoverflow.com/q/49365883
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85736477
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85736346
has comment: http://stackoverflow.com/comment/85736171
has comment: http://stackoverflow.com/comment/85736004
has comment: http://stackoverflow.com/comment/85735663

http://stackoverflow.com/comment/90682211
type: Comment
type: QuestionComment
has text: Here is the answer https://stackoverflow.com/a/50876207/898057
comment on: http://stackoverflow.com/q/49386920
score: 0

http://stackoverflow.com/a/49325919
type: Answer
accepted answer of: http://stackoverflow.com/q/49325164
upvote count: 1
has comment: http://stackoverflow.com/comment/85655977
has comment: http://stackoverflow.com/comment/85657115
has body: You could do it like this: with open('test.bin', 'rb') as f: data = f.read() def reverse(b): return int('{:08b}'.format(b)[::-1], 2) out = bytearray() for i in range(0, len(data), 2): out.extend((reverse(data[i+1]), reverse(data[i]))) with open('out.bin', 'wb') as f: f.write(out) The reverse part is from nneonneo's answer to Reversing bits of Python integer
answers question: http://stackoverflow.com/q/49325164
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85655558
has comment: http://stackoverflow.com/comment/85658198
has comment: http://stackoverflow.com/comment/85657633

http://stackoverflow.com/comment/85576064
type: Comment
type: QuestionComment
has text: `print` merely outputs data, it doesn't do any formatting. `print(stuff)` means `sys.stdout.write(str(stuff))`, so, it's `str` that does the formatting. You can customise what `str` returns for your class by using the `__str__` method. However, you can't easily change the representation of other objects as that'd require you to reimplement their `__str__`.
score: 0
comment on: http://stackoverflow.com/q/49286472

http://stackoverflow.com/a/49439082
has body: You should probably use a system that's meant for sharing large amounts of data with many different processes -- like a Database. Take your giant dataset and create a schema for it and dump it into a database. You could even put it on a separate machine. Then launch as many processes as you want, across as many hosts as you want, to process the data in parallel. Pretty much any modern database will be more than capable of handling the load.
score: 10
has comment: http://stackoverflow.com/comment/86193945
type: Answer
upvote count: 10
answers question: http://stackoverflow.com/q/49438954
downvote count: 0
has comment: http://stackoverflow.com/comment/86195185
has comment: http://stackoverflow.com/comment/86193801
has comment: http://stackoverflow.com/comment/86189310

http://stackoverflow.com/a/49326581
has comment: http://stackoverflow.com/comment/85655197
has comment: http://stackoverflow.com/comment/85655172
type: Answer
has comment: http://stackoverflow.com/comment/131546403
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49326282
has comment: http://stackoverflow.com/comment/85655462
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85655402
answers question: http://stackoverflow.com/q/49326282
has body: Yes, you can override the delete_view() and response_action() methods of your ModelAdmin. I would also suggest to override the has_delete_permission() method so that the "Delete" button won't appear at all: class MyModelAdmin(admin.ModelAdmin): def delete_view(self, request, object_id, extra_context=None): try: return super().delete_view(request, object_id, extra_context) except ProtectedError: msg = "you cannot delete this object" self.message_user(request, msg, messages.ERROR) opts = self.model._meta return_url = reverse( 'admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(object_id,), current_app=self.admin_site.name, ) return HttpResponseRedirect(return_url) def response_action(self, request, queryset): try: return super().response_action(request, queryset) except ProtectedError: msg = "you cannot delete this object" self.message_user(request, msg, messages.ERROR) opts = self.model._meta return_url = reverse( 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) return HttpResponseRedirect(return_url) def has_delete_permission(self, request, obj=None) return super().has_delete_permission(request, obj) and ( not obj or obj.name != 'bar' )

http://stackoverflow.com/a/49303838
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49297254
has body: Ok, turns out without metaclass=ABCMeta only mypy will catch the error whereas with the metaclass=ABCMeta both mypy and python will catch the error. See: from abc import abstractmethod class C(): @abstractmethod def my_abstract_method(self): print('foo') class D(C): pass x = C() y = D() $ mypy test.py test.py:13: error: Cannot instantiate abstract class 'C' with abstract attribute 'my_abstract_method' test.py:15: error: Cannot instantiate abstract class 'D' with abstract attribute 'my_abstract_method' but $ python3 test.py $ Whereas with that, python will catch the error as well. from abc import ABCMeta, abstractmethod class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self): print('foo') class D(C): pass x = C() y = D() $ python3 test.py Traceback (most recent call last): File "test.py", line 11, in &lt;module&gt; x = C() TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
score: 4

http://stackoverflow.com/a/49526918
has body: The first step is correct, i.e. the mapping is correct. But then, you need to first index a query, that's the whole point of percolation. So let's index your query: curl -XPUT 'localhost:9200/my-index/_doc/my-span-query?refresh&pretty' -H 'Content-Type: application/json' -d '{ "query": { "span_near" : { "clauses" : [ { "span_term" : { "title" : "dünya" } }, { "span_term" : { "title" : "mirası" } }, { "span_term" : { "title" : "sözleşmesi" } } ], "slop" : 0, "in_order" : true } } }' Then the idea is to find out which query would match the document you're percolating, so let's percolate a document: curl -XGET 'localhost:9200/my-index/_search?pretty' -H 'Content-Type: application/json' -d '{ "query" : { "percolate" : { "field" : "query", "document" : { "title" : "Arkeoloji, arkeolojik yöntemlerle ortaya çıkarılmış kültürleri, dünya mirası sözleşmesi sosyoloji, coğrafya, tarih, etnoloji gibi birçok bilim dalından yararlanarak araştıran ve inceleyen bilim dalıdır. Türkçeye yanlış bir şekilde> \"kazıbilim\" olarak çevrilmiş olsa da kazı, arkeolojik araştırma yöntemlerinden sadece bir tanesidir." } } }, "highlight": { "fields": { "title": {} } } }' And you would get this response with highlighting where you can see that my-span-query matches the given document: { "took": 104, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 1, "max_score": 0.8630463, "hits": [ { "_index": "my-index", "_type": "_doc", "_id": "my-span-query", "_score": 0.8630463, "_source": { "query": { "span_near": { "clauses": [ { "span_term": { "title": "dünya" } }, { "span_term": { "title": "mirası" } }, { "span_term": { "title": "sözleşmesi" } } ], "slop": 0, "in_order": true } } }, "fields": { "_percolator_document_slot": [ 0 ] }, "highlight": { "title": [ "Arkeoloji, arkeolojik yöntemlerle ortaya çıkarılmış kültürleri, dünya mirası sözleşmesi sosyoloji, coğrafya" ] } } ] } } UPDATE The same thing using elasticsearch-py-dsl: from elasticsearc…
has comment: http://stackoverflow.com/comment/86164271
has comment: http://stackoverflow.com/comment/86089991
has comment: http://stackoverflow.com/comment/86452656
has comment: http://stackoverflow.com/comment/86306974
has comment: http://stackoverflow.com/comment/86117072
has comment: http://stackoverflow.com/comment/86071106
has comment: http://stackoverflow.com/comment/86303836
answers question: http://stackoverflow.com/q/49387372
has comment: http://stackoverflow.com/comment/86068373
has comment: http://stackoverflow.com/comment/86091453
has comment: http://stackoverflow.com/comment/86059858
has comment: http://stackoverflow.com/comment/86073999
has comment: http://stackoverflow.com/comment/86071462
has comment: http://stackoverflow.com/comment/86074455
has comment: http://stackoverflow.com/comment/86075369
has comment: http://stackoverflow.com/comment/86789302
has comment: http://stackoverflow.com/comment/86103185
type: Answer
accepted answer of: http://stackoverflow.com/q/49387372
has comment: http://stackoverflow.com/comment/86090211
score: 4
has comment: http://stackoverflow.com/comment/86068482
has comment: http://stackoverflow.com/comment/86061779
has comment: http://stackoverflow.com/comment/86067717
has comment: http://stackoverflow.com/comment/86060145
has comment: http://stackoverflow.com/comment/86089301
upvote count: 4
has comment: http://stackoverflow.com/comment/86126636
has comment: http://stackoverflow.com/comment/86062077
has comment: http://stackoverflow.com/comment/86075130
has comment: http://stackoverflow.com/comment/86789171
has comment: http://stackoverflow.com/comment/86073880
has comment: http://stackoverflow.com/comment/86069721
has comment: http://stackoverflow.com/comment/86126827
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86068358
downvote count: 0
has comment: http://stackoverflow.com/comment/86066203
has comment: http://stackoverflow.com/comment/86091099
has comment: http://stackoverflow.com/comment/86451257

http://stackoverflow.com/q/49371343
answer count: 1
duplicate of: http://stackoverflow.com/q/13445241
tagged with: string
has answer: http://stackoverflow.com/a/49371512
type: Question
linked to: http://stackoverflow.com/q/13445241
has comment: http://stackoverflow.com/comment/85743829
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85743776
tagged with: python
score: 0
tagged with: pandas
has body: I want to apply this function df.column.str.split(expand = True) but the problem is there are some "empty cells", and when I mean "empty" it means that it has, for example, 6 white-spaces. Moreover, this is an iteration, so sometimes I have cells with 2 white-spaces. How can I identify this "empty cells"? PD: df[df.column != '(6 spaces inside)'] works only for a particular case when there are 6 spaces. EDIT 1: the df.column is an object type with people names (one or more than one, even errors) EDIT 2: The idea is to remove this cell (row) in order to successfully applied the "str.split" function. This is an interation so sometimes I have cells with 6 spaces and other with 2 spaces. EDIT 3: I can't remove all whitespaces because then I won't be able to apply the string separation (because I have names like "Jean Carlo" that I want to separate) FINAL SOLUTION: I could solve the problem with the post that was signaled only adding a '+' because I have whitespaces in other cells. Solution: df = df.replace(['^\s+$'], np.nan, regex = True)
has title: Identify cells with only whitespace

http://stackoverflow.com/q/49297456
favorite count: 0
tagged with: multiclass-classification
type: Question
has body: I am using the Tensorflow DNNClassifier for my dataset that has 25 features, and 12 class labels. My code right now is: def main(): training_set = tf.contrib.learn.datasets.base.load_csv_without_header(filename=TRAINING,target_dtype=np.int,features_dtype=np.float32) test_set = tf.contrib.learn.datasets.base.load_csv_without_header(filename=TEST,target_dtype=np.int,features_dtype=np.float32) feature_columns = [tf.contrib.layers.real_valued_column("", dimension=25)] classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,activation_fn = tf.nn.relu,hidden_units=[50, 50, 50, 50, 50,50, 50, 50, 50, 50],optimizer=tf.train.AdamOptimizer(0.01),n_classes=12, model_dir="./model/") def get_train_inputs(): x = tf.constant(training_set.data) y = tf.constant(training_set.target) return x, y classifier.fit(input_fn=get_train_inputs, steps=1000) def get_test_inputs(): x = tf.constant(test_set.data) y = tf.constant(test_set.target) return x, y accuracy_score = classifier.evaluate(input_fn=get_test_inputs,steps=1)["accuracy"] print("\n\nTest Accuracy: {0:f}\n".format(accuracy_score)) def new_samples(): with open(PREDICT,"r") as f: contents = f.readlines() arr = [] for c in contents: arr.append([float(x.strip()) for x in c.split(",")]) return np.array(arr, dtype=np.float32) predicted_classes = list(classifier.predict(input_fn=new_samples)) print("Predicted class: {}\n".format(predicted_classes)) probabilities = list(classifier.predict_proba(input_fn=new_samples)) print("Predictions probability: ", probabilities) probabs = np.array(probabilities) The accuracy on both the training and test data is less than 0.2 I have tried more epochs, changing the learning rate, activation function and optimizer, but the accuracy is not increasing. According to my knowledge, my network is underfitting severely. In which case adding more nodes and layers should work, but increasing the nodes and layers barely increases the accuracy and it is still below 0.2 Can anyone please point o…
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 2
answer count: 0
downvote count: 0
tagged with: classification
has title: Tensorflow classifier underfits consistently
tagged with: tensorflow

http://stackoverflow.com/comment/85792203
type: AnswerComment
score: 2
has text: Yes; they used appropriate terminology for such discussions. You understand the underlying situation quite well. Personally, I'd have a quick chat with their tech writer ...
comment on: http://stackoverflow.com/a/49395194
type: Comment

http://stackoverflow.com/q/49389920
favorite count: 0
has title: What's the best way to allow a user to select from multiple functions to run in Python?
accepted answer: http://stackoverflow.com/a/49389997
has body: I've got 20 files, each defining their own function. Sets of files are related. Each file defines a sport and an age group. So, as an example, these functions exist, each in their own individual file: footballAdults() footballTeens() footballKids() tennisAdults() tennisTeens() .... etc. I want to allow the user to to call any one of them through a main file, filtering their choices like so: x = input("Pick a sport:") y = input ("Pick an age group:") Then, the program will filter through the user's choices to run the function the user has chosen. Is there a better way to do this other than by doing a huge if...elif...elif...elif...else statement, or am I stuck doing that? Example: from footballAdults import footballAdults from footballTeens import footballTeens from footballKids import footballKids from tennisAdults import tennisAdults #this would continue on until all 20 files have had their functions imported x = input("Pick a sport:") y = input ("Pick an age group:") if x == ("football") and y == ("adults") footballAdults() elif x == ("football") and y == ("teens") footballTeens() elif x == ("football") and y == ("kids") footballKids() elif x == ("tennis") and y == ("adults") tennisAdults() #this would continue on until the final else statement #cycling through all 20 functions
type: Question
tagged with: if-statement
has answer: http://stackoverflow.com/a/49389997
tagged with: python-3.x
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: python
tagged with: dictionary
answer count: 1

http://stackoverflow.com/comment/85879511
score: 0
type: AnswerComment
has text: I really like this solution but it throws an error every time it encounters a key that is not present, is there a way to avoid that?
comment on: http://stackoverflow.com/a/49438694
type: Comment

http://stackoverflow.com/comment/85700914
type: QuestionComment
has text: @Jean-FrançoisFabre I am not sure I would agree with *irrelevant*, but it may not be perfect, please feel free to reopen it
comment on: http://stackoverflow.com/q/49339589
score: 0
type: Comment

http://stackoverflow.com/q/49357973
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37110879
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85716488
duplicate of: http://stackoverflow.com/q/37110879
score: 2
has answer: http://stackoverflow.com/a/49358330
answer count: 2
has comment: http://stackoverflow.com/comment/85716163
has answer: http://stackoverflow.com/a/49358321
downvote count: 0
duplicate of: http://stackoverflow.com/q/31406975
favorite count: 0
has body: Is it possible to do a polynomial regression line on a scatter() in matplotlib? This is my graph: https://i.sstatic.net/3ra9x.jpg alg_n = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4...] orig_hc_runtime = [0.01, 0.02, 0.03, 0.04, 0.04, 0.04, 0.05, 0.09...] plt.scatter(alg_n, orig_hc_runtime, label="Orig HC", color="b", s=4) plt.scatter(alg_n, mod_hc_runtime, label="Mod HC", color="c", s=4) ... x_values = [x for x in range(5, n_init+2, 2)] y_values = [y for y in range(0, 10, 2)] plt.xlabel("Number of Queens") plt.ylabel("Time (sec)") plt.title("Algorithm Performance: Time") plt.xticks(x_values) plt.yticks(y_values) plt.grid(linewidth="1", color="white") plt.legend() plt.show() Is it possible to have regression lines for eat data set? If so, can you please explain how I can do it.
type: Question
upvote count: 2
has title: Matplotlib scatter(): Polynomial regression line

http://stackoverflow.com/comment/85820666
has text: This is indeed a breaking change for a lot of Anaconda users. See this (heated) GH issue https://github.com/pypa/pip/issues/5081
comment on: http://stackoverflow.com/a/49401566
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49347548
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85700078
accepted answer of: http://stackoverflow.com/q/49347310
has comment: http://stackoverflow.com/comment/85695732
answers question: http://stackoverflow.com/q/49347310
has body: The reason your code isn't working is because k*v will replicate the string v times e.g: o*3 gives use ooo. def export_inventory(inventory, filename="export_inventory.csv"): l = [] with open(filename, "w") as csvfile: new = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) for key,value in inventory.items(): l+=[key for _ in range(value)] new.writerow(l)
type: Answer
has comment: http://stackoverflow.com/comment/85714126
has comment: http://stackoverflow.com/comment/85698328

http://stackoverflow.com/a/49329249
type: Answer
has comment: http://stackoverflow.com/comment/85660956
has comment: http://stackoverflow.com/comment/85660918
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85660884
has comment: http://stackoverflow.com/comment/85660511
downvote count: 0
has body: This is a well documented error. Take a look at How to deal with SettingWithCopyWarning in Pandas?. For the fix, start with raw_corpus = raw_corpus.copy(deep=True) Next, get a list of all the columns you want to aggregate: cols = ['trigger_channel_cat', 'trigger_channel_clean', ...] And call df.agg: raw_corpus['constructed_recipe'] = raw_corpus[cols].agg(' '.join, axis=1)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49329183
has comment: http://stackoverflow.com/comment/85660759
accepted answer of: http://stackoverflow.com/q/49329183

http://stackoverflow.com/comment/85742502
type: AnswerComment
has text: What is the max local space allowed on the colab instance?
comment on: http://stackoverflow.com/a/49362032
type: Comment
score: 0

http://stackoverflow.com/q/49283986
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49284503
accepted answer: http://stackoverflow.com/a/49284503
type: Question
has body: I am running a Kmeans algorithm with pyspark. The input is a Vector of length 20 (output of a word2vec on text verbatims). I then transform my input dataframe to get the predicted center associated to each verbatim. from pyspark.ml.clustering import KMeans n_centres = 14 kmeans = KMeans().setK(n_centres).setSeed(1) model = kmeans.fit(df) df_pred = model.transform(df) I have the following results : df_pred.show() +--------------------+----------+ | features|prediction| +--------------------+----------+ |[-0.1879145856946...| 13| |[-0.4428333640098...| 6| |[0.00466226078569...| 9| |[0.09467326601346...| 12| |[-0.0388545106080...| 5| |[-0.1805213503539...| 13| |[0.08455141757925...| 3| +--------------------+----------+ I would like to add a column to my dataframe containing the distance between the features array and the center to which it is associated. I know I can get the coordinates of the center, I know how to compute the distance between a vector and the center : model.clusterCenters()[3] # to get the coordinates of cluster number 3 v1.squared_distance(center_vect) # euclidean distance between v1 and the center center_vect But I can't figure out how to add the result of this computation as a column. A udf or a map seems to be a solution but I keep getting errors like : PicklingError: Could not serialize object....
tagged with: k-means
tagged with: pyspark
tagged with: python
has title: Create column with distance to center
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87602257
score: 2
comment on: http://stackoverflow.com/q/49348839
has text: Did you consider mocking Neo4j in your tests?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49313055
has comment: http://stackoverflow.com/comment/85628391
has comment: http://stackoverflow.com/comment/85664062
upvote count: 4
answers question: http://stackoverflow.com/q/49312540
downvote count: 1
score: 3
type: Answer
has body: Ctrl+F5 is a shortcut to Start without Debugging What you want is just running a file according to your post. To run a python file in the integrated terminal, right-click your editor window and Run Python File in Terminal. It should open up a terminal window within VS Code and run as normal. It also takes into account the environment you are currently using whenever you run it. To answer your other question about Python Experimental, it is an option to use the experimental debugger, an alternate version of a Python Debugger. You can read the instructions here

kivy
tags question: http://stackoverflow.com/q/49414737
tags question: http://stackoverflow.com/q/49289412
tags question: http://stackoverflow.com/q/49297316
tags question: http://stackoverflow.com/q/49367546
type: Tag
tags question: http://stackoverflow.com/q/49399940
tag name: kivy
tags question: http://stackoverflow.com/q/49284459
tags question: http://stackoverflow.com/q/49434491
tags question: http://stackoverflow.com/q/49434908
tags question: http://stackoverflow.com/q/49353288
tags question: http://stackoverflow.com/q/49334697
tags question: http://stackoverflow.com/q/49320520
tags question: http://stackoverflow.com/q/49385148
tags question: http://stackoverflow.com/q/49320747
tags question: http://stackoverflow.com/q/49378827
tags question: http://stackoverflow.com/q/49309631
tags question: http://stackoverflow.com/q/49357315
tags question: http://stackoverflow.com/q/49421627
tags question: http://stackoverflow.com/q/49334295
tags question: http://stackoverflow.com/q/49438255
tags question: http://stackoverflow.com/q/49308461
tags question: http://stackoverflow.com/q/49403918
tags question: http://stackoverflow.com/q/49409322
tags question: http://stackoverflow.com/q/49399678
tags question: http://stackoverflow.com/q/49312256
tags question: http://stackoverflow.com/q/49324241
tags question: http://stackoverflow.com/q/49312760
tags question: http://stackoverflow.com/q/49313316
tags question: http://stackoverflow.com/q/49396155
tags question: http://stackoverflow.com/q/49352732
tags question: http://stackoverflow.com/q/49324659
tags question: http://stackoverflow.com/q/49314588

http://stackoverflow.com/a/49314754
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49314455
type: Answer
has body: NaNs can be replaced with zeros for the operation. Using the same solution as Replace nan values in tensorflow tensor sess.run(tf.reduce_mean(tf.abs(tf.where(tf.is_nan(x), tf.zeros_like(x), x)-y)))
score: 0
accepted answer of: http://stackoverflow.com/q/49314455

http://stackoverflow.com/comment/85631055
type: Comment
comment on: http://stackoverflow.com/a/49314719
type: AnswerComment
has text: Duplicate of 'A','B','D' columns?
score: 0

http://stackoverflow.com/q/49388884
score: 0
has title: Using multiple gpus for regression
answer count: 1
tagged with: machine-learning
tagged with: multiple-gpu
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has body: I am trying to write a tensorflow code for a regression problem. I have written the code and it works perfectly when run on a single gpu. However, I want to test how fast can it go a 2 gpus. I have modified the code for 2 gpus using tf.device. But I am not sure how can I code the loss on cpu and update the weights based on that? Did I even write it correctly? Another question is the batch size, how can I modify the batch size for the 2 gpus? import numpy as np import tensorflow as tf import threading from sklearn import cross_validation X_train0 = np.load('XTrain006.npy') ncol = X_train0.shape[0] Y_train00 = np.load('YTrain006.npy') Y_train0 = Y_train00[:,:] print Y_train0.shape[0] X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X_train0, Y_train0, test_size=0.1, random_state=42) XMEAN=np.max(X_train,axis=0) XSTDD=np.min(X_train,axis=0) X_train=(X_train-XSTDD)/(XMEAN-XSTDD) X_test=(X_test-XSTDD)/(XMEAN-XSTDD) #print X_train[0:10,189:219] for j in range(3808): if((XMEAN[j]-XSTDD[j])== 0): X_train[:,j] = 0.0 X_test[:,j] = 0.0 print XMEAN[189:219] print XSTDD[189:219] np.savetxt('xdiff.dat',XMEAN-XSTDD) np.savetxt('xmin.dat',XSTDD) np.savetxt('xmax.dat',XMEAN) YMEAN=np.max(Y_train,axis=0) YSTDD=np.min(Y_train,axis=0) Y_trainYY = Y_train Y_train=(Y_train-YSTDD)/(YMEAN-YSTDD) Y_test=(Y_test-YSTDD)/(YMEAN-YSTDD) for j in range(1035): if(YMEAN[j]-YSTDD[j]== 0): Y_train[:,j] = Y_trainYY[:,j] np.savetxt('ydiff.dat',YMEAN-YSTDD) np.savetxt('ymin.dat',YSTDD) np.savetxt('ymax.dat',YMEAN) total_len = X_train.shape[0] learning_rate = 0.001 training_epochs = 50 batch_size = 64 display_step = 1 # Network Parameters n_hidden_1 = 64 # 1st layer number of features n_hidden_2 = 64 # 2nd layer number of features n_hidden_3 = 64 n_input = 3808 n_classes = 1035 for d in ['/device:GPU:0', '/device:GPU:1']: with tf.device(d): # tf Graph input x = tf.placeholder("float64", [None, 3808]) y = tf.placeholder("float64", [None, 1035]) # Create model def multilayer_perceptron(…
tagged with: python
has answer: http://stackoverflow.com/a/49389715

http://stackoverflow.com/comment/85662366
type: Comment
type: QuestionComment
score: 0
has text: Did you try sorting those values? `avgsalary_10jobtitle.sort_values(by='TotalPayBenefits', ascending=False)`
comment on: http://stackoverflow.com/q/49330100

http://stackoverflow.com/q/49407911
upvote count: 1
score: 1
has body: I have a 1 column dataframe df = pd.read_csv(txt_file, header=None) I am trying to search for a string in the column and then return the row after key_word_df = df[df[0].str.contains("KeyWord")] I dont know how you can then every each time the keyword is found, isolate the row below it and assign to a new df.
favorite count: 0
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/49408199
has answer: http://stackoverflow.com/a/49408199
possible better answer: http://stackoverflow.com/a/49408254
tagged with: python
has answer: http://stackoverflow.com/a/49408254
tagged with: python-2.7
has title: Pandas dataframe isolate row below a keyword
tagged with: pandas
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49408212

http://stackoverflow.com/q/49339067
score: -3
has comment: http://stackoverflow.com/comment/85678847
answer count: 1
has title: How to translate a python file to linux executable file
downvote count: 3
has comment: http://stackoverflow.com/comment/85744927
has comment: http://stackoverflow.com/comment/85744645
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85744772
tagged with: linux
has body: I use python 2.7 and I am wondering how can I change my python code into a linux executable file very similar to using gcc -o hello hello.c but with python
has answer: http://stackoverflow.com/a/49339099
tagged with: python
has comment: http://stackoverflow.com/comment/85744563
duplicate of: http://stackoverflow.com/q/12059509
has comment: http://stackoverflow.com/comment/85744973
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5458048

http://stackoverflow.com/comment/85702911
comment on: http://stackoverflow.com/q/49349682
type: Comment
score: 1
type: QuestionComment
has text: `pip install boto3 --user`. Always install python packages with the `--user` flag.

http://stackoverflow.com/q/49336415
has comment: http://stackoverflow.com/comment/92371130
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85676111
answer count: 1
tagged with: button
has comment: http://stackoverflow.com/comment/85676599
has answer: http://stackoverflow.com/a/52722929
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85676147
tagged with: raspberry-pi
tagged with: bounce
type: UnansweredQuestion
has body: I have a strange problem with raspberry (3B) ang GPIO as Input. I'm actually just experimenting and trying to get a pushbutton press without side effects. setup Hardware PIN 16 (GPIO 26) as IN PIN 6 as GND 2 open Jumper wires on the pins for better debugging. Later there will be pushbutton behind Software Raspbian 9.4 stretch Kernel 4.9.80-v7+ (newest over normal apt-get) RPi.GPIO version 0.63 code #!/usr/bin/python import RPi.GPIO as GPIO from time import sleep red_channel = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(red_channel, GPIO.IN, pull_up_down=GPIO.PUD_UP) # pin is up to 3.3V try: while True: state = GPIO.input(red_channel) if state == 0: # when pin pulled down print 'red pressed', state sleep(0.3) except KeyboardInterrupt: GPIO.cleanup() Problem When I run the code and only come with my hand in the near of the jumper wires or even move them, button pressure will be detected. And at this point I don't get why! Did I get something wrong? Solutions already tried new wires other ports other raspberry (same version)! OS new installed and GPIO Libs fresh installed Breadboard between (same effect) Thanks for your help!
tagged with: gpio
tagged with: python
has title: Raspberry-pi gpio input not stable
has comment: http://stackoverflow.com/comment/85676481
has comment: http://stackoverflow.com/comment/85742101

adaboost
tag name: adaboost
tags question: http://stackoverflow.com/q/49307047
type: Tag

http://stackoverflow.com/q/49342183
type: AnsweredQuestion
has body: I have a list of e-mail ids among which I have to select only those which do not have ruba.com as domain name with regex. For examples, if I have ads@gmail.com, dgh@rubd.com and ert@ruba.com, then my regular expression should select first two Ids. What should be the regular expression for this problem? I have tried with two expressions: [a-zA-Z0-9_.+-]+@[^(ruba)]+.[a-zA-Z0-9-.]+ and [a-zA-Z0-9_.+-]+@[^r][^u][^b][^a]+.[a-zA-Z0-9-.]+ None of the above two was able to fulfill my requirement.
possible better answer: http://stackoverflow.com/a/49342323
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/85684821
type: Question
score: 2
answer count: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/49342334
has title: How can I avoid selecting email Ids with a particular domain name with regex
has answer: http://stackoverflow.com/a/49342323
has answer: http://stackoverflow.com/a/49342334
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2049502

http://stackoverflow.com/comment/85664367
comment on: http://stackoverflow.com/q/49331185
has text: `[w[0] for w in trans.split()]`
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/85714229
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49357099
has text: Possible duplicate of [Complete search algorithm for combinations of coins](https://stackoverflow.com/questions/43642133/complete-search-algorithm-for-combinations-of-coins)
type: Comment

http://stackoverflow.com/a/49330324
type: Answer
has body: You could define a mask that contains the circle. Below, I have demonstrated it for a circle, but you could write any arbitrary function in the mask assignment. The field mask has the dimensions of arr and has the value True if the condition on the righthand side is satisfied, and False otherwise. This mask can be used in combination with the indexing operator to assign to only a selection of indices, as the line arr[mask] = 123. demonstrates. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 32) y = np.arange(0, 32) arr = np.zeros((y.size, x.size)) cx = 12. cy = 16. r = 5. # The two lines below could be merged, but I stored the mask # for code clarity. mask = (x[np.newaxis,:]-cx)**2 + (y[:,np.newaxis]-cy)**2 &lt; r**2 arr[mask] = 123. # This plot shows that only within the circle the value is set to 123. plt.figure(figsize=(6, 6)) plt.pcolormesh(x, y, arr) plt.colorbar() plt.show()
has comment: http://stackoverflow.com/comment/136683502
downvote count: 0
upvote count: 21
score: 21
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/136686511
accepted answer of: http://stackoverflow.com/q/49330080
has comment: http://stackoverflow.com/comment/85663713
answers question: http://stackoverflow.com/q/49330080
has comment: http://stackoverflow.com/comment/85663630

http://stackoverflow.com/comment/85839128
type: QuestionComment
has text: @NathanHughes Calling `shutdown` will just tell the executor to stop giving out new tasks. Since he's manually batched things up so he only has a small number of tasks each of which does a huge number of loops, that won't help. (Of course a better design that let the executor do what it does best would mean `shutdown` is more useful, but…)
comment on: http://stackoverflow.com/q/49418638
score: 0
type: Comment

http://stackoverflow.com/a/49307408
upvote count: 5
type: Answer
score: 5
answers question: http://stackoverflow.com/q/49307303
downvote count: 0
has body: The problem is that pypiwin32 depends on pywin32, and, as the README says: Note that PIP support is experimental. Even if pip installs pywin32, you still have to manually run the post-install script with elevated privileges. So, rather than debugging why the experimental pip support isn't working for you, it's probably better to manually download the appropriate installer from the Releases page and run it. Once that completes, pip should know that you now have pywin32 version 223 installed, so pip install pypiwin32 should hopefully work. You might want to look through the pywin32 issues to see if anyone has reported this problem (it may only be mentioned in some issue about completing pip support, not a separate one) and, if not, file a bug report. That way, the next time someone wants to use pypiwin32, they may not even need this answer. (Since Mark Hammond, the main author of pywin32, is also listed as a maintainer of pypiwin32, I'm guessing he already knows about it—but it can't hurt to check.)

http://stackoverflow.com/q/49292137
type: Question
has comment: http://stackoverflow.com/comment/85586864
tagged with: python
accepted answer: http://stackoverflow.com/a/49292826
has comment: http://stackoverflow.com/comment/85596199
has title: Getting invalid type comparison error
has comment: http://stackoverflow.com/comment/85587159
has body: I am getting invalid type comparison error if anyone could help? Basically, I am getting an error on the line where I want to replace all "-" with zeros in the data frame, so as to make it uniform for numerical manipulations. Following is my code and error respectively: Code: import quandl, math import numpy as np import pandas as pd from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import time import seaborn as sns import matplotlib.pyplot as plt import datetime from matplotlib import style style.use('ggplot') # get market info for bitcoin from the start of 2016 to the current day bitcoin_market_info = pd.read_html("https://coinmarketcap.com/currencies/ethereum/historical-data/?start=20130428&amp;end="+time.strftime("%Y%m%d"))[0] # convert the date string to the correct date format bitcoin_market_info = bitcoin_market_info.assign(Date=pd.to_datetime(bitcoin_market_info['Date'])) # when Volume is equal to '-' convert it to 0 #In the line below I am getting error bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']=0 # convert to int bitcoin_market_info['Volume'] = bitcoin_market_info['Volume'].astype('int64') bitcoin_market_info.set_index('Date', inplace=True) bitcoin_market_info = bitcoin_market_info.reindex(index=bitcoin_market_info.index[::-1]) # look at the first few rows bitcoin_market_info.head() Error: F:\Anaconda3\lib\site-packages\pandas\core\ops.py:798: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison result = getattr(x, name)(y) Traceback (most recent call last): File "C:/Users/The_Anil/Desktop/fvsffsf.py", line 20, in &lt;module&gt; bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']=0 File "F:\Anaconda3\lib\site-packages\pandas\core\ops.py", line 861, in wrapper res = na_op(values, other) File "F:\Anaconda3\lib\site-packages\pandas\core\…
type: AnsweredQuestion
downvote count: 0
tagged with: data-mining
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85587684
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85587635
has answer: http://stackoverflow.com/a/49292826
tagged with: python-3.x

http://stackoverflow.com/comment/85845554
comment on: http://stackoverflow.com/a/49422423
score: 0
type: AnswerComment
has text: For starters, please indent your code.
type: Comment

http://stackoverflow.com/q/49306694
tagged with: python
tagged with: list-comprehension
answer count: 4
type: AnsweredQuestion
has title: create flat list from coins and quantities
accepted answer: http://stackoverflow.com/a/49306928
has answer: http://stackoverflow.com/a/49306924
has answer: http://stackoverflow.com/a/49306928
score: 1
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49306979
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49306979
linked to: http://stackoverflow.com/q/952914
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49307321
has body: I have an array with coins, e.g. (coins=[10, 50, 100]) and an array of the quantities of each coin (e.g. quantity=[1, 2, 1]). I want to generate a new list l, which shows all coins I have (e.g l=[10, 50, 50, 100]). So far i have this, which does the trick: coins=[i for s in [b*[a] for a,b in zip(coins,quantity)] for i in s] Is there a better way to solve this in python, than to create a list of lists and then flatten it?

http://stackoverflow.com/q/49367297
accepted answer: http://stackoverflow.com/a/49382781
answer count: 1
tagged with: quantlib-swig
has answer: http://stackoverflow.com/a/49382781
has title: DepositRateHelper unexpected keyword argument 'dayCounter'
type: Question
type: AnsweredQuestion
score: 0
has body: I copied the example for EONIA curve bootstrapping. I tried to link the inputs to the corresponding keyword arguments of the DepositRateHelper class. I checked the keyword arguments in the docs, which resulted in the following import QuantLib as ql today = ql.Date(11, 12, 2012) ql.Settings.instance().evaluationDate = today helpers = [ ql.DepositRateHelper(rate = ql.QuoteHandle(ql.SimpleQuote(rate/100)), tenor = ql.Period(1,ql.Days), fixingDays = fixingDays, calendar = ql.Germany(), convention = ql.Following, endOfMonth = False, dayCounter = ql.Actual360() ) for rate, fixingDays in [(0.04, 0), (0.04, 1), (0.04, 2)] ] Now I get a TypeError: TypeError: __init__() got an unexpected keyword argument 'dayCounter' If skipping all the "keywords" the code works perfectly fine. So my question is, is there a way to get to know the desired keywords or did I search in the wrong place? Best Daniel
tagged with: python

http://stackoverflow.com/comment/85821748
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the input. I was bored and like building classes; so I thought I'd give it a shot
comment on: http://stackoverflow.com/a/49409749

http://stackoverflow.com/q/49355187
tagged with: 3d
type: UnansweredQuestion
has title: Building the 3D Map Python
has answer: http://stackoverflow.com/a/50803600
tagged with: python
tagged with: opencv
tagged with: python-2.7
score: 0
answer count: 1
type: Question
tagged with: numpy
has body: Hi I'm a student and I try to make a 3d map reconstruction for a signature and just follow the example in the book "OpenCV with Python by Example" and I don't know why, or how to fix this mistake. I got this error, please help me. This is the code: import argparse import cv2 import numpy as np def build_arg_parser(): parser = argparse.ArgumentParser(description='Reconstruct the 3D map from \the two input stereo images. Output will be saved in\'output.ply\'') parser.add_argument("--image-left", dest="image_left", required=True, help="Input image captured from the left") parser.add_argument("--image-right", dest="image_right", required=True, help="Input image captured from the right") parser.add_argument("--output-file", dest="output_file", required=True, help="Output filename (without the extension) where the point cloud will be saved") return parser def create_output(vertices, colors, filename): colors = colors.reshape(-1, 3) vertices = np.hstack([vertices.reshape(-1,3), colors]) ply_header = '''ply format ascii 1.0 element vertex %(vert_num)d property float x property float y property float z property uchar red property uchar green property uchar blue end_header ''' with open(filename, 'w') as f: f.write(ply_header % dict(vert_num=len(vertices))) np.savetxt(f, vertices, '%f %f %f %d %d %d') if __name__ == '__main__': args = build_arg_parser().parse_args() image_left = cv2.imread(args.image_left) image_right = cv2.imread(args.image_right) output_file = args.output_file + '.ply' if image_left.shape[0] != image_right.shape[0] or \ image_left.shape[1] != image_right.shape[1]: raise TypeError("Input images must be of the same size") # downscale images for faster processing image_left = cv2.pyrDown(image_left) image_right = cv2.pyrDown(image_right) # disparity range is tuned for 'aloe' image pair win_size = 1 min_disp = 16 max_disp = min_disp * 9 num_disp = max_disp - min_disp# Needs to be divisible by 16 stereo = cv2.StereoSGBM(minDisparity = min_disp, numDisparities = …

http://stackoverflow.com/comment/85625093
comment on: http://stackoverflow.com/q/49303554
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/a/33522724/5008845

http://stackoverflow.com/comment/85845504
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49422041
has text: Can you provide a minimum required code sample to reproduce the issue? Cause for now you pasted only 4 methods extracted from some class(es) and the traceback from IPython without. The error message is clear and to fix it you need to store value of `a` somewhere else than just a local variable in `OnImport2()` method. Possibly using `self.a` but to decide on the proper place we need more background. See https://stackoverflow.com/help/mcve

http://stackoverflow.com/q/49366928
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/85735560
favorite count: 0
has comment: http://stackoverflow.com/comment/85734725
has comment: http://stackoverflow.com/comment/85736404
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85734652
has body: Not a complicate question but I couldn't find an explicit answer around. For example, if I want to find out the number of prime numbers in a list of numbers: def count_prime(lst): """lst is a list of integers""" def isPrime(n): return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n &gt; 1 else False result = 0 for num in lst: if isPrime(num): result += 1 return result This looks very simple, but I put isPrime(n) inside of the main function. How does it compare to: def isPrime(n): return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n &gt; 1 else False def count_prime(lst): """lst is a list of integers""" result = 0 for num in lst: if isPrime(num): result += 1 return result My question is: Does it make any difference? Which one is preferred?
has comment: http://stackoverflow.com/comment/85735416
linked to: http://stackoverflow.com/q/1589058
accepted answer: http://stackoverflow.com/a/49367112
tagged with: nested-function
has title: Sould I write a function inside of a function or write them all in the global frame?
has comment: http://stackoverflow.com/comment/85738204
upvote count: 4
has comment: http://stackoverflow.com/comment/85736575
has comment: http://stackoverflow.com/comment/85735593
type: Question
has comment: http://stackoverflow.com/comment/85735556
has comment: http://stackoverflow.com/comment/85738138
has comment: http://stackoverflow.com/comment/85738906
has comment: http://stackoverflow.com/comment/85738796
has comment: http://stackoverflow.com/comment/85735687
duplicate of: http://stackoverflow.com/q/1589058
tagged with: function
has comment: http://stackoverflow.com/comment/85735908
has comment: http://stackoverflow.com/comment/85735713
has comment: http://stackoverflow.com/comment/85738961
answer count: 1
has comment: http://stackoverflow.com/comment/85735831
has answer: http://stackoverflow.com/a/49367112

http://stackoverflow.com/q/49307001
tagged with: pandas
has body: Given the following DataFrame how can I retrieve only the values where IS_TESTED has both True and False values. d = pd.DataFrame({"ID":[700,700,701,702,702,703],"IS_TESTED":[True,False,True,False,True,True],"TEST_NAME":["A","B","A","A","B","A"]}) In the following example, my desired result should be: 700 True A 700 False B 702 False A 702 True B since 701 &amp; 703 occurs only once.
tagged with: dataframe
has title: Select Data Frame result based on row occurrences
possible better answer: http://stackoverflow.com/a/49307154
type: Question
has answer: http://stackoverflow.com/a/49307154
answer count: 2
accepted answer: http://stackoverflow.com/a/49307082
upvote count: 2
has answer: http://stackoverflow.com/a/49307082
downvote count: 0
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49372550
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/49388763
has body: I'm using Geany as my editor and when I first started using it, writing to files worked fine but somehow it randomly stopped working. The code executes without any errors but the file isn't created / is empty if already created and I've no idea why. Simple code as below doesn't work: filename = 'dogs' with open(filename, 'w') as f: f.write('tester') with open(filename, 'r') as f: contents = f.read() print(contents) The output I get from the 'read' method looks correct on the console output (it just prints 'tester'), but no file is created / edited in my directory. Geany also has a weirdly complex debugger (if anyone has any helpful guides on how to use it please let me know) so I can't debug properly. I've tried all that I know including using an absolute file path, running in admin mode. The issue is also present when I try to use Pygal to render_to_file(), which is the project I'm working on so right now I can't go any further because anything that requires writing doesn't work. FYI it reads fine.... It's like Geany doesn't have admin rights or something? EDIT: I've run this code on a python shell (without a .py file) and it worked fine, creating the file as desired. I then ran it using CMD with the .py file and it didn't work. Also ran using Pycharm, it doesn't work when I run it normal but it works when I run it in debug mode? It doesn't seem to be a Geany specific issue, but I am so confused!
tagged with: python
accepted answer: http://stackoverflow.com/a/49391024
has comment: http://stackoverflow.com/comment/85746647
has answer: http://stackoverflow.com/a/49391024
type: AnsweredQuestion
score: 0
answer count: 2
has title: Geany and other IDE not writing to file
has comment: http://stackoverflow.com/comment/85767502
tagged with: geany
tagged with: pygal
possible better answer: http://stackoverflow.com/a/49388763

http://stackoverflow.com/comment/85572662
comment on: http://stackoverflow.com/q/49284703
has text: Seems problematic because the iterator could very well affect the contents of very thing it's iterating over...so I suspect that overall this is a poor approach to whatever it is your trying to accomplish. i.e. An [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49286473
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/49286761
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/49286761
has body: I use Anaconda as the main source of python packages and also my main interpreter in PyCharm. If I want to install any package, I go to Anaconda Cloud and find it immediately something like this. Now, I want to install a package that only exists in Python Package Index here. I cannot find it in Anaconda Cloud so I don't know how to install it. Do I just need to include the package folder in the project directory in this case? Thank you
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/29286624
tagged with: python
duplicate of: http://stackoverflow.com/q/29286624
has title: How to install a Python package that does not exist in Anaconda Cloud

http://stackoverflow.com/a/49362574
has comment: http://stackoverflow.com/comment/85726248
has body: Best option would be use try except block to catch exceptions while your rest code runs fine. Also your syntax is bit haywire. Try this: try: drop = browser.find_elements_by_css_selector('#someID').click() except: print("Menu not found")
type: Answer
has comment: http://stackoverflow.com/comment/85725716
has comment: http://stackoverflow.com/comment/85730409
has comment: http://stackoverflow.com/comment/85726205
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49362476
has comment: http://stackoverflow.com/comment/85751621
downvote count: 1

http://stackoverflow.com/q/49424277
has title: Selenium and dimension of device
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
linked to: http://stackoverflow.com/q/3401343
has comment: http://stackoverflow.com/comment/85867066
favorite count: 0
has body: I just recently incurred a lot of problem with selenium, especially with clicking the button and switch to the dialog box. The main problem is that I can run it in my own laptop the Dell E7250 with is 12.5", but when I moved it to another computer which is also Dell but 14", the button cannot be clicked and all the code seems to be useless. While it did run well in my own laptop. So I make a guess, that selenium performance will be affected by the dimension of the device, is it correct? Hi, this is my code, I can run it with the 12.5" device, but when I transferred to the Dell E7250 device, it can no longer run. My code.
has comment: http://stackoverflow.com/comment/85893790
has answer: http://stackoverflow.com/a/49424411
tagged with: python
tagged with: selenium-webdriver
type: Question
has answer: http://stackoverflow.com/a/49424556
has comment: http://stackoverflow.com/comment/85850585
answer count: 2

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/49403315
tags question: http://stackoverflow.com/q/49439339
tags question: http://stackoverflow.com/q/49320935
tags question: http://stackoverflow.com/q/49426128
type: Tag
tags question: http://stackoverflow.com/q/49371931
tags question: http://stackoverflow.com/q/49398737
tags question: http://stackoverflow.com/q/49291083
tags question: http://stackoverflow.com/q/49353954
tags question: http://stackoverflow.com/q/49379890
tags question: http://stackoverflow.com/q/49323426
tags question: http://stackoverflow.com/q/49391821
tags question: http://stackoverflow.com/q/49399686
tags question: http://stackoverflow.com/q/49336657
tags question: http://stackoverflow.com/q/49332961
tags question: http://stackoverflow.com/q/49348647
tags question: http://stackoverflow.com/q/49385843
tags question: http://stackoverflow.com/q/49342838
tags question: http://stackoverflow.com/q/49289785
tags question: http://stackoverflow.com/q/49366169
tags question: http://stackoverflow.com/q/49359266
tags question: http://stackoverflow.com/q/49309068
tags question: http://stackoverflow.com/q/49405831
tags question: http://stackoverflow.com/q/49345411
tags question: http://stackoverflow.com/q/49425947
tags question: http://stackoverflow.com/q/49294655
tags question: http://stackoverflow.com/q/49394609
tags question: http://stackoverflow.com/q/49370371
tags question: http://stackoverflow.com/q/49372083
tags question: http://stackoverflow.com/q/49421540
tags question: http://stackoverflow.com/q/49390954
tags question: http://stackoverflow.com/q/49360921
tags question: http://stackoverflow.com/q/49287747
tag name: csv
tags question: http://stackoverflow.com/q/49331751
tags question: http://stackoverflow.com/q/49350370
tags question: http://stackoverflow.com/q/49314977
tags question: http://stackoverflow.com/q/49349079
tags question: http://stackoverflow.com/q/49288597
tags question: http://stackoverflow.com/q/49312300
tags question: http://stackoverflow.com/q/49349872
tags question: http://stackoverflow.com/q/49312476
tags question: http://stackoverflow.com/q/49306430
tags question: http://stackoverflow.com/q/49422921
tags question: http://stackoverflow.com/q/49406747
tags question: http://stackoverflow.com/q/49357352
tags question: http://stackoverflow.com/q/49295890
tags question: http://stackoverflow.com/q/49342528
tags question: http://stackoverflow.com/q/49308201
tags question: http://stackoverflow.com/q/49355577
tags question: http://stackoverflow.com/q/49366352
tags question: http://stackoverflow.com/q/49318684
tags question: http://stackoverflow.com/q/49280161
tags question: http://stackoverflow.com/q/49422041
tags question: http://stackoverflow.com/q/49331624
tags question: http://stackoverflow.com/q/49411182
tags question: http://stackoverflow.com/q/49283979
tags question: http://stackoverflow.com/q/49324426
tags question: http://stackoverflow.com/q/49304932
tags question: http://stackoverflow.com/q/49338248
tags question: http://stackoverflow.com/q/49377576
tags question: http://stackoverflow.com/q/49433165
tags question: http://stackoverflow.com/q/49420730
tags question: http://stackoverflow.com/q/49350510
tags question: http://stackoverflow.com/q/49371868
tags question: http://stackoverflow.com/q/49346405
tags question: http://stackoverflow.com/q/49395838
tags question: http://stackoverflow.com/q/49355984
tags question: http://stackoverflow.com/q/49306352
tags question: http://stackoverflow.com/q/49329326
tags question: http://stackoverflow.com/q/49376339
tags question: http://stackoverflow.com/q/49372868
tags question: http://stackoverflow.com/q/49308464
tags question: http://stackoverflow.com/q/49320362
tags question: http://stackoverflow.com/q/49405766
tags question: http://stackoverflow.com/q/49411783
tags question: http://stackoverflow.com/q/49312914
tags question: http://stackoverflow.com/q/49326081
tags question: http://stackoverflow.com/q/49352303
tags question: http://stackoverflow.com/q/49374080

http://stackoverflow.com/comment/85761560
has text: You can also try: `16.02-0.01 == 16.009999999999998`
comment on: http://stackoverflow.com/q/49380267
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85802584
score: 0
comment on: http://stackoverflow.com/q/49400498
type: QuestionComment
has text: Also, "I was thinking about multithreading or multiprocessing but i don't know how to use it" means you should read a tutorial on it, not ask someone to basically write a new tutorial that won't be as good because it's off the top of their head and has to fit into an SO answer. For multiprocessing (and concurrent.futures), the stdlib docs actually have enough good examples that they might serve as their own tutorial; for threading, not so much.
type: Comment

http://stackoverflow.com/comment/85812127
type: Comment
comment on: http://stackoverflow.com/q/49405240
type: QuestionComment
score: 0
has text: Note: possibly you can use `is` instead `==` to check if it is the same object. Because objects can be shared, is not definitive, but it rules out the case with same value, but different object.

http://stackoverflow.com/comment/85636035
score: 0
comment on: http://stackoverflow.com/q/49316810
has text: @brunodesthuilliers my mistake edited the code indentation
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49428449
answer count: 1
linked to: http://stackoverflow.com/q/48178284
type: Question
has title: Spawning of multiple enemies randomly in Pygame
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85884593
tagged with: python
tagged with: pygame
tagged with: class
score: 0
has answer: http://stackoverflow.com/a/49442410
has body: Basically I am coding a programming project for my school at the moment, I was originally using a modular form of coding however it became apparent that OOP would be a more efficient way to code. I've been following some youtube tutorials as I am not that confident with OOP and seem to have hit a brick wall. I am currently struggling with spawning multiple enemies from my enemy class and also in random locations on the screen. I thought maybe ill have to create a list to append the enemies to and go from there but everything I have tried over the past few days has not worked! Thanks in advance for helping me with this issue and I will paste the code below. import tkinter as tk import pygame import time import random def shutdown(): root.destroy() #Beginning of the game code for mainmenu link def Begin(): pygame.init() #display size display_width = 640 display_height = 750 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption ("Spellmaster") #Images for wizard sprite wizard_right = [pygame.image.load('right_1.png'), pygame.image.load('right_3.png'), pygame.image.load('right_2.png'), pygame.image.load('right_4.png'), pygame.image.load('right_5.png')] wizard_left = [pygame.image.load('left_1.png'), pygame.image.load('left_3.png'), pygame.image.load('left_2.png'), pygame.image.load('left_4.png'), pygame.image.load('left_5.png')] still = pygame.image.load("wizardsprite.png") background = pygame.image.load("background.png") clock = pygame.time.Clock() score = 0 class player(object): def __init__ (self,x,y,width,height): self.x = x self.y = y self.width = width self.height = height self.vel = 4 self.steps= 0 self.left = False self.right = False self.hitbox = (self.x + 20, self.y, 50, 60) #blit the character on screen def draw(self,gameDisplay): if self.steps + 1 &gt;=27: self.steps = 0 if self.left: gameDisplay.blit(wizard_left [self.steps//20], (self.x,self.y)) self.steps +=1 elif self.right: gameDisplay.blit(wizard_right [self.s…

http://stackoverflow.com/q/49377085
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: apache-spark-sql
type: UnansweredQuestion
tagged with: arrays
tagged with: pyspark
tagged with: python
has body: I have a dataframe df as below: +---+--------+----+ | Id| Size| Amt| +---+--------+----+ | a1| 1|55.0| | a2| 2|48.0| | a3| 3|28.0| +---+--------+----+ The schema of this dataframe is: StructType([ StructField("Id", StringType(), True), StructField("Size", IntegerType(), True), StructField("Amt", FloatType(), True) ]) When I use df.write.json("my_output_path"), the json file looks like: {"Id":"a1", "Size":1, "Amt":55.0} {"Id":"a2", "Size":2, "Amt":48.0} {"Id":"a3", "Size":3, "Amt":28.0} Using df, I want to create df1 such that it has a new array column (Arr) which contains key value pairs of the existing columns. The output file of df1.write.json("my_new_output_path") should look like something below: {"Id":"a1", "Size":1, "Amt":55.0, "Arr":[{"Id":"a1","Size":1,"Amt":55.0 }] } {"Id":"a2", "Size":2, "Amt":48.0, "Arr":[{"Id":"a2","Size":2,"Amt":48.0 }] } {"Id":"a3", "Size":3, "Amt":28.0, "Arr":[{"Id":"a3","Size":3,"Amt":28.0 }] } I tried the following but it gave me a different output: df1 = df.select('Id', 'Size', 'Amt', array('Id','Size','Amt').alias("Arr")) df1.write.json("my_new_output_path") Current Output: {"Id":"a1", "Size":1, "Amt":55.0, "Arr":["a1", 1 ,55.0] } {"Id":"a2", "Size":2, "Amt":48.0, "Arr":["a2", 2 ,48.0] } {"Id":"a3", "Size":3, "Amt":28.0, "Arr":["a3", 3 ,28.0] } How can I get the expected output? Any solutions or pointers would be appreciated.
has title: Create an array column of key value pairs
tagged with: apache-spark
has answer: http://stackoverflow.com/a/49377260
answer count: 1

django-users
tags question: http://stackoverflow.com/q/49346893
tags question: http://stackoverflow.com/q/49332285
type: Tag
tag name: django-users

http://stackoverflow.com/comment/93237775
type: QuestionComment
comment on: http://stackoverflow.com/q/49370077
has text: Did you get any further on this? Tried the same with the same result ;-)
score: 0
type: Comment

http://stackoverflow.com/a/49371276
has body: Replace: for row in rows: cb.insert(END, row) with: cache = list() for row in rows: cache.append(row) cb['values'] = cache Since ttk.Combobox, in fact, inherits from tk.Entry the insert method makes you populate the 'entry part' of the widget, so it's not what you think it is, or the data you're getting are not what you think they are.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49371033
answers question: http://stackoverflow.com/q/49371033
score: 0
type: Answer

http://stackoverflow.com/comment/85623521
type: Comment
type: QuestionComment
has text: The most recent version is 2.1. [Documentation](https://networkx.github.io/documentation/networkx-2.1/reference/algorithms/generated/networkx.algorithms.shortest_paths.unweighted.all_pairs_shortest_path.html?highlight=all_pairs_shortest_path#networkx-algorithms-shortest-paths-unweighted-all-pairs-shortest-path) for `all_pairs_shortest_path` changed since 1.9
score: 0
comment on: http://stackoverflow.com/q/49309670

http://stackoverflow.com/comment/85660759
type: AnswerComment
score: 1
has text: Excellent and learned something new (.copy, .agg)
comment on: http://stackoverflow.com/a/49329249
type: Comment

http://stackoverflow.com/a/49343001
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49342926
has comment: http://stackoverflow.com/comment/85686224
has comment: http://stackoverflow.com/comment/85686232
type: Answer
has body: Vigorous testing using the following program shows that the function works just fine: import random, string def random_string(chars=string.ascii_letters + string.digits): size = random.randrange(10, 15) return str(''.join(random.choice(chars) for _ in range(size))) for i in range(10000): x = random_string() if not (10 &lt;= len(x) &lt;= 15): #Check that the length of the #generated string is within range print("Failed: len={0}".format(len(x))) print("Tests completed")
score: 0
accepted answer of: http://stackoverflow.com/q/49342926

http://stackoverflow.com/comment/85727249
type: AnswerComment
comment on: http://stackoverflow.com/a/49361075
score: 0
type: Comment
has text: Do you have any other file named "textblob.py". Because that is a core file of textblob module.

http://stackoverflow.com/a/49473375
answers question: http://stackoverflow.com/q/49397209
score: 0
has body: I just want to clarify the conversations between @Allen and me. Session still exist after as_default. import tensorflow as tf import numpy as np with tf.Graph().as_default(): const = tf.constant(3.) sess = tf.Session() with sess.as_default(): print(sess.run(const)) print(sess.run(const)) sess.close() print(sess.run(const)) You can find the result: 3.0 3.0 ------------------------------------------------------------- RuntimeError Traceback (most recent call last) ... ... RuntimeError: Attempted to use a closed Session. And you can repeat the bug through the following snippet: import tensorflow as tf import numpy as np with tf.Graph().as_default(): const = tf.constant(3.) with tf.Session() as sess: print("No sess run within with block.") print(sess.run(const)) sess.close() print(sess.run(const)) And the corresponding result is: No sess run within with block. 3.0 ------------------------------------------------------------- RuntimeError Traceback (most recent call last) ... ... RuntimeError: Attempted to use a closed Session.
type: Answer

http://stackoverflow.com/q/49404599
has title: Python Flask render_template not rendering correctly
has answer: http://stackoverflow.com/a/49405133
has comment: http://stackoverflow.com/comment/85831661
answer count: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: flask
tagged with: jinja2
has body: When someone logs out of my page I want to add a paragraph to HTML with Jinja saying they have successfully logged out. It works up to the point where I actually return render_template. @app.route('/logout',methods=['POST']) def logout(): session['logged_in'] = False message = "You have successfully logged out" return redirect(url_for('index_page',message=message)) @app.route('/', methods=['POST','GET']) def index_page(): try: session['logged_in'] message = request.args['message'] return render_template('index.html',message=message) except: session['logged_in'] = False return render_template('index.html') When I print message in index_page after logging out, it correctly prints out "You have successfully logged out" and even if I print render_template('index.html',message=message) it gives a correct HTML with the message where it should be. But it doesn't actually render the page correctly on the screen, as if message was undefined. If I define message withing index_page directly (message = "You have successfully logged out"), it renders correctly. EDIT: Thanks, I tried doing that. However, the issue is everything works fine just before rendering. Consider this code I did: @app.route('/', methods=['POST','GET']) def index_page(): try: print("Checkpoint 1") message = request.args['message'] print("Checkpoint 2") except: print("Checkpoint 3") message = "Other message" print("Checkpoint 4",message) #print("Checkpoint 5",render_template('index.html',message=message)) return render_template('index.html',message=message) So, when I just refresh the page (pass no message) my console output is something like: Checkpoint 1 Checkpoint 3 Checkpoint 4 "Other message" "GET / HTTP/1.1" 200 - And I get the page saying "Other message" However, if I pass a message by calling logout first, I get something like: Checkpoint 1 Checkpoint 2 Checkpoint 4 "You have successfully logged out" "GET /?message=You+have+successfully+logged+out HTTP/1.1" 200 - And I still get the page saying "Othe…

http://stackoverflow.com/comment/85604617
type: QuestionComment
comment on: http://stackoverflow.com/q/49299079
score: 0
type: Comment
has text: can you provide more informations? I guess you are missing transform line

http://stackoverflow.com/comment/85652605
type: AnswerComment
type: Comment
has text: wondering is it possible to also apply `Timedelta.days` to the one liner code, so i don't have to `df['E'].apply(lambda x: x.days)` later on?
comment on: http://stackoverflow.com/a/49325042
score: 0

http://stackoverflow.com/a/49430800
score: 0
answers question: http://stackoverflow.com/q/49429709
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49429709
type: Answer
has body: Spark doesn't handle multiple line data very well. The Example code you linked to shows how to need to lay out the file in the examples folder. Single objects on multiple lines. Not one object with an array {'age': '54', 'firstName': 'Peter1', 'lastName': 'Jones1'} {'age': '44', 'firstName': 'Peter2', 'lastName': 'Jones2'} {'age': '42', 'firstName': 'Peter3', 'lastName': 'Jones3'} Also, JSON uses double quotes for keys and values, so you'll need to fix that Then df = spark.read().json("file.json") And, to find the max age df.groupBy().max("age").show()

http://stackoverflow.com/comment/85795452
comment on: http://stackoverflow.com/a/49289636
type: AnswerComment
has text: The line of : question1 = q.get('question1')
score: 0
type: Comment

http://stackoverflow.com/comment/85822493
type: AnswerComment
has text: Glad to be helpful!
comment on: http://stackoverflow.com/a/49382743
score: 0
type: Comment

http://stackoverflow.com/q/49368975
type: Question
tagged with: class
tagged with: object
has comment: http://stackoverflow.com/comment/85738966
has answer: http://stackoverflow.com/a/49369035
linked to: http://stackoverflow.com/q/4794244
tagged with: python
duplicate of: http://stackoverflow.com/q/4794244
favorite count: 0
has body: I have the following concern in Python: a = 1 b = a b = 2 print(a) From what I understand, b is a new variable that uses the value of a. Thus, when the value of b is changed, that does not affect a. So, print(a) should yield 1. class Object: def __init__(self): self.value = 0 a = Object() a.value = 1 b = a b.value = 2 print(a.value) However, in this instance, a would print 2. Why is this? How do I make it so that a.value will still be 1 instead of 2?
upvote count: 0
has comment: http://stackoverflow.com/comment/85738992
downvote count: 2
tagged with: instance
type: UnansweredQuestion
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/85738970
has title: Instance of attributes in an Object

http://stackoverflow.com/a/49428892
has comment: http://stackoverflow.com/comment/85920525
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49428050
has body: I am not aware of a way to overload the plot function in matplotlib. However, you can create a new function which emulates the matplotlib plot function. def plot(x=None, y=None, *args, axis=None, **kwargs): """Creates a plot from iterable, works with magnitude instances. All keyword arguments in matplotlib functions are accepted, but `linewidth` should not be used if y contains magnitude instances. Parameters ---------- x : Array like The x positions of the plot [pomts. If y is not given, y is set to x and x is set to range(len(y)). y : Array like The y positions of the plot points. axis : matplotlib.Axes (optional) Axes to plot the values in. """ if axis is None: axis = plt if y is None: y = x x = range(len(y)) if isinstance(y[0], magnitude): for yi in y: if not isinstance(y[i]), magnitude): raise ValueError( 'Either all or none of the plot positions should ' 'be magnitude instances' ) y_val = [yi.val for yi in y] y_err = [yi.err for yi in y] lines = axis.plot(x, y_val, *args, linewidth=2.0, **kwargs) lines += axis.plot(x, y_val + y_err, *args, **kwargs) lines += axis.plot(x, y_val - y_err, *args, **kwargs) else: lines = axis.plot(x, y, *args, **kwargs) return lines Lastly, I would recommend using fill between for the error lines instead of a thick and two thin lines.
downvote count: 0
has comment: http://stackoverflow.com/comment/85920566
upvote count: 1

http://stackoverflow.com/comment/85827244
has text: For anyone stumbling across this: I can't testify to the use of `Manager`s - because I opted to use `Pipe`s instead - but the bit about the pool duplication between process led me to my solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/49394093
score: 0
type: Comment

http://stackoverflow.com/comment/85627510
comment on: http://stackoverflow.com/q/49312838
score: 0
type: Comment
type: QuestionComment
has text: What you want is set. I don't know how to do it in pandas

http://stackoverflow.com/a/49301441
accepted answer of: http://stackoverflow.com/q/49300970
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49300970
has body: If you don't want to use pandas, you can write your own group_by function: from collections import defaultdict def group_by(dicts, key): out = defaultdict(list) for d in dicts: out[d[key]].append(d) return out def combine_receipts(receipts): for receipt_id, receipts in group_by(receipts, 'receipt_id').items(): if len(receipts) &gt; 1: service = ' '.join(f"{r['service']} {r['charge']}" for r in receipts) charge = str(sum(float(r['charge']) for r in receipts)) yield {'receipt_id': receipt_id, 'service': service, 'charge': charge, 'company': receipts[0]['company']} elif len(receipts) == 1: yield receipts[0] else: raise RuntimeError("empty group") if __name__ == "__main__": receipts = [{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'}, {'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'}, {'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}] print(list(combine_receipts(receipts))) # [{'receipt_id': '1', 'service': 'A 2000 B 3000', 'charge': '5000.0', 'company': 'Company A'}, # {'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]

http://stackoverflow.com/comment/85678602
type: QuestionComment
comment on: http://stackoverflow.com/q/49336474
score: 0
has text: Are you saying the solution from the linked question does not solve your issue?
type: Comment

http://stackoverflow.com/q/49401544
has answer: http://stackoverflow.com/a/49401582
downvote count: 0
answer count: 1
score: 1
has title: Pandas not returning values in same row on conditional
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49401582
upvote count: 1
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has body: Let's say I create a simple dataframe and I add on some columns import pandas as pd data = { 'price': [6, 5.5, 5, 4.8], 'amount': [10, 12, 8, 6] } df = pd.DataFrame(data=data) df['total'] = df.price * df.amount df['running_total'] = df.total.cumsum().round(2) my dataframe now looks like this: amount price total running_total 0 10 6.0 60.0 60.0 1 12 5.5 66.0 126.0 2 8 5.0 40.0 166.0 3 6 4.8 28.8 194.8 I want the row from the dataframe with running total just under 160: row_under_160 = df[df['running_total'] &lt; 160].max() This row (series) looks like this: amount 12.0 price 6.0 total 66.0 running_total 126.0 dtype: float64 All the values look good EXCEPT PRICE. For some reason it's returning the top price (6.0) when it should return 5.5 which is the corresponding value. Am I missing something/doing this entirely wrong?
tagged with: pandas

http://stackoverflow.com/comment/85692324
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49346154
has text: Also, you talk about distinguishing normal generators from generator-based coroutines. Do you mean you want to distinguish 3.4-style-`asyncio` generators using `yield from` from normal generators using `yield from`?

http://stackoverflow.com/comment/85688041
type: AnswerComment
has text: It works with piping. I tried with `curl -s 'https://www.sunwind.no/Outlet/' | html2text | grep __` and found that grep can handle the output from html2txt. I think you are correct about terminal can support the encoding by html2txt. I also think the pipe is just stream of bytes. And programs in pipe need to have same understanding (encoding/decoding method) about the byte stream.
comment on: http://stackoverflow.com/a/49338501
type: Comment
score: 0

http://stackoverflow.com/comment/86074455
has text: I haven't this problem before, now i can not put any element in the index.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49526918

http://stackoverflow.com/comment/85626626
type: QuestionComment
has text: Possible duplicate of [Pythonic way to find maximum value and its index in a list?](https://stackoverflow.com/questions/6193498/pythonic-way-to-find-maximum-value-and-its-index-in-a-list)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49312403

http://stackoverflow.com/a/49398702
has comment: http://stackoverflow.com/comment/85845680
has comment: http://stackoverflow.com/comment/85845757
has comment: http://stackoverflow.com/comment/85846379
has comment: http://stackoverflow.com/comment/85805578
answers question: http://stackoverflow.com/q/49396106
has comment: http://stackoverflow.com/comment/85868938
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49396106
has comment: http://stackoverflow.com/comment/85845916
has comment: http://stackoverflow.com/comment/85824024
has comment: http://stackoverflow.com/comment/85823824
has body: Using requests Open Developer tools > Network > XHR tab in your browser. Then, click on the Site/Facility Docs tab. You'll see an AJAX request in the XHR tab. The request is sent to this site to get the tab data. You can scrape anything you want from that tab by simply using requests module. import requests r = requests.get('http://www.envirostor.dtsc.ca.gov/public/profile_report_include?global_id=01290021&ou_id=&site_id=&tabname=sitefacdocs&orderby=&schorderby=&comporderby=&rand=0.07839738919075079&_=1521609095041') soup = BeautifulSoup(r.text, 'lxml') # And to check whether we've got the correct data: table = soup.find('table', class_='display-v4-default') print(table.find('a', target='_documents').text) # Soil Management Plan Implementation Report, Public Market Infrastructure Relocation, Phase 1-B Infrastructure Area Using Selenium When you want to wait for a page to load, you should never use time.sleep(). You should use Eplicit Waits instead. After using that, you can get the whole tab content using the .get_attribute('innerHTML') property. 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 driver = webdriver.Chrome() driver.get('http://www.envirostor.dtsc.ca.gov/public/profile_report?global_id=01290021&starttab=landuserestrictions') driver.find_element_by_id('sitefacdocsTab').click() wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.ID, 'docdatediv'))) html = driver.find_element_by_id('sitefacdocs').get_attribute('innerHTML') soup = BeautifulSoup(html, 'lxml') table = soup.find('table', class_='display-v4-default') print(table.find('a', target='_documents').text) # Soil Management Plan Implementation Report, Public Market Infrastructure Relocation, Phase 1-B Infrastructure Area Additional info: The element with id="docdatediv" is the div tag that contains date range filter. I've used it a…
score: 1
has comment: http://stackoverflow.com/comment/85823615
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49411406
has comment: http://stackoverflow.com/comment/85834920
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: I need to make a function which randomly chooses a key from a dictionary. I'm not quite sure how to do that! Help?
score: 0
tagged with: random
answer count: 0
tagged with: function
linked to: http://stackoverflow.com/q/4859292
tagged with: key
has comment: http://stackoverflow.com/comment/85824573
has comment: http://stackoverflow.com/comment/85824581
type: Question
has comment: http://stackoverflow.com/comment/85834897
has title: How to make a function randomly choose a key in a dictionary?
duplicate of: http://stackoverflow.com/q/4859292
has comment: http://stackoverflow.com/comment/85824628

http://stackoverflow.com/q/49302984
accepted answer: http://stackoverflow.com/a/49303049
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has body: I'm trying to get the values from highest to lowest which is pretty straightforward using the code but this is what I'm receiving when I do: Input: s.sort_values(by('1617 Entries &amp; Exits), ascending = True) Output: 1617 Entries &amp; Exits Station Name 2559 NaN Manchester United Football Ground 2558 NaN Heathrow Terminals 2 &amp; 3 2557 NaN Heathrow Terminal 5 2556 NaN Heathrow Terminal 4 1285 998,316 King's Lynn 1230 997,912 Irvine 915 996 Gainsborough Central 641 994 Cynghordy 1697 990,438 Ockendon 1540 99,704 Metheringham 847 99,610 Falmouth Docks 1294 99,484 Kintbury 2378 99,403,096 Waterloo 1642 99,394 Newcourt 34 99,380 Albrighton 2196 99,042 Summerston 2392 989,728 Wellingborough 1048 984,504 Hampton Wick 1677 984,332 North Wembley 2302 983,704 Trowbridge 1876 982,934 Rectory Road 296 982,592 Bootle New Strand 94 98,472 Ashburys 1282 98,290 Kinghorn 1474 98,234 Lytham 970 98,218 Gorebridge 1220 98,140 Insch 1978 979,098 Scarborough 494 978,986 Cheam 928 974 Garth (Powys) I was expecting it to return the highest number in that column '1617 Entries &amp; Exits' which is actually 99,039,875 and ascend from there but it isn't happening. Do I need to remove the missing values (NaN) first or change the data type of the column first? The data type for that column is a series by the way: pandas.core.series.Series
has title: Sorting values in a pandas column with type string
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49303049
score: 1
type: Question

http://stackoverflow.com/q/49335307
tagged with: utf-8
has comment: http://stackoverflow.com/comment/85672852
type: Question
tagged with: python-3.x
tagged with: encoding
has comment: http://stackoverflow.com/comment/85673345
answer count: 0
has body: I was trying to count the number of words in a text file using python. To remove punctuations I used: word = word.replace("“","") My code gave different result when I used: word = word.replace("\"","") Previously, I was having some encoding related problems while opening the text file, the statement I used was: file = open('98-0.txt') Error code: 'charmap' codec can't decode byte 0x9d in position 6552: character maps to &lt;undefined&gt; So I used the following statement: file = open('98-0.txt',encoding="utf-8-sig") I am using Anaconda 1.6.5, python 3.6.3 on Windows 8.
has comment: http://stackoverflow.com/comment/85673401
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85673895
has comment: http://stackoverflow.com/comment/85673077
tagged with: python
has comment: http://stackoverflow.com/comment/85673478
has comment: http://stackoverflow.com/comment/85672179
has title: Getting different results in python while using “ (U+201C) instead of " (Quotation mark typed from keyboard) in replace()
score: 0

http://stackoverflow.com/q/49390954
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85783620
has comment: http://stackoverflow.com/comment/85789129
has body: I need to compare two csv files and add a new column on df_g with the Price column of df. I suppose I need to read line for line of the 2 csv but I don't know how I can do it so I try with it: df = pd.read_csv('test2.csv') df_g = pd.read_csv('test_hecho.csv') if (df_g['Sitio'] == df['Sitio'] and df_g['Country'] == df['Country']): df_g['Bidfloor'] = df['Price'] df_g.to_csv('aaa.csv') A possible answer is: df_g['Bidfloor'] = df_g'Sitio','Country'.merge(df,how='left').Pricebut I need to change the =to = or part of. Is it possible??
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85834216
has title: Compare 2 csv with python and add a new Column
has comment: http://stackoverflow.com/comment/85784485
has comment: http://stackoverflow.com/comment/85784307
has comment: http://stackoverflow.com/comment/85786399
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85784005
tagged with: pandas
has comment: http://stackoverflow.com/comment/85783968

http://stackoverflow.com/q/49306083
tagged with: spacy
type: AnsweredQuestion
score: 1
tagged with: nlp
tagged with: named-entity-recognition
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49307026
answer count: 1
has comment: http://stackoverflow.com/comment/85614375
has body: I'm working with SpaCy in order to extract the different named entities from a sample text. The problem is that SpaCy doesn't recognize all the expected entities. It has problems with money and some locations. This is my code: # encoding: utf-8 import spacy from spacy import displacy nlp = spacy.load('es') #cargo el modelo en español. text = u"Una vez un personaje le preguntó a Agustín Chirichigno si estaba en su casa. El nombre de este personaje es Lucas Picchi y es de Mar del Plata. Junto a SU PRIMO, DE ESTADOS UNIDOS hacen cosas re locas como por ejemplo comprar un Fernet Branca a AR$2.500 cuando en realidad está a $180." doc = nlp(text) displacy.serve(doc, style='ent') Note that I'm loading a spanish model. My configuration is as follows: spacy info Info about spaCy Python version 2.7.6 Platform Linux-4.4.0-112-generic-x86_64-with-Ubuntu-14.04-trusty spaCy version 2.0.9 Location /usr/local/lib/python2.7/dist-packages/spacy Models es, en So, the output is: What is expected is that SpaCy recognize MONEY correctly (AR$2500 is 2500 argentinian pesos and $180 is money too). The word "Junto" is not a LOCATION and neither "SU PRIMO". "Junto a su primo" would be like "with his cousin" in english. Also, Fernet Branca is a BRAND, and not a person. So, my question is: what am I doing wrong? Should I use additional libraries? Thanks in advance.
has answer: http://stackoverflow.com/a/49307026
has title: SpaCy doesn't recognize money and countries as expected
has comment: http://stackoverflow.com/comment/85614436

http://stackoverflow.com/comment/85685424
comment on: http://stackoverflow.com/a/49342359
score: 0
type: AnswerComment
has text: @Fackelmann if the algorithm doesn't change your training score, then your different results come from the normalization. It is possible that without your pre-processing, your algorithm (regardless the cost function) gets stuck into a local minimum (close to the global). For example scaling your data in Neural network algorithm normally leads to better results
type: Comment

http://stackoverflow.com/a/49433660
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49433555
accepted answer of: http://stackoverflow.com/q/49433555
score: 3
type: Answer
has body: You can using duplicated df[~df.iloc[:,:-1].duplicated()] Out[53]: 0 1 2 3 4 5 6 0 0 12 1 99 23 2 75 2 5 12 1 99 23 2 66

http://stackoverflow.com/a/49373575
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85748465
has comment: http://stackoverflow.com/comment/85748775
accepted answer of: http://stackoverflow.com/q/49373453
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85748950
has comment: http://stackoverflow.com/comment/85748923
has body: You could try from pyspark.sql.functions import split df_temp = df.withColumn("dim1", split("dim", "x")[0]) df_new = df_temp.withColumn("dim2", split("dim", "x")[1]) df_new.show() Or you can chain these together in one call: df_new = df.withColumn("dim1", split("dim", "x")[0])\ .withColumn("dim2", split("dim", "x")[1])
type: Answer
has comment: http://stackoverflow.com/comment/85749012
answers question: http://stackoverflow.com/q/49373453
has comment: http://stackoverflow.com/comment/85748802

http://stackoverflow.com/comment/85649193
has text: I changed my script to use chromedriver and it still isn't working. Please see updated post.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49322582

http://stackoverflow.com/q/49284933
tagged with: python
has comment: http://stackoverflow.com/comment/85572780
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85572810
has comment: http://stackoverflow.com/comment/85643474
has comment: http://stackoverflow.com/comment/85572822
tagged with: parameter-expansion
tagged with: exe
has body: I'm trying to call an application and pass a text file as a parameter. The text file has instructions. I tried passing a parameter when opening notepad but couldn't get it to work. Here is the code I'm trying: import os os.startfile(r"C:\Windows\notepad.exe c:\cobra\advancecalendar.txt") If I don't include the path to the second file it launches notepad, but with the file name included i get the following error: RESTART: C:/Users/timbo/AppData/Local/Programs/Python/Python36-32/Open exe module.py Traceback (most recent call last): File "C:/Users/timbo/AppData/Local/Programs/Python/Python36-32/Open exe module.py", line 3, in &lt;module&gt; os.startfile(r"C:\Windows\notepad.exe c:\cobra\advancecalendar.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Windows\\notepad.exe c:\\cobra\\advancecalendar.txt' How can I pass a parameter to the startfile so it opens a specific file? when I tried putting both in quotes it still got an error.
score: -1
type: Question
linked to: http://stackoverflow.com/q/15928956
upvote count: 0
type: UnansweredQuestion
has title: launch an exe with parameter from python
answer count: 1
has answer: http://stackoverflow.com/a/49285011

http://stackoverflow.com/comment/85796436
score: 0
type: AnswerComment
has text: Are the `NaN` values being read in as actual null values recognized by python, or just the string `'NaN'`? Check the type with `df.dtypes`. Otherwise perhaps there's extra empty which space in the Title variables, so that they are actually ' Mr.' which will not match with 'Mr.'. You can see what they actually are by just selecting the column and index of individual elements with `df.loc[1,'Age']` or whatever index and column you want.
type: Comment
comment on: http://stackoverflow.com/a/49376307

http://stackoverflow.com/comment/85778194
type: Comment
score: 0
type: AnswerComment
has text: This looks correct except that it needs to include the "outer" time periods that aren't included in the sample data. That is, this doesn't cover the entire 24-hour day.
comment on: http://stackoverflow.com/a/49388157

http://stackoverflow.com/comment/85783404
type: QuestionComment
comment on: http://stackoverflow.com/q/49390354
has text: Technically, VC++ 14.0 is Microsoft Visual Studio 2015. Also, try to invoke pip from "Developer Command Prompt for VS 2017"
type: Comment
score: 0

http://stackoverflow.com/q/49400465
favorite count: 0
type: Question
has title: Cufflinks how to use connectgaps
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49706272
downvote count: 0
has body: In python plotly you can use connectgaps = true in case there are datapoints missing. Plotly will plot lines between them. My question is how does that work with cufflinks. It is based on plotly so I would assume that it should work as well. Does someone has an example how missing data is connected in a graph with cufflinks? So this is not working for me: df.iplot(kind=‘line’, connectgaps = True) Thanks! Amir
tagged with: python
has answer: http://stackoverflow.com/a/49706272
type: AnsweredQuestion
tagged with: plotly
score: 1
answer count: 1
upvote count: 1

http://stackoverflow.com/a/49282925
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85569386
accepted answer of: http://stackoverflow.com/q/49282799
downvote count: 0
has comment: http://stackoverflow.com/comment/85569210
has comment: http://stackoverflow.com/comment/85568834
answers question: http://stackoverflow.com/q/49282799
has comment: http://stackoverflow.com/comment/85569606
score: 20
upvote count: 20
has body: From PEP-238, which introduced the new division (emphasis mine): Semantics of Floor Division Floor division will be implemented in all the Python numeric types, and will have the semantics of: a // b == floor(a/b) except that the result type will be the common type into which a and b are coerced before the operation. Specifically, if a and b are of the same type, a//b will be of that type too. If the inputs are of different types, they are first coerced to a common type using the same rules used for all other arithmetic operators. In particular, if a and b are both ints or longs, the result has the same type and value as for classic division on these types (including the case of mixed input types; int//long and long//int will both return a long). For floating point inputs, the result is a float. For example: 3.5//2.0 == 1.0 For complex numbers, // raises an exception, since floor() of a complex number is not allowed. For user-defined classes and extension types, all semantics are up to the implementation of the class or type. So yes, it is supposed to behave that way. "// means integer division and should return an integer" - not quite, it means floor division and should return something equal to an integer (you'd always expect (a // b).is_integer() to be true where either operand is a float).
has comment: http://stackoverflow.com/comment/85572372

http://stackoverflow.com/comment/85644955
comment on: http://stackoverflow.com/a/49321689
score: 0
type: AnswerComment
has text: I'd be much surprised, that I can get all vars, but not vars from that file only in python. How to make it clever, is a trick i am asking for.
type: Comment

http://stackoverflow.com/comment/85660945
comment on: http://stackoverflow.com/q/49329079
score: 0
type: Comment
has text: @sam Nothing changes. [...] value = value[1] IndexError: tuple index out of range
type: QuestionComment

http://stackoverflow.com/q/49304496
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
has body: I have created a list containing 10 arrays that consist of 20 random numbers between 0 and 1 each. Now, I wish to multiply each array in the list with the numbers 0.05, 0.1, ..., to 1.0 so that none of the elements in each array is larger than the number it is multiplied with. For example, all the 20 elements in the first array should lie between 0 and 0.05, all the elements in the second array between 0 and 0.10 and so on. I create a list of 10 random arrays and a range of numbers between 0 and 1 with: range1 = np.arange(0.005, 0.105, 0.005) noise1 = [abs(np.random.uniform(0,1,20)) for i in range(10)] I then try to multiply the elements with: noise2 = [noise1 * range1 for i in noise1] But this doesn't work and just causes all the arrays in the list to have the same values. I would really appreciate some help with how to do this.
has comment: http://stackoverflow.com/comment/85611288
has comment: http://stackoverflow.com/comment/85611241
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
accepted answer: http://stackoverflow.com/a/49304957
tagged with: arrays
possible better answer: http://stackoverflow.com/a/49305525
has answer: http://stackoverflow.com/a/49304957
has title: Multiplying each array inside another list with an element from another array
upvote count: 1
has answer: http://stackoverflow.com/a/49305525
downvote count: 1
has comment: http://stackoverflow.com/comment/85611255

http://stackoverflow.com/q/49344575
has answer: http://stackoverflow.com/a/49350791
has comment: http://stackoverflow.com/comment/85696288
answer count: 1
has comment: http://stackoverflow.com/comment/85691618
upvote count: 1
has comment: http://stackoverflow.com/comment/85691651
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85691155
type: Question
has title: How kill or destroy the either root window or child window
tagged with: python
accepted answer: http://stackoverflow.com/a/49350791
has comment: http://stackoverflow.com/comment/85702603
has body: import tkinter as tk from tkinter import messagebox import xlrd as rd class Example(): def __init__(self,master): self.frameExample =tk.Frame(master,width =600,height = 200) self.frameExample.pack() self.loadButton = tk.Button(self.frameExample,text = "Load",command =self.loadFile) self.loadButton.pack() def loadFile(self): sheetWindow = tk.Toplevel() sheetFrame = tk.Frame(sheetWindow, width = 600,height = 400,bg = "alice blue") sheetFrame.pack() try: print("entered") self.workbook = rd.open_workbook("tiger.jpg") except: print("entered 1") messagebox.showinfo(title = "Load error",message = "Error") self.master.destroy() root = tk.Tk() Example(root) root.mainloop() I have tried self.masterdestroy(), not sure how to kill main window
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85689992
tagged with: tkinter

http://stackoverflow.com/comment/85690017
type: Comment
score: 0
has text: As the code is right now, if more than one client connects to the server, only the last client to connect receives the message that a change occurred (and every subsequent change message) because the thread for that client changes the state of dbMon before the other threads get a chance to notify their respective clients. I need every connected client to receive the message. It is okay if a single client misses the first or even second change message.
type: AnswerComment
comment on: http://stackoverflow.com/a/49344765

http://stackoverflow.com/a/49356803
has comment: http://stackoverflow.com/comment/85932812
type: Answer
has comment: http://stackoverflow.com/comment/85932668
accepted answer of: http://stackoverflow.com/q/49356624
has body: Creating a categorical variable will help. from pandas.api.types import CategoricalDtype colors = ['green','red'] labels=['Passed','Failed'] cat_type = CategoricalDtype(categories=labels, ordered=True) df_spark["Missing_records_check"] = df_spark["Missing_records_check"].astype(cat_type) ax_3 =df_spark["Missing_records_check"].value_counts().sort_index(ascending=True)\ .plot(kind='pie',y="Missing_records_check", figsize=(10, 10),legend=True,autopct='%1.1f%%',\ startangle=90,shadow=False,colors=['green','red']) Since you also want to remove the labels for non-existing categories, I will probably use a custom legend. I have also added a line to sort the color based on values.- import pandas as pd import matplotlib.patches as mpatches color= ['red' if l == 'Failed' else 'green' for l in df_spark['Missing_records_check']] ax_3 =df_spark["Missing_records_check"].value_counts().sort_index(ascending=False)\ .plot(kind='pie',y="Missing_records_check", figsize=(10, 10),autopct='%1.1f%%',\ startangle=90,shadow=False,colors=color, legend=True) red_patch = mpatches.Patch(color='red', label='Failed') green_patch = mpatches.Patch(color='green', label='Passed') ax_3.legend(handles=[green_patch, red_patch])
has comment: http://stackoverflow.com/comment/85755038
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85970712
has comment: http://stackoverflow.com/comment/85726834
score: 0
answers question: http://stackoverflow.com/q/49356624

http://stackoverflow.com/a/49420658
answers question: http://stackoverflow.com/q/49378741
type: Answer
score: 0
has body: Seems like the "real" limits are 250MB from this blog post: https://hackernoon.com/exploring-the-aws-lambda-deployment-limits-9a8384b0bec3 Just to quote from the article, seems like what you can do is first to upload the zip file to s3: aws s3 cp ./ s3://limits-test-foobar-bucket/ --recursive --exclude "*" --include "*.zip" And then update the lambda function using the aws cli as well: aws lambda update-function-code --function-name limits-test --region us-east-1 --s3-bucket limits-test-foobar-bucket --s3-key 100MB.zip Hope that helps!

http://stackoverflow.com/a/68376312
score: 1
upvote count: 1
has body: I got similar issue recently and finally fixed by upgrading python version in my local. I generated python-flask-server zip file from https://editor.swagger.io/. Then I set up the environment locally with py 3.6.10. I got same error when parsing input by using "Model_Name.from_dict()", telling me raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 ValueError: Invalid value for `name`, must not be `None` Then I upgraded to python 3.7.x, the issue was resolved. I know that your problem is not related to version, however, just in case anyone got similar issue and seeking for help could see this answer.
answers question: http://stackoverflow.com/q/49299808
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85875336
comment on: http://stackoverflow.com/q/49436402
type: Comment
score: 1
type: QuestionComment
has text: @cmaher thank you for the feedback. In reality the Description string will not be organized as I originally had it. I have updated to better represent reality. I will look into the link you added.

http://stackoverflow.com/comment/85582778
comment on: http://stackoverflow.com/a/49289747
type: Comment
type: AnswerComment
has text: @user3613025 It will, but you don't need numpy. See the other answers.
score: 0

http://stackoverflow.com/comment/85605490
type: AnswerComment
comment on: http://stackoverflow.com/a/49301876
score: 0
has text: He, nice one :)
type: Comment

http://stackoverflow.com/a/49287305
accepted answer of: http://stackoverflow.com/q/49287132
has body: How to make the interpreter distinguish between "\" used as a string element and "\" as the newline character ? OK, first, \ is not a newline character. \n is a newline character. And \t is a tab character. And so on. You've already found the whole list of them in some third-party docs, so I won't list them here. So, how does the interpreter* distinguish between \ meaning an actual backslash, vs. \ meaning the first character of an escape sequence? The rule is pretty simple:** It looks at the next character, and if it's a n or t or x or anything else on that list you found, then the \ is the first character of an escape sequence; otherwise, it's just a plain backslash. (There's a separate rule for raw strings, but let's not worry about that here.***) If you want to make sure you have a plain backslash: notice that \\ is an escape sequence for \. So, just escape the backslash to make sure it's a backslash instead of an escape for something else: strk = "*\\" Or, to put it in terms that don't make your head hurt: Double all your backslashes in source-code string literals. * Actually, by the time it gets to the interpreter, it's just a string constant object somewhere; it's the compiler that handles escape sequences. But that doesn't matter here. ** But it's not the same rule used by C. For example, in Python, \Q means a backslash followed by a Q, but in C, it's just the Q. Most other languages have either copied C, or just made it an error to use a backslash that isn't part of a documented escape sequence. *** For most cases of backslash-related confusion, raw strings make everything a lot easier. But for the specific case of a backslash at the very end of the string, they instead make things slightly more confusing.
downvote count: 0
answers question: http://stackoverflow.com/q/49287132
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/85582544
type: QuestionComment
has text: `pandas` has an API called the `IntervalIndex` which builds a tree and indexes in logarithmic time. You can also query the tree with many values at a time.
comment on: http://stackoverflow.com/q/49289685
score: 0
type: Comment

http://stackoverflow.com/comment/85625891
has text: @DeliriousLettuce That's not what i'm looking for
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49311922

http://stackoverflow.com/q/49300887
tagged with: placeholder
has comment: http://stackoverflow.com/comment/85603740
has body: I am working on a bit of code, where I need to convert the values in a table column to numbers, and i'm using a dictionary to keep it concise. colodesc = {'Lawn': 1, 'Unpaved': 2, 'Paved': 3, 'Unknown': 4, '': 4}#DEBUGING# cursor = arcpy.da.UpdateCursor(co_reh_sum_mem, "Cleanout_Location_Area_Description__Lawn_Unpaved_Paved_") for row in cursor: row = colodesc[row[0]] cursor.updateRow([row]) The column values will be either Lawn, Unpaved, Paved, or Unknown - but sometimes other values may have been entered into the column. I want to convert any of these to the value 4 (unknown), but it is not practical to create a key for all possible input values. Is there a way to have a "placeholder" dictionary key for any value other than those already defined? Thank you!
has title: Placeholder Value for Dictionary? (Python 2.7)
type: Question
tagged with: arcgis
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85603789
score: 0
has comment: http://stackoverflow.com/comment/85604292
answer count: 0

http://stackoverflow.com/comment/85752963
score: 0
comment on: http://stackoverflow.com/q/49375881
type: QuestionComment
type: Comment
has text: Actually, looking at the code: I wouldn't trust this scraper very far. It looks like the author just dumped his initial "works for me" version on github and then never maintained it (and may well have never used it again, once he scraped his own old WP site…). It has no error handling, is written for old versions of Python and BeautifulSoup (and requires iPython?!), and says that it only works on Apache-WP sites.

http://stackoverflow.com/comment/85701393
type: QuestionComment
score: 0
has text: @MadPhysicist, I tried to show the print statements I referred to and highlight the fact that I want to run this code in GUI. Thanks for your thoughts.
comment on: http://stackoverflow.com/q/49349388
type: Comment

http://stackoverflow.com/a/49352864
has comment: http://stackoverflow.com/comment/85712669
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49352751
downvote count: 0
score: 1
type: Answer
has body: pip list can do things like list all outdated packages. From the examples: $ pip list --outdated docutils (Current: 0.10 Latest: 0.11) Sphinx (Current: 1.2.1 Latest: 1.2.2) There's no way to do that without comparing the installed package version to the repo package version, which means pip list potentially needs to access the same data as pip install.
accepted answer of: http://stackoverflow.com/q/49352751

http://stackoverflow.com/comment/85989869
type: Comment
comment on: http://stackoverflow.com/a/49353740
type: AnswerComment
has text: I checked that and it's not :( anyway, I added an ID columns that is basically the same as the index. And now it works.
score: 0

http://stackoverflow.com/q/49388091
answer count: 2
possible better answer: http://stackoverflow.com/a/49389257
has title: Div Class Text not saving
has body: I am trying to collect prices for films on Vudu. However, when I try to pull data from the relevant div container, it returns as empty. from bs4 import BeautifulSoup url = "https://www.vudu.com/content/movies/details/title/835625" response = get(url) html_soup = BeautifulSoup(response.text, 'html.parser') type(html_soup) price_container = html_soup.find_all('div', class_ = 'row nr-p-0 nr-mb-10') Result: In [43]: price_container Out[43]: [] As you can see here, the price information is contained in a the div class I specified:
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49388455
has answer: http://stackoverflow.com/a/49389257
tagged with: python
accepted answer: http://stackoverflow.com/a/49388455
has comment: http://stackoverflow.com/comment/85778098
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49361298
score: 0
type: AcceptedAnswer
has body: I managed to get it working with a cstring.i template: %cstring_output_allocate_size(char** data_out, int* maxdata, NULL) When I set the data I also set the size, which I use to set maxdata. The third parameter is NULL and not free because the data is meant to be a reference only.
accepted answer of: http://stackoverflow.com/q/49346490
type: Answer
answers question: http://stackoverflow.com/q/49346490

http://stackoverflow.com/comment/85647586
score: 0
type: AnswerComment
has text: OK, so I edit the answer to include save/restore features for the histogram data
type: Comment
comment on: http://stackoverflow.com/a/49310737

http://stackoverflow.com/a/49406762
accepted answer of: http://stackoverflow.com/q/49405914
type: AcceptedAnswer
downvote count: 0
has body: You want to avoid interfering with this attribute. There is no reason to do any kind of stubbing manually - you want to get out of the way and let it do what it usually does. If it behaves like attributes usually do, everything will work correctly. The correct implementation is therefore to special-case the __objclass__ attribute in your __getattr__ function and throw an AttributeError. class some_class: def __getattr__(self, name): if name == "__objclass__": raise AttributeError # Do something with "name" (by passing it to a server) This way it will behave the same way as it would in a class that has no __getattr__: The attribute is considered non-existant by default, until it's assigned to. The __getattr__ method won't be called if the attribute already exists, so it can be used without any issues: &gt;&gt;&gt; obj = some_class() &gt;&gt;&gt; hasattr(obj, '__objclass__') False &gt;&gt;&gt; obj.__objclass__ = some_class &gt;&gt;&gt; obj.__objclass__ &lt;class '__main__.some_class'&gt;
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49405914
upvote count: 4

http://stackoverflow.com/q/49359762
type: AnsweredQuestion
has title: I need a Python function that can fit a curve within a parameter space
score: 0
has answer: http://stackoverflow.com/a/49363237
accepted answer: http://stackoverflow.com/a/49363237
answer count: 1
has comment: http://stackoverflow.com/comment/85728216
tagged with: scipy
type: Question
tagged with: python-3.x
tagged with: curve-fitting
tagged with: python
has body: I've been working on a project that uses SciPy's optimize.curve_fit() function to fit a curve to some data by varying 3 parameters, which has been working well. However, I now need to alter the program so that 1 of the parameters has bounds which are a function of another parameter (e.g. when x = 10 ybounds = 1 +/- 0.2 but when x = 11 ybounds = 1.1 +/- 0.2). The only idea I've had so far is to put another optimize.curve_fit() function inside the first one, but this has proved hugely inefficient (program now takes ~4 hours rather than 5 mins). Are there any other Python functions I can use to accomplish this?

http://stackoverflow.com/q/49401604
favorite count: 0
has title: How to create a kde(density plot) in a histogram which uses weight parameter?
type: Question
linked to: http://stackoverflow.com/q/27623919
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has body: Originally, I have a bar data like this. import pandas as pd import matplotlib.pyplot as plt import pandas import numpy as np x = np.array([1, 2, 3.1, 3.2, 4.1, 4.2, 4.3, 5, 6, 7]) y = np.random.rand(10) s = pandas.Series(y, index=x) 1.0 0.895835 2.0 0.117966 3.1 0.397263 3.2 0.669877 4.1 0.330271 4.2 0.664608 4.3 0.006288 5.0 0.671697 6.0 0.587998 7.0 0.809034 dtype: float64 Then, I want to use this bar data create a histogram. So I add weight=s.values to achieve sum in a same section. plt.hist(s.index, weights=s.values, bins=7) plt.show( enter image description here However I have no idea about how to bulit a kde in this figure.
downvote count: 0
answer count: 0
score: 1
upvote count: 1
duplicate of: http://stackoverflow.com/q/27623919

http://stackoverflow.com/a/49411388
answers question: http://stackoverflow.com/q/49396765
has body: Answering my own question here, turns out I'm really stupid. The characters / \ : * ? " &lt; &gt; | cannot be used in filenames. For some reason, my computer once allowed me to put them in my file names. More information can be found here.
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49396765

http://stackoverflow.com/comment/85566560
type: Comment
has text: don't bother for the quotes.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49281306

http://stackoverflow.com/a/49364841
type: Answer
has body: Go install VirtualEnvWrapper first. After that, create a new virtualenv, activate it, and run pip freeze. You should see nothing in there because nothing is installed. Deactivate the env to go back to your 'Base' environment and pip freeze again. You will see all the installs you have. A best practice is to create a requirements.txt file and version control it so everyone can use the same versions of the same packages. If you don't want to do this, simply activate your new virtual env and pip install everything you want.
answers question: http://stackoverflow.com/q/49364776
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85688877
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49344311
has text: No worries - always happy to help!

http://stackoverflow.com/comment/85822304
score: 4
comment on: http://stackoverflow.com/q/49410317
type: Comment
type: QuestionComment
has text: You might want to use `for i, age in enumerate(ages)` on the first loop, and then to update the value_map: `value_map[i] = actual_value`. Regarding your second question, [numpy.where](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html) might help

http://stackoverflow.com/q/49399678
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: kivy-language
type: UnansweredQuestion
has title: How to pass a value to initialize a screen widget in Kivy?
tagged with: user-interface
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/27362687
has body: I'm making a travel/tourism app using Kivy as my project and I need to pass some value from a widget to another screen that'll display information of a location. I am able to share information between different screens using this Kivy - Screen Manager - Accessing attribute in other class method, however this doesn't seem to work when I try to pass variables from a widget that isn't directly a screen. I have a chatting interface created using RecycleView that has a button to "see more" information on the current location we're talking about, but I am unable to pass values from this Row widget to the LocationInfo widget/screen. Here is the relevant code Relevant Python code class TourismRoot(ScreenManager): def open_location_info_page(self, locationname): self.current = 'LocationInfoPage' class LocationInfo(Screen): cityname = StringProperty() def test_print(self): print(self.cityname) Relevant KV code TourismRoot: id: screen_manager FirstTimeRun: id: firstrunid name: 'FirstRun' manager: screen_manager FirstTimeRun2: id: firstrun2id name: 'FirstRun_2' manager: screen_manager nickname: firstrunid.entered_nickname #taking value from another screen, works LoginScreen: id: loginscreenid name: 'Login' manager: screen_manager ChatBotScreen: id: chatbotid name: 'ChatBot' manager: screen_manager nickname: firstrunid.entered_nickname LocationInfo: id: locationinfo name: 'LocationInfoPage' manager: screen_manager cityname: chatbotid.ids.lb_chat_row #gives error &lt;Row&gt;: BoxLayout: Label: id: lb_chat_row text: 'stuff' GridLayout: Button: id: bt_chat_row text: root.button_text font_size: "18dp" text_size: self.size on_release: app.root.open_location_info_page(root.ids.lb_chat_row.text) &lt;ChatBotScreen&gt; ScrollView: size_hint_y: 85 RecycleView: id: chatbase_list viewclass: 'Row' data: [] RecycleBoxLayout: orientation: 'vertical' padding: "15dp", "45dp", "15dp", "15dp" default_size_hint: 1, None size_hint_y: None height: self.minimum_height as you can see, the Row widget is…
score: 1
answer count: 1
upvote count: 1
tagged with: kivy
has answer: http://stackoverflow.com/a/49455451

http://stackoverflow.com/q/49360938
accepted answer: http://stackoverflow.com/a/49384639
linked to: http://stackoverflow.com/q/15624667
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49384639
score: 0
has title: Can't run SikuliX scripts from Command Line (Mac)
answer count: 1
tagged with: macos
type: Question
tagged with: sikuli
tagged with: automation
tagged with: python
has body: I'm using MacOS 10.11.6. According to the instructions here, I should have a command runsikulix available, but I don't. (Should it be available after installing? Or do I need to set the variable myself? I couldn't find any explanation). So I tried the following, hoping it would work: I wrote a SikuliX script that works when running from the IDE, and tried running it with the command line as follows: open ./Applications/SikuliX.app -r ./agilent/test.sikuli and I got this response: open: invalid option -- r Without the file argument, the IDE opens. Can anyone give me a pointer on how to run a file? Thanks.

http://stackoverflow.com/a/49381812
has body: Just change the above line this: for dlink in links.find("td",{"class": "download-cell"}): to this: for dlink in links.find_all("td",{"class": "download-cell"}): because you are running a loop on an single element rather than a list. Note: The only difference is that find_all() returns a list containing the single result, and find() just returns the result. Hope this will helps you! :)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49380186
accepted answer of: http://stackoverflow.com/q/49380186

http://stackoverflow.com/comment/108666780
type: AnswerComment
has text: @Giacomo, found any way to sort this out?, i am getting same error...
comment on: http://stackoverflow.com/a/54869077
score: 1
type: Comment

http://stackoverflow.com/q/49402573
tagged with: python
has comment: http://stackoverflow.com/comment/85847447
has comment: http://stackoverflow.com/comment/85831145
has title: Receiving error while loading multiple files with GDAL
type: Question
has body: I have read the path of the files using the following code. import os directory = os.listdir("/home/user/Downloads/SE_75_Ice") fcount = len(directory) i =0 while i &lt; fcount : directory[i] = ('"'+'/home/user/Downloads/SE_75_Ice/'+directory[i]+'"') print(directory[i]) i = i+1 And I tried to read several files using the code below. from osgeo import gdal from matplotlib import pyplot as plt while i &lt; n: directory[i] = ('"'+'path'+directory[i]+'"') ds = gdal.Open(directory[i], gdal.GA_ReadOnly) rb = ds.GetRasterBand(i) img_array_wake_1 = rb.ReadAsArray() plt.imshow(img_array_wake_1) plt.savefig('path/si%d.jpg'%i) i = i+1 When I run the above code, I get the following error: AttributeError: 'NoneType' object has no attribute 'GetRasterBand' I think it may be directory list isn't string type so it can't be read path Please let me know the solution to the above problem or how you can read multiple files at once.
tagged with: gdal
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85818065
tagged with: raster
tagged with: gis
score: 0
has comment: http://stackoverflow.com/comment/85841585
tagged with: geotiff

http://stackoverflow.com/comment/85863763
has text: `C1, C2, C2 = zip(*X)`
type: QuestionComment
score: 5
type: Comment
comment on: http://stackoverflow.com/q/49431032

http://stackoverflow.com/comment/85576237
comment on: http://stackoverflow.com/a/49283519
type: AnswerComment
has text: Thank you for the detailed answer. Explicitly setting the levels accomplished what I wanted. However, my colorbar now shows a mid point of 0 and the labels are every 15 units (-45,-30,-15,0,15,30,45). How can I specify that the colorbar labels appear in increments of 10, going from -50 to 50?
score: 0
type: Comment

http://stackoverflow.com/a/52340867
type: Answer
has body: There are alternative versions of the cocoapi that you can download and use too (I'm using python 3.5). Here's a solution that you might want to try out: How to download and use object detection datasets (e.g. coco or pascal)
answers question: http://stackoverflow.com/q/49311195
score: 0

http://stackoverflow.com/q/49309679
has answer: http://stackoverflow.com/a/49433801
tagged with: one-hot-encoding
downvote count: 0
upvote count: 1
tagged with: python
has title: Feeding numpy uint8 into tensorflow float32 placeholder
tagged with: type-conversion
type: AnsweredQuestion
has body: I recently found a proof of concept implementation, which prepares features in a one-hot encoding using numpy.zeros: data = np.zeros((len(raw_data), n_input, vocab_size),dtype=np.uint8) As could be seen above, the single ones are typed as np.uint8. After inspecting the model, I realized that the input placeholder of the tensorflow model is defined as tf.float32: x = tf.placeholder(tf.float32, [None, n_input, vocab_size], name="onehotin") My particular question: How does tensorflow deal with this "mismatch" of input types. Are those values (0/1) correctly interpreted or casted by tensorflow. If so, is this somewhere mentioned in the docs. After googling I could not found a answer. It should be mentioned that the model runs and values seems plausible. However, typing the input numpy features as np.float32 would cause a significant amount of memory needed. Relevance: A running but falsely trained model would behave differently after adopting the input pipeline / rolling out a model into production.
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49433801
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/49324062
answer count: 0
has comment: http://stackoverflow.com/comment/85650081
type: UnansweredQuestion
has body: I am trying to design a program in python that can share the json file with a server all the time, so I tested to determine whether there an issue when reading and writing the file. The reading of the file has a gap between the changes of content of the file. Separate files Here is my codes: #write.py #from time import sleep i = 0 while 1: f = open("test.txt", 'w') f.write(str(i)) f.close() i+=1 # sleep(1) And #read.py #import time f = open("test.txt", 'r') while 1: print "::> ", f.read() # time.sleep(1) f.seek(0,0) Executed in separate terminal: bash4.2$ python read.py >> logfile.log bash4.2$ python write.py I log the output of read.py and get this result: ::> 1 ::> 1 ::> 1 ::> 1 ::> 1 ::> 1 ::> 1 ::> ::> ::> ::> ::> 2 ::> 2 ::> 2 ::> 2 Here is the image of the log Tried with multiprocessing: #rw.py import multiprocessing as m def writing(): i = 0 while 1: fw = open("test.txt", 'w') fw.write(str(i)) fw.close() i+=1 def reading(): fr = open("test.txt", 'r') while 1: print "::> ", fr.read() fr.seek(0,0) def main(): if __name__ == '__main__': p_w = m.Process(target=writing, args=()) p_r = m.Process(target=reading, args=()) p_w.start() p_r.start() p_w.join() p_r.join() main() Execute in Terminal: bash4.2$ python rw.py >> logfile.log I log the output of this: ::> 0 ::> 0 ::> 0 ::> 0 ::> ::> 1 ::> 1 ::> 1 This is the picture of result of multiprocessing It can be observed that there is always a gap between the change of number. The file using multiprocessing generates only one line gap. Why does that happen? How could I avoid it? If it could be avoided, how does the solution applied to the interaction between the server and python program? Thanks. ########Update 1######## I have tested the program many times and tried with C and Python with the same process. I found that the write and read are not very synchronous in both operating system and software stages. (i.e. The log shows that the gaps between different numbers are different) It appears to be that there is a prior…
tagged with: python
score: 0
tagged with: file-io
has comment: http://stackoverflow.com/comment/85656129
has title: python : file synchronous R/W & multiprocessing
has comment: http://stackoverflow.com/comment/85656100
type: Question

http://stackoverflow.com/a/49374447
has comment: http://stackoverflow.com/comment/85750201
score: 2
has body: You don't need a function. Use a list comprehension instead: &gt;&gt;&gt; list = [5, 6.4, 7.5, 8.8, 2, 2.1] &gt;&gt;&gt; nl = [int(x) for x in list] &gt;&gt;&gt; nl [5, 6, 7, 8, 2, 2] You can think of the list comprehension as a function that gets applied to all of its elements: &gt;&gt;&gt; def process_list(a_list, a_func): ... new_list = [] ... for x in a_list: ... new_list.append(a_func(x)) ... return new_list ... &gt;&gt;&gt; process_list(list,int) [5, 6, 7, 8, 2, 2] but as you see, a list comprehension does a lot of this stuff on its own, and you only have to supply a function that translates each value to a new one. (And technically speaking, you don't even have to process the original values. The list will be iterated for each of its elements and the function will be called for each, but what the function actually does with it is none of Python's concern.)
upvote count: 2
answers question: http://stackoverflow.com/q/49374267
downvote count: 0
has comment: http://stackoverflow.com/comment/85750311
has comment: http://stackoverflow.com/comment/85750168
type: Answer

http://stackoverflow.com/comment/85782847
comment on: http://stackoverflow.com/q/49389054
has text: My point is, show your effort you've tried, even if it doesn't work we can tell you why it doesn't work and how to fix it. Thus you learn more from it.
type: Comment
type: QuestionComment
score: 0

rest
tags question: http://stackoverflow.com/q/49316810
tags question: http://stackoverflow.com/q/49287116
tags question: http://stackoverflow.com/q/49343095
tags question: http://stackoverflow.com/q/49286928
tags question: http://stackoverflow.com/q/49310191
type: Tag
tags question: http://stackoverflow.com/q/49320399
tags question: http://stackoverflow.com/q/49379778
tags question: http://stackoverflow.com/q/49281234
tag name: rest
tags question: http://stackoverflow.com/q/49396670

http://stackoverflow.com/comment/85825003
score: 0
comment on: http://stackoverflow.com/q/49411676
has text: `try... except...`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49290736
has answer: http://stackoverflow.com/a/72889281
has comment: http://stackoverflow.com/comment/85584627
has comment: http://stackoverflow.com/comment/85584654
tagged with: xlsxwriter
tagged with: python
has comment: http://stackoverflow.com/comment/85584678
has body: class house_crawl(): def __init__(self): self.row=0 self.workbook = xlsxwriter.Workbook(self.getdesktoppath() + '\\house_price.xlsx') self.worksheet1 = self.workbook.add_worksheet() self.worksheet1.write_row(self.row,0,['address','describe1','describle2','price','avg_price']) self.row+=1 def __call__(self, url): self.page_crawl(url) def __del__(self): self.workbook.close() def page_crawl(self,url): page=requests.get(url) tree=html.fromstring(page.text) for house in tree.xpath('//*[@class="house-item clearfix"]'): address=house.xpath('div[1]/p[3]/text()')[0] address=re.sub('\r|\n| ','',address) #print(address)浦东-潍坊崂山路571弄（旧址崂山东路571弄） d1=[] for i in house.xpath('div[1]/p[1]/child::*'): d1.append(i.xpath('text()')[0]) st=',' d1=st.join(d1) # print(d1)东欣高层,3室1厅,70平 d2=house.xpath('div[1]/p[2]/text()') stringt=',' d2=stringt.join(d2) d2 = re.sub('\r|\n| ','',d2) #print(d2)南,中层,中装,1991年 price=house.xpath('div[2]/p[1]/text()')[0] #print(price)580万 avg_price=house.xpath('div[2]/p[2]/text()')[0] if '元/平' not in avg_price: avg_price = house.xpath('div[2]/p[3]/text()')[0] #print(avg_price)83400元/平 self.worksheet1.write_row(self.row, 0, [address,d1,d2,price,avg_price]) self.row+=1 def getdesktoppath(self): return os.path.join(os.path.expanduser("~"), 'Desktop') he exception thrown is: Exception ignored in: &lt;bound method house_crawl.__del__ of &lt;__main__.house_crawl object at 0x000001A14533B940&gt;&gt; Traceback (most recent call last): File "D:/pythoncode/crawl/house.py", line 15, in __del__ File "C:\Anaconda3\lib\site-packages\xlsxwriter\workbook.py", line 311, in close File "C:\Anaconda3\lib\site-packages\xlsxwriter\workbook.py", line 619, in _store_workbook File "C:\Anaconda3\lib\site-packages\xlsxwriter\packager.py", line 131, in _create_package File "C:\Anaconda3\lib\site-packages\xlsxwriter\packager.py", line 188, in _write_worksheet_files File "C:\Anaconda3\lib\site-packages\xlsxwriter\xmlwriter.py", line 41, in _set_xml_writer File "C:\Anaconda3\lib\codecs.py", lin…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85584549
answer count: 1
has comment: http://stackoverflow.com/comment/85584511
tagged with: del
upvote count: 1
has comment: http://stackoverflow.com/comment/85584519
downvote count: 1
has comment: http://stackoverflow.com/comment/85584526
favorite count: 0
has comment: http://stackoverflow.com/comment/85584602
type: Question
has comment: http://stackoverflow.com/comment/85584855
has comment: http://stackoverflow.com/comment/85584566
score: 0
has title: python class method __del__ with xlsxwriter.workbook.close()

http://stackoverflow.com/a/49346728
type: Answer
answers question: http://stackoverflow.com/q/49343923
downvote count: 0
upvote count: 1
has body: Note the error: python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. its likely that python executable not set in the environment variable, set it in your environment variable or navigate to directory where python installed. How to add to the pythonpath in windows 7?
score: 1

http://stackoverflow.com/comment/85586831
type: QuestionComment
comment on: http://stackoverflow.com/q/49291726
score: 1
has text: You have to extrapolate what you think `a` should look like at `0` or `nan` first, which is more to do with image processing. If they're invalid pixels, what are you going to do? Take the average of the closest values?
type: Comment

http://stackoverflow.com/comment/85585303
comment on: http://stackoverflow.com/q/49291275
type: Comment
type: QuestionComment
score: 0
has text: whats your django version ?

http://stackoverflow.com/q/49400189
answer count: 1
tagged with: python
tagged with: request
favorite count: 0
has title: Python - Get timing property from network response
type: AnsweredQuestion
has body: How to get the properties as shown on the image (Blocked, DNS resolution, Connecting ...) after sending the request? From firefox, the waiting time = ~650ms From python, requests.Response.elapsed.total_seconds() = ~750ms Since the result is difference, i want to have a more details result as shown on firefox developer mode.
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/49400330
accepted answer: http://stackoverflow.com/a/49400330
upvote count: 1

http://stackoverflow.com/comment/91039628
comment on: http://stackoverflow.com/a/49323825
type: Comment
score: 0
type: AnswerComment
has text: @eduzen you can use two queries OR'd together - `q = Q("match", codeData__code="L4") | Q("match", codeData__code="L6")` or you can use a special query that can handle multiple values like `terms` etc

http://stackoverflow.com/comment/85576416
type: AnswerComment
score: 1
type: Comment
has text: Yup....your answer looks easy to understand and 2nd one is lil'bit complex for me as I am a beginner in python.
comment on: http://stackoverflow.com/a/49286501

http://stackoverflow.com/q/49343908
accepted answer: http://stackoverflow.com/a/49343969
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49343969
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49343991
answer count: 5
linked to: http://stackoverflow.com/q/21581824
has body: So I wrote this code to remove the vowels from any string given. it should work fine. And it actually does. Just not for all strings which is weird why it would work for some strings and not for others here's the code: vowels = ["a", "e", "i", "o", "u"] def anti_vowel(text): text1 = list(text) print text1 for i in text1: if i.lower() in vowels: text1.remove(i) text2 = "".join(text1) return text2 and here are the tests that I placed: print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") I tried placing print statements in the middle of the code to test it and I found something weird. the for loop iterates about 3 or 4 times to remove one vowel. I can't seem to know why
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49345349
possible better answer: http://stackoverflow.com/a/49343960
has answer: http://stackoverflow.com/a/49343989
type: Question
has comment: http://stackoverflow.com/comment/85688188
has answer: http://stackoverflow.com/a/49343960
tagged with: python
has title: my code to remove vowels from a string is acting weird

http://stackoverflow.com/comment/85758861
type: QuestionComment
has text: Hi, but I make some changes to the code, and I can run it, I make modification to the method showmessagebox, and i created checking name method. It can be run, the problem is that the message box cannot be closed
score: 0
comment on: http://stackoverflow.com/q/49379069
type: Comment

http://stackoverflow.com/a/49424146
accepted answer of: http://stackoverflow.com/q/49424010
has body: This could be to do with a lack of cv::waitKey(0) and the window is not getting updated, although this is odd. Try adding a cv::waitKey command after imshow like this import cv2 cap = cv2.VideoCapture(0) cv2.namedWindow('frame', cv2.WINDOW_NORMAL) while True: key = cv2.waitKey(0) &amp; 0xFF ret, frame = cap.read() cv2.imshow('frame', frame) cv2.waitKey(0) if key == ord('q'): cap.release() cv2.destroyAllWindows() break if key == ord('c'): cv2.imwrite('capture.jpg', frame) cap.release() cv2.destroyAllWindows() I think it might be this as when you do the imwrite you are effectively breaking out of the while loop (albeit slightly) to do something else with opencv.
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49424010
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/78274524
has body: For an approximate result, x**(1/3) should be fine. If you know that x = n**3 is the cube of an integer n, then you can use round() to get the nearest integer which should be n up to n ~ 2**53 ~ 10**16. For larger numbers, the approach using floats will necessarily give wrong results. For example, x = 2**54+1 is odd, but round((x**3)**(1/3)) will give you an even number, which is certainly wrong. You can write your own function using Newton's (a.k.a. the Babylonian) method to get the exact integer result for integers of arbitrary size. That means, you consider the sequence of approximations defined by x(k+1) = φ(x(k)) with φ(x) = x - f(x)/f'(x) = ((p-1)*x + n/x^(p-1))/p for f(x) = x^p - n whose zero is the p-th root of n. Thus, at each step you take the weighted average of the approximation x (with weight p-1) and n/x^(p-1) (which would be equal to x if x = n^(1/p)) with weight 1. (This should converge faster then the simple average corresponding to binary search.) You stop when the approximations are close enough. (Due to integer arithmetic, the weighted average may not always result in |a-b| <= 1 for p > 2, so the code below has some ugly terminating criteria/process (which can probably be improved) to ensure it always returns the expected result.). def root(x: int, n: int = 3): "Return integer part of the n-th root (n > 1) of x > 0." p = n-1; a = x >> (x.bit_length()*p//n) # initial guess while True: b = x // a**p # too small if a is too big and vice versa if abs(a-b) < n: if a < b: a = b while a**n >= x: a -= 1 # ugly but safe return a a = (p*a + b) // n
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49401472
type: Answer

http://stackoverflow.com/a/49320996
downvote count: 0
has comment: http://stackoverflow.com/comment/85644168
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49320935
type: Answer
has comment: http://stackoverflow.com/comment/85644150
answers question: http://stackoverflow.com/q/49320935
has body: I think need map with groupby and lists per groups: df1['ticketid'] = df1['cid'].map(df2.groupby('cid')['ticketid'].apply(list)) print (df1) cid name surname address ticketid 0 1 Mueller Hans 42553 [9, 22] 1 2 Meier Peter 42873 [8] 2 3 Schmidt Micha 42567 [7] 3 4 Pauli Ulli 98790 [6] 4 5 Dick Franz 45632 [5] EDIT: More general solution with join and aggregate all columns to lists: print (df2) cid ticketid A 0 1 9 s 1 1 22 r 2 2 8 t 3 3 7 r 4 4 6 m 5 5 5 a df = df1.join(df2.groupby('cid').agg(lambda x: x.tolist()), on='cid', rsuffix='_B') print (df) cid name surname address ticketid A 0 1 Mueller Hans 42553 [9, 22] [s, r] 1 2 Meier Peter 42873 [8] [t] 2 3 Schmidt Micha 42567 [7] [r] 3 4 Pauli Ulli 98790 [6] [m] 4 5 Dick Franz 45632 [5] [a]
score: 2

http://stackoverflow.com/q/49419621
has answer: http://stackoverflow.com/a/49420351
tagged with: selenium
tagged with: python
score: 0
has body: I have to get the specific values from Request Header -- referer referer: https://xxx.xx.xx/xx/xx?programGroupName=xxx&amp;fundraiserPageID=3041315&amp;participantFirstName=Test&amp;participantLastName=Testerson&amp;displayName=Test%20Testerson&amp;fundraiserPageURL=http://xxx.xxx.xx/wpa/xx/xxx In above I have to get only fundraiserPageID value that is '3041315' and after that participantFirstName value 'Test' plus other values and then need to store in the previous defined variables, so that I can reuse in the next request. I tied following attempt using regular expression and it shows nothing, I'm going something wrong, not sure how to define the regular expression for it etc...
tagged with: jmeter
has title: how can I get the value from header in JMeter
tagged with: java
type: Question
has answer: http://stackoverflow.com/a/49423869
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/85569726
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49283099
has text: What is the format of data variable that's taken here? Having trouble using OP's data as data = [[1,2,3], [4,5,6], [7,8,9]]. Get TypeError: list indices must be integers or slices, not list.
score: 0

http://stackoverflow.com/q/49341366
tagged with: python
has comment: http://stackoverflow.com/comment/85684422
downvote count: 0
has title: How to close a program on a raspberry pi, in python
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49354518
favorite count: 0
type: Question
tagged with: raspberry-pi
has body: What code can be used to close a program running on RPI3? I am running a smart magic mirror using my Raspberry Pi, and I want to then close it. How can I?
type: UnansweredQuestion

http://stackoverflow.com/a/49323952
answers question: http://stackoverflow.com/q/49321731
type: Answer
has comment: http://stackoverflow.com/comment/85720893
score: 2
has body: If your dataframe looks as +---------+---------+ |sessionid|event_col| +---------+---------+ |0 |1 | |1 |2 | |1 |3 | |2 |1 | |0 |3 | +---------+---------+ Then groupBy and aggregation as stated by Lokesh in the comment above should be sufficient to get the output as from pyspark.sql import functions as F df.groupBy("sessionid").agg(F.collect_list(F.col("event_col")).alias("events")).show(truncate=False) and you should get the desired output +---------+------+ |sessionid|events| +---------+------+ |0 |[1, 3]| |1 |[2, 3]| |2 |[1] | +---------+------+ I hope the answer is helpful
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49321731
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49294356
downvote count: 0
has body: Not all types have such a value to begin with. Others may have many such values. The most correct way of doing this would be to create a type-to-value dict, because then you could check if a given type was in the dict at all, and you could chose which value is the correct one if there are multiple options. The drawback is of course that you would have to somehow register every type you were interested in. Alternatively, you could write a function using some heuristics. If you were very careful about what you passed into the function, it would probably be of some limited use. For example, all the cases you show except complex are containers that generalize with cls(). complex actually works like that too, but I mention it separately because int and float do not. So if your attempt with the empty constructor fails by returning a truthy object or raising a TypeError, you can try cls(0). And so on and so forth... Update @juanpa.arrivillaga's answer actually suggests a clever workaround that will work for most classes. You can extend the class and forcibly create an instance that will be falsy but otherwise identical to the original class. You have to do this by extending because dunder methods like __bool__ are only ever looked up on the class, never on an instance. There are also many types where such methods can not be replaced on the instance to begin with. As @Aran-Fey's now-deleted comment points out, you can selectively call object.__new__ or t.__new__, depending on whether you are dealing with a very special case (like int) or not: def f(t): class tx(t): def __bool__(self): return False try: return object.__new__(tx) except TypeError: return tx.__new__(tx) This will only work for 99.9% of classes you ever encounter. It is possible to create a contrived case that raises a TypeError when passed to object.__new__ as int does, and does not allow for a no-arg version of t.__new__, but I doubt you will ever find such a thing in nature. See the gist @Aran-Fey made to de…
type: Answer
answers question: http://stackoverflow.com/q/49294222
upvote count: 5
score: 5

http://stackoverflow.com/q/49311845
tagged with: computer-science
type: Question
possible better answer: http://stackoverflow.com/a/49311995
has answer: http://stackoverflow.com/a/49311995
tagged with: python
has title: dictionary using in python creating a movie cinema
has body: The dictionary will store the names of the movies, and for each movie the dictionary value will be a list of show times. I could not figure it out. Is that correct??? movie A: 9,11,15 movie B: 10,14,6 movie C: 11,13,19 dictionary={"moviesA":0, "moviesB":0, "moviesC":0} showingtimes={"moviesA": 9, "moviesA": 11, "moviesA": 15, "moviesA": 21, "moviesB" : 10, "moviesB": 14, "moviesB": 16, "moviesC": 11, "moviesC":13, "moviesC":19, "moviesC": 20, "moviesC": 21, "movieC":22}
has answer: http://stackoverflow.com/a/49314768
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85626934
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49314768
has comment: http://stackoverflow.com/comment/85625583

http://stackoverflow.com/comment/85649206
comment on: http://stackoverflow.com/q/49323896
type: Comment
type: QuestionComment
score: 2
has text: Have you made any attempts? Where did you get stuck, what doesn't work for you?

http://stackoverflow.com/a/49411563
has body: cumsum + idxmax should work: df.A.cumsum().gt(5).idxmax() 3
has comment: http://stackoverflow.com/comment/85825467
type: Answer
accepted answer of: http://stackoverflow.com/q/49411523
score: 2
answers question: http://stackoverflow.com/q/49411523
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49427601
type: Question
has body: i am trying to insert a list of values in to DB table created with 3 field. Here is the code I tried conn = sqlite3.connect("C://Users// Analysis//Data_Analysis_DB.db") c = conn.cursor() test="value1", "value2", 3663 string_value=str(test) a,b,c=string_value.split(',') c.execute('Insert into Users values(?,?,?)',a,b,c) but I am getting following error AttributeError: 'str' object has no attribute 'execute' Would be appreciated if anyone can help on this Thanks
type: UnansweredQuestion
has title: Unable to parse a list of values to sqlite3 DB
tagged with: python
score: 0
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/49435395

http://stackoverflow.com/comment/85568135
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49282574
has text: thanks @alasair, I got it resolved, but i have another problem please take a look at updated `forms.py` code. it was throwing me ` __init__() takes at least 2 arguments (1 given)` this error. As I said, I want to populate modelchoicefield with values from database. :)

flask
tags question: http://stackoverflow.com/q/49333656
tags question: http://stackoverflow.com/q/49308534
tags question: http://stackoverflow.com/q/49414776
tags question: http://stackoverflow.com/q/49409691
tags question: http://stackoverflow.com/q/49382913
tags question: http://stackoverflow.com/q/49395252
tags question: http://stackoverflow.com/q/49413062
tags question: http://stackoverflow.com/q/49288541
tags question: http://stackoverflow.com/q/49419563
tags question: http://stackoverflow.com/q/49395490
tags question: http://stackoverflow.com/q/49425538
tags question: http://stackoverflow.com/q/49396485
tags question: http://stackoverflow.com/q/49376394
tags question: http://stackoverflow.com/q/49292416
tags question: http://stackoverflow.com/q/49282724
tags question: http://stackoverflow.com/q/49311103
tags question: http://stackoverflow.com/q/49414253
tags question: http://stackoverflow.com/q/49351121
tags question: http://stackoverflow.com/q/49374730
tags question: http://stackoverflow.com/q/49408509
tags question: http://stackoverflow.com/q/49369254
tags question: http://stackoverflow.com/q/49332853
tags question: http://stackoverflow.com/q/49413109
tags question: http://stackoverflow.com/q/49425787
tags question: http://stackoverflow.com/q/49352878
tags question: http://stackoverflow.com/q/49405648
tags question: http://stackoverflow.com/q/49310191
tags question: http://stackoverflow.com/q/49419231
tags question: http://stackoverflow.com/q/49341712
tags question: http://stackoverflow.com/q/49333233
tags question: http://stackoverflow.com/q/49314730
tags question: http://stackoverflow.com/q/49378849
tags question: http://stackoverflow.com/q/49295149
tags question: http://stackoverflow.com/q/49388628
tags question: http://stackoverflow.com/q/49382024
tags question: http://stackoverflow.com/q/49293729
tags question: http://stackoverflow.com/q/49358868
tags question: http://stackoverflow.com/q/49316810
tags question: http://stackoverflow.com/q/49334438
tags question: http://stackoverflow.com/q/49291739
tags question: http://stackoverflow.com/q/49316674
tags question: http://stackoverflow.com/q/49434267
tags question: http://stackoverflow.com/q/49358039
tags question: http://stackoverflow.com/q/49333279
tags question: http://stackoverflow.com/q/49422913
tags question: http://stackoverflow.com/q/49365066
tags question: http://stackoverflow.com/q/49324076
tags question: http://stackoverflow.com/q/49314242
tags question: http://stackoverflow.com/q/49326245
tags question: http://stackoverflow.com/q/49404599
tag name: flask
tags question: http://stackoverflow.com/q/49375141
tags question: http://stackoverflow.com/q/49417145
tags question: http://stackoverflow.com/q/49390512
tags question: http://stackoverflow.com/q/49424938
tags question: http://stackoverflow.com/q/49381433
tags question: http://stackoverflow.com/q/49339600
tags question: http://stackoverflow.com/q/49316475
tags question: http://stackoverflow.com/q/49285147
tags question: http://stackoverflow.com/q/49328240
tags question: http://stackoverflow.com/q/49390075
tags question: http://stackoverflow.com/q/49399612
tags question: http://stackoverflow.com/q/49299470
tags question: http://stackoverflow.com/q/49334636
type: Tag
tags question: http://stackoverflow.com/q/49283494
tags question: http://stackoverflow.com/q/49438740
tags question: http://stackoverflow.com/q/49280460
tags question: http://stackoverflow.com/q/49385103
tags question: http://stackoverflow.com/q/49371873
tags question: http://stackoverflow.com/q/49383678
tags question: http://stackoverflow.com/q/49340821
tags question: http://stackoverflow.com/q/49298114
tags question: http://stackoverflow.com/q/49403645
tags question: http://stackoverflow.com/q/49387542
tags question: http://stackoverflow.com/q/49392527
tags question: http://stackoverflow.com/q/49307704
tags question: http://stackoverflow.com/q/49392595

http://stackoverflow.com/comment/85697063
score: 0
type: Comment
type: QuestionComment
has text: I'm planning to convert this to mips assembly language so I figured while loop will be easier?
comment on: http://stackoverflow.com/q/49348469

http://stackoverflow.com/comment/85958417
type: AnswerComment
comment on: http://stackoverflow.com/a/49476551
has text: Thanks, If you were using that approach and it worked so I'm going to use it too :-)
score: 1
type: Comment

http://stackoverflow.com/q/49414976
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/49415169
has answer: http://stackoverflow.com/a/49418546
tagged with: django-models
tagged with: python
tagged with: django-related-manager
has title: Django rest framework serializer with reverse relation
has body: I have two models where employee have relation with person model but person have no relation with employee model. Like: class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Employee(models.Model): person = models.ForeignKey(Person, related_name='person_info') code = models.CharField() In such cases I want code field data in person serializer. I can solved this with writing method in person model or using SerializerMethodField in person serializer like this: def get_employee_code(self): return Employee.objects.get(person=self).id and add this as source in person serializer employee_code = serializers.CharField(source='get_employee_code') Or adding employee serializer into person serialiszer class PersonSerializer(serializers.ModelSerializer): employee = EmployeeSerializer() class Meta: model = Person fields = ('name', 'address', 'employee') But i was trying to do this with reverse relation but i can't. I have tried like this, it gives an error Serializer: class PersonSerializer(serializers.ModelSerializer): employee_code = serializers.CharField(source='person_info.code') class Meta: model = Person fields = ('name', 'address', 'employee_code') How can i solve this with reverse relation?
answer count: 2
score: 5
type: UnansweredQuestion

http://stackoverflow.com/comment/85838790
type: QuestionComment
comment on: http://stackoverflow.com/q/49418478
score: 0
has text: it is python 3.
type: Comment

animation
tags question: http://stackoverflow.com/q/49293067
tags question: http://stackoverflow.com/q/49346708
tags question: http://stackoverflow.com/q/49404585
tags question: http://stackoverflow.com/q/49363806
tags question: http://stackoverflow.com/q/49405265
type: Tag
tag name: animation
tags question: http://stackoverflow.com/q/49391563

http://stackoverflow.com/comment/85793588
type: Comment
type: AnswerComment
has text: They probably just call `float()` in it. `float()` calls `x.__float__()` on types that have it.
comment on: http://stackoverflow.com/a/49395852
score: 0

http://stackoverflow.com/comment/85645912
score: 0
comment on: http://stackoverflow.com/q/49304191
type: Comment
has text: @TomDalton `do_stuff_with_inputs()` just creates a text file that `my_executable.x` uses as in input to the simulation, and `post_process_stuff()` parses the output of `my_executable.x` and records it. And yes it seems my code snippet only runs two, but one of the goals is to to able to run an arbitrary number of these simulations independently (limited only by my cores available to me)
type: QuestionComment

http://stackoverflow.com/a/49429772
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49429709
has body: It look like You have a list (or array) in employees.age. Even if you have only 1 item in that array. Try use that in your code "filter(employees#0.age &gt; 22)"

http://stackoverflow.com/q/49433383
has comment: http://stackoverflow.com/comment/86273090
has title: conda-build of official AnacondaRecipes/opencv-feedstock fails looking for libpng.h
has comment: http://stackoverflow.com/comment/86506438
has comment: http://stackoverflow.com/comment/86510031
tagged with: conda
has body: I have downloaded the official conda recipe of opencv in AnacondaRecipes. I have tried to build this package executing: conda-build recipe -c conda-forge I am getting the following error when the recipe compiles opencv, when doing [ 72%] Built target opencv_dnn . The error is the following: [ 67%] Building CXX object modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/src/grfmt_png.cpp.o /opt/conda/conda-bld/opencv_1521187259162/work/modules/imgcodecs/src/grfmt_png.cpp:62:10: fatal error: libpng/png.h: No such file or directory #include &lt;libpng/png.h&gt; ^~~~~~~~~~~~~~ compilation terminated. modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/build.make:326: recipe for target 'modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/src/grfmt_png.cpp.o' failed make[2]: *** [modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/src/grfmt_png.cpp.o] Error 1 CMakeFiles/Makefile2:4645: recipe for target 'modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/all' failed make[1]: *** [modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/all] Error 2 make[1]: *** Waiting for unfinished jobs.... Lookin in the $PREFIX directory, there is not libpng folder, only a libpng16 folder: /opt/conda/conda-bld/opencv_1521187259162/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeh/include/ I suspect it must be something related to how conda-build manages the path environment, but I do not have any clue of how to solve it. Environment: conda 4.4.11, OS: Ubuntu 16.04. UPDATE 23/03/2018 I have also tried: add libpng/png.h to the location pointed by the $PREFIX directory. add /usr/include to the $PATH No success in either case. UPDATE 04/03/2018 libpng-dev is installed in the environment. UPDATE 09/04/2018 Docker recipe to reproduce environment UPDATE 12/04/2018 Docker recipe using miniconda3 and installing conda in /usr/local/conda instead of /o…
score: 14
upvote count: 14
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49642742
has comment: http://stackoverflow.com/comment/85890664
answer count: 1
tagged with: conda-build
has comment: http://stackoverflow.com/comment/86595815
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/86582844
has answer: http://stackoverflow.com/a/49642742
has comment: http://stackoverflow.com/comment/86526277
downvote count: 0
has comment: http://stackoverflow.com/comment/85879000
tagged with: python
has comment: http://stackoverflow.com/comment/86282153

http://stackoverflow.com/q/49319153
downvote count: 1
favorite count: 0
type: Question
has title: MultiValue Dict Key Error Django - Forms when trying to display DateField
has comment: http://stackoverflow.com/comment/85639903
has comment: http://stackoverflow.com/comment/85639675
has comment: http://stackoverflow.com/comment/85639264
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49319778
tagged with: python
has body: I have a form with DateField - 'receivedon' attribute as below: forms.py: class PreDataForm(forms.ModelForm): journalname=forms.ChoiceField(required=True,choices=JOURNAL_CHOICES) articletype = forms.ChoiceField(required=True, choices=ARTICLE_TYPES) granttype = forms.ChoiceField(required=True, choices=GRANTS) receivedon=forms.DateField(widget=forms.SelectDateWidget) class Meta: model=PreData fields=['journalname','articlename','articlenumber','caname','camail','articletype', 'country','affliation','granttype','status','receivedon'] I will be asking users to fill that date in html, normal procedure: html: &lt;div class="center col-md-6"&gt; Received On: {{ form.receivedon }} &lt;/div&gt; Now i want to upload the date through django views like this: views.py: if request.method=="POST": form=PreDataForm(request.POST or None) print request.POST['receivedon'] if form.is_valid(): instance=form.save(commit=False) instance.save() One thing is that form is always invalid for post request, when i check is_valid function, other thing when I try to display datefield data using request.POST['receivedon'] i am getting Multi Value Dict Key Error Can any one help me with this? Thanks. Traceback - Edit: File "/Users/Devadanam/Desktop/django_project_postgresql/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/Users/Devadanam/Desktop/django_project_postgresql/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Devadanam/Desktop/django_project_postgresql/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/Devadanam/Desktop/django_project_postgresql/django_project/jsmmetrics/views.py" in createdata 55. print request.POST['receivedon'] File "/Users/Devadanam/Desktop/django_project_postgresql/lib/py…
score: 0
has comment: http://stackoverflow.com/comment/85639552
answer count: 1
tagged with: datefield
has comment: http://stackoverflow.com/comment/85639436
tagged with: django
upvote count: 1

http://stackoverflow.com/q/49284893
type: Question
has answer: http://stackoverflow.com/a/79268232
has title: Matplotlib while debugging in Pycharm: How to turn off interactive mode?
upvote count: 8
type: UnansweredQuestion
has body: First of all, I am working on the Pycharm debug console and want to put a caption under my diagram. According to this answer this can be achieved by: plt.plot([2,5,1,2] fig = plt.figure() fig.text(.5, .05, "text", ha="center") plt.show() However, this shows me the plot at first, then an empty window (after typing the second line) and nothing later. I figured out this must be because of interactive mode of matplotlib so I turned it off using plt.ioff() in the debug session after which plt.isinteractive() returns False. Still this does not change its behaviour and shows the plot right after the plt.plot(...) command. Weirdly enough when I put plt.ioff() in my script, it is ignored and plt.isinteractive() returns True. import matplotlib.pyplot as plt plt.ioff() plt.plot([1,2,3,4,5]) print(plt.isinteractive()) My system information: PyCharm CE 2017.3.2 macOS Sierra 10.12.6 Python 3.6.3 in an Anaconda Environment Can anyone reproduce this? Is there another way to create more complicated diagrams from the Pycharm debug console? I would prefer to not change my development environment everytime I want to plot something more complicated.
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/34010205
score: 8
tagged with: pycharm
answer count: 3
has answer: http://stackoverflow.com/a/78731434
downvote count: 0
tagged with: python-interactive
tagged with: macos
favorite count: 0
has answer: http://stackoverflow.com/a/49288052

http://stackoverflow.com/comment/85650492
type: QuestionComment
comment on: http://stackoverflow.com/q/49324426
type: Comment
score: 1
has text: You should use the `csv` module instead of parsing CSV file with `line.strip().split()`.

http://stackoverflow.com/a/51004211
answers question: http://stackoverflow.com/q/49311929
downvote count: 0
has comment: http://stackoverflow.com/comment/110544007
has comment: http://stackoverflow.com/comment/119795503
upvote count: 10
score: 10
type: Answer
has body: Download the datasets from the answer above. And use this code (It's better than the above since it closes the files after usage): def load_dataset(): with h5py.File('datasets/train_catvnoncat.h5', "r") as train_dataset: train_set_x_orig = np.array(train_dataset["train_set_x"][:]) train_set_y_orig = np.array(train_dataset["train_set_y"][:]) with h5py.File('datasets/test_catvnoncat.h5', "r") as test_dataset: test_set_x_orig = np.array(test_dataset["test_set_x"][:]) test_set_y_orig = np.array(test_dataset["test_set_y"][:]) classes = np.array(test_dataset["list_classes"][:]) train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

http://stackoverflow.com/q/49434319
has answer: http://stackoverflow.com/a/49434596
has comment: http://stackoverflow.com/comment/85917469
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/26671931
score: 0
tagged with: function
has title: numpy array fromfunction using each previous value as input, with non-zero initial value
answer count: 1
has body: I would like to fill a numpy array with values using a function. I want the array to start with one initial value and be filled to a given length, using each previous value in the array as the input to the function. Each array value i should be (i-1)*x**(y/z). After a bit of work, I have got to: import numpy as np f = np.zeros([31,1]) f[0] = 20 fun = lambda i, j: i*2**(1/3) f[1:] = np.fromfunction(np.vectorize(fun), (len(f)-1,1), dtype = int) This fills an array with [firstvalue=20, 0, i-1 + 1*2**(1/3),...] I have arrived here having read https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfunction.html Use of numpy fromfunction Most efficient way to map function over numpy array Fastest way to populate a matrix with a function on pairs of elements in two numpy vectors? How do I create a numpy array using a function? But I'm just not getting how to translate it to my function.
tagged with: numpy
has comment: http://stackoverflow.com/comment/85910994
type: Question
has comment: http://stackoverflow.com/comment/85917973
has comment: http://stackoverflow.com/comment/85911070
linked to: http://stackoverflow.com/q/35215161
linked to: http://stackoverflow.com/q/16800355
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/85878886
has comment: http://stackoverflow.com/comment/85957952
accepted answer: http://stackoverflow.com/a/49434596
linked to: http://stackoverflow.com/q/40672367
has comment: http://stackoverflow.com/comment/85909219

http://stackoverflow.com/a/49339451
upvote count: 2
downvote count: 0
has body: You can see the description of context argument: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template. Change your line: return render_to_response('comments.html', RequestContext(request, locals())) To: return render_to_response('comments.html', context=locals())
type: Answer
answers question: http://stackoverflow.com/q/49339404
score: 2

http://stackoverflow.com/comment/85750718
type: QuestionComment
score: 0
has text: @PHPglue Normally you don't use this on three ranges, you use it on some useful pair of sequences where you want the cartesian product (without building the whole list in memory). In other words, it's exactly as useless as a nested loop statement is…
comment on: http://stackoverflow.com/q/49374737
type: Comment

http://stackoverflow.com/comment/85865162
type: Comment
type: QuestionComment
score: 0
has text: do your folders have `__init__.py` files
comment on: http://stackoverflow.com/q/49431681

http://stackoverflow.com/q/49361665
accepted answer: http://stackoverflow.com/a/49362496
has body: I've done this RLE code a while back and I seem to be blind on what is going on wrong. The expected output of encode() should be 'a1b2c3' but instead I'm getting the value 'None'. def encode(text): if not text: return "" else: last_char = text[0] max_index = len(text) i = 1 while i &lt; max_index and last_char == text[i]: i += 1 return last_char + str(i) + encode(text[i:]) print(encode("abbccc")) def decode(text): if not text: return "" else: char = text[0] quantity = text[1] return char * int(quantity) + decode(text[2:]) print(decode("a1b2c3")) Regards
has comment: http://stackoverflow.com/comment/85723421
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49362414
has answer: http://stackoverflow.com/a/49362496
tagged with: algorithm
answer count: 2
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85724679
type: AnsweredQuestion
score: 0
has title: What is wrong with this RLE Algorithm in Python?
has comment: http://stackoverflow.com/comment/85723397
possible better answer: http://stackoverflow.com/a/49362414

http://stackoverflow.com/q/49396631
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85812356
has comment: http://stackoverflow.com/comment/85795488
score: 3
linked to: http://stackoverflow.com/q/41732836
has body: dear. I am going to get text from image using python ocr. I hope resolve following error. I can not solve this error. code and error is follow. thanks. import pytesseract from PIL import Image, ImageEnhance, ImageFilter import cv2 import numpy as np src_path = "" def get_string(img_path): #read image with opencv img = cv2.imread(img_path) #convert to gray img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #apply dilation and erosion to remove some noise kernel = np.ones((1,1), np.unicode) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) cv2.imwrite("2.jpg", img) #apply threshold to get image with only black and white img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSAIN_C, cv2.THRESH_BINARY,11,2) cv2.imwrite("1.jpg", img) #recognize text with tesseract for python result = pytesseract.image_to_string(Image.open("1.jpg")) return result print(get_string("a.jpg")) error is following. C:\python\python.exe C:/Users/rharmed/PycharmProjects/nike/crawler2_.py Traceback (most recent call last): File "C:/Users/rharmed/PycharmProjects/nike/crawler2_.py", line 26, in &lt;module&gt; print(get_string("a.jpg")) File "C:/Users/rharmed/PycharmProjects/nike/crawler2_.py", line 15, in get_string img = cv2.dilate(img, kernel, iterations=1) TypeError: kernel data type = 19 is not supported [ INFO:0] Initialize OpenCL runtime... Process finished with exit code 1
upvote count: 3
has answer: http://stackoverflow.com/a/58655710
has title: How to resolve "data type = 19 is not supported" error in python?
tagged with: ocr
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85798498

http://stackoverflow.com/comment/85915948
type: AnswerComment
comment on: http://stackoverflow.com/a/49442484
score: 0
type: Comment
has text: thank you for the explanation! I will try it out and see what I can get

http://stackoverflow.com/q/49438025
has title: Merge rows of pandas data frame by grouping a column
has body: A beginner in panda and trying to achieve this in a pandas data frame- Input- Input I want an output like- Output It is groupby on name columns, the merge all the rows in Address and in same row store the total count of address. Any help is appreciated. thanks
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49438141
tagged with: python
has comment: http://stackoverflow.com/comment/85878159
accepted answer: http://stackoverflow.com/a/49438141
type: AnsweredQuestion
tagged with: pandas-groupby
upvote count: 2
tagged with: pandas
score: 1
answer count: 1

http://stackoverflow.com/q/49349627
has comment: http://stackoverflow.com/comment/85699268
linked to: http://stackoverflow.com/q/17702937
linked to: http://stackoverflow.com/q/240178
tagged with: python
has title: Editing 2D lists in python
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/85698969
score: 0
has body: I created a 2D list in python as follows: b = [[0] * 3] * 3 # 3 * 3 Now if I want to make the first element of the first row to be 1, I am doing this: b[0][0] = 1 But if I print b, it is making the first element of every row to be 1, something like this: [[1, 0, 0], [1, 0, 0], [1, 0, 0]] What is the problem with my approach? Please suggest some alternatives to create a 2D list in python.
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2739552
type: Question
tagged with: python-3.x

pyelasticsearch
tags question: http://stackoverflow.com/q/49320599
tag name: pyelasticsearch
type: Tag

http://stackoverflow.com/comment/85719983
has text: @VivekKumar - Yes, it is calculating the dot product, which I am also doing..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49340540

http://stackoverflow.com/q/49357063
downvote count: 0
has comment: http://stackoverflow.com/comment/85717800
has comment: http://stackoverflow.com/comment/85714435
linked to: http://stackoverflow.com/q/3393612
tagged with: sleep
has title: Python - Alternative to time.sleep
favorite count: 0
type: Question
has body: Hello is there a alternative to time.sleep? Because I want to let my LEDs blink in the exact amount of Hz what is not able because to call time.sleep needs time too, so the blinking needs more time than expected. #!/usr/bin/python import RPi.GPIO as GPIO import time from threading import Thread GPIO.setmode(GPIO.BOARD) GPIO.setup(32, GPIO.IN) def blink(port, hz): GPIO.setup(port, GPIO.OUT) while True: if GPIO.input(32) == 1: //lever activated? GPIO.output(port, GPIO.HIGH) time.sleep(0.5/hz) GPIO.output(port, GPIO.LOW) time.sleep(0.5/hz) else: GPIO.output(port, GPIO.LOW) #to make it easier to add new LED def start(port, hz): Thread(target=blink, args=(port, hz)).start() #to add LED insert start(GPIOport, Hz) start(15, 2) start(16, 4) start(18, 6) start(22, 12) start(29, 24)
tagged with: timer
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/85714754
accepted answer: http://stackoverflow.com/a/49358018
tagged with: python
has answer: http://stackoverflow.com/a/49358018
has comment: http://stackoverflow.com/comment/85714985
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85714720
upvote count: 2
score: 2
answer count: 1

http://stackoverflow.com/comment/85678566
type: Comment
comment on: http://stackoverflow.com/a/49336096
type: AnswerComment
has text: Yes you're understanding is correct. I need to check 1) whether those "short" cycles are actually looks "axiomatic" upon human intuition- anyway the most important number for `k` is 2,3, or at most 4. They deserve to be called "small enough" 2) As I keep increasing `k`, which `word` will we sequentially face for the source of cycle? That's my second question. One thing I roughly but intuitively knows is that, small cycles normally for `predicates` - verb or adjectives and bigger cycles normally for `nouns`. That's what my intuition tells.
score: 0

http://stackoverflow.com/a/49369473
has body: As others have pointed out, you can use enumerate() to get the indexes. I'd also argue that if you are treating the tuples as ranges, you should make them ranges. This then makes the check to see if the value is inside the range very intuitive: value in range. import itertools seg = [(874, 893), (964, 985), (1012, 1031)] ranges = list(itertools.starmap(range, seg)) def test(value): for i, valueRange in enumerate(ranges): if value in valueRange: return i # + 1 if you want to index from 1 as indicated. # You could add some special case handling here if there is no match, like: # throw NoSuchRangeException("The given value was not inside any of the ranges.") print(test(876)) # 0 print(test(1015)) # 1 Obviously using ranges has some cost (if you are in Python 2.x, this is comparatively huge because it will make actual lists of all the values, and unfortunately xrange() return objects without __contains__() implemented). If you are doing this kind of thing in lots of places, it's much nicer, however. You may be able to just replace your tuple construction with range construction, depending on the situation, rather than doing the starmap.
answers question: http://stackoverflow.com/q/49369276
has comment: http://stackoverflow.com/comment/85739872
has comment: http://stackoverflow.com/comment/85739912
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/49375054
downvote count: 0
has answer: http://stackoverflow.com/a/54697430
score: 11
has answer: http://stackoverflow.com/a/57039627
has comment: http://stackoverflow.com/comment/85751757
favorite count: 0
accepted answer: http://stackoverflow.com/a/49466811
type: AnsweredQuestion
tagged with: alexa-skills-kit
has answer: http://stackoverflow.com/a/49466811
has comment: http://stackoverflow.com/comment/85751710
has body: I'm trying to begin developing a skill for alexa using flask-ask and ngrok in python. Following is my code: from flask import Flask from flask_ask import Ask, statement, question, session import json import requests import time import unidecode app = Flask(__name__) ask = Ask(app, "/reddit_reader") def get_headlines(): titles = 'is this working' return titles @app.route('/') def homepage(): return "hi there, how ya doin?" @ask.launch def start_skill(): welcome_message = 'Hello there, would you like the news?' return question(welcome_message) @ask.intent("YesIntent") def share_headlines(): headlines = get_headlines() headline_msg = 'The current world news headlines are {}'.format(headlines) return statement(headline_msg) @ask.intent("NoIntent") def no_intent(): bye_text = 'I am not sure why you asked me to run then, but okay... bye' return statement(bye_text) if __name__ == '__main__': app.run(debug=True) The code runs fine on my machine and returns the correct output if I print it out. But the skill gives a HTTP 500 internal error when I deploy it on amazon using ngrok. I get the same 500 internal error both in the text as well as json simulator in the development console. This is my intent schema: { "intents": [ { "intent": "YesIntent" }, { "intent": "NoIntent" } ] } I get the following error in my python prompt: AttributeError: module 'lib' has no attribute 'X509V3_EXT_get The stacktrace is as follows: Traceback (most recent call last): File "C:\Python36\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_r…
tagged with: ngrok
has answer: http://stackoverflow.com/a/61585718
tagged with: python
has comment: http://stackoverflow.com/comment/85751636
has title: Alexa Skill Development using flask-ask and ngrok
answer count: 4
upvote count: 11
type: Question
has comment: http://stackoverflow.com/comment/85751846
has comment: http://stackoverflow.com/comment/85752010
possible better answer: http://stackoverflow.com/a/54697430
has comment: http://stackoverflow.com/comment/85752412

http://stackoverflow.com/comment/85893965
has text: running that line produces the same error - "WebDriverException: Message: unknown error: call function result missing 'value'."
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49437509
type: Comment

http://stackoverflow.com/comment/85631127
has text: @jarmod, I have already implemented the sophisticated solution for the links on s3. I am creating URL limited by time and restricted by user's IP address. My issue - how to create an archive file in lambda function and don't overhead time and memory limits.. or use any service for this.
comment on: http://stackoverflow.com/q/49309147
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85881741
comment on: http://stackoverflow.com/a/49439685
type: AnswerComment
has text: Thanks Simon, I changed it. My first post. ;-)
score: 1
type: Comment

http://stackoverflow.com/q/49404977
has title: PyQt5 QDateEdit() undo
tagged with: pyqt
answer count: 1
has comment: http://stackoverflow.com/comment/85831418
tagged with: pyqt5
tagged with: qt
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49405163
has body: In a hotel booking system, I have a couple of QDateEdit fields mapped to a database record in my form. After the user updates any of these fields, the program makes a check to ensure that the room is available. If the room is not available, I would like to restore the QDateEdit to its original value and let the user know with a QMessageBox. QLineEdit has an undo method which works as I intend. Furthermore, if I try to reset the QDateEdit by pulling the information from the model, it triggers the dateChanged signal again. This isn't a huge problem as I know the original value is valid but seems wasteful to me. How can I undo a change to a QDateEdit without generating the dateChanged signal? import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Guest_form(QDialog): def __init__(self, parent=None): QDialog.__init__(self) self.date_good = True self.date_edit = QDateEdit() self.line_edit = QLineEdit() layout = QVBoxLayout() layout.addWidget(self.date_edit) layout.addWidget(self.line_edit) self.setLayout(layout) self.date_edit.setFocus() self.date_edit.dateChanged.connect(self.check_date) self.line_edit.editingFinished.connect(self.check_date) def check_date(self): self.line_edit.setText(self.date_edit.date().toString()) self.date_good = False #self.date_edit.undo() #How? self.date_edit.setDate(QDate.currentDate()) self.line_edit.undo() print('here') if __name__=="__main__": app=QApplication(sys.argv) myapp = Guest_form() myapp.show() sys.exit(app.exec_())
tagged with: python
has comment: http://stackoverflow.com/comment/85811092
type: Question
has comment: http://stackoverflow.com/comment/85853025
accepted answer: http://stackoverflow.com/a/49405163

http://stackoverflow.com/a/49286071
has body: In your code the main function is nothing more than a regular function named main. So if you're asking if you can use return in your main function, then absolutely yes. You most certainly can
score: 8
has comment: http://stackoverflow.com/comment/85575351
has comment: http://stackoverflow.com/comment/85575322
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85575391
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49286011
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/85575274
has comment: http://stackoverflow.com/comment/85575525
answers question: http://stackoverflow.com/q/49286011

http://stackoverflow.com/comment/85643771
comment on: http://stackoverflow.com/a/49320897
type: AnswerComment
score: 1
type: Comment
has text: Thinking a bit further, it seems reasonable that django default form fields and/or widgets do not support nested arrays. You would have to create your own formfield/widget to handle your `schedule` field. Can you tell me your version of Django? I will try to write such widget to complete my answer.

http://stackoverflow.com/q/49378857
tagged with: python
has comment: http://stackoverflow.com/comment/85758452
has title: What happens to the Django admin site during production?
has answer: http://stackoverflow.com/a/49379519
tagged with: security
downvote count: 0
has comment: http://stackoverflow.com/comment/85759198
has comment: http://stackoverflow.com/comment/85759001
has comment: http://stackoverflow.com/comment/85758310
answer count: 1
has comment: http://stackoverflow.com/comment/85758356
has comment: http://stackoverflow.com/comment/85789998
has body: Django offers an admin interface at /admin. Is it not safe to keep this URL during production? Or should I change the URL to /d0oai32492384h24ui234nij23n4k2jnkjnkjn or something?
favorite count: 0
score: 9
type: Question
upvote count: 9
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django

input
tags question: http://stackoverflow.com/q/49331391
tags question: http://stackoverflow.com/q/49407702
tags question: http://stackoverflow.com/q/49350870
tags question: http://stackoverflow.com/q/49319667
tags question: http://stackoverflow.com/q/49284175
tags question: http://stackoverflow.com/q/49338078
tags question: http://stackoverflow.com/q/49348544
tag name: input
tags question: http://stackoverflow.com/q/49324828
tags question: http://stackoverflow.com/q/49324899
tags question: http://stackoverflow.com/q/49352561
type: Tag
tags question: http://stackoverflow.com/q/49350510

http://stackoverflow.com/a/49727366
accepted answer of: http://stackoverflow.com/q/49382024
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49382024
type: Answer
has body: Used python-3.6.4 in runtime.txt everything started working.
score: 0

http://stackoverflow.com/comment/85814725
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49405133
has text: Thanks, I tried doing that. However, the issue is everything works fine just before rendering. Consider this code I did (posted in the original post)
type: AnswerComment

http://stackoverflow.com/q/49370879
has answer: http://stackoverflow.com/a/49371307
tagged with: grid-search
has title: Python and HyperOpt: How to make multi-process grid searching?
tagged with: python
has answer: http://stackoverflow.com/a/49660963
upvote count: 6
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/49371100
type: UnansweredQuestion
downvote count: 0
score: 6
has body: I am trying to tune some params and the search space is very large. I have 5 dimensions so far and it will probably increase to about 10. The issue is that I think I can get a significant speedup if I can figure out how to multi-process it, but I can't find any good ways to do it. I am using hyperopt and I can't figure out how to make it use more than 1 core. Here is the code that I have without all the irrelevant stuff: from numpy import random from pandas import DataFrame from hyperopt import fmin, tpe, hp, Trials def calc_result(x): huge_df = DataFrame(random.randn(100000, 5), columns=['A', 'B', 'C', 'D', 'E']) total = 0 # Assume that I MUST iterate for idx_and_row in huge_df.iterrows(): idx = idx_and_row[0] row = idx_and_row[1] # Assume there is no way to optimize here curr_sum = row['A'] * x['adjustment_1'] + \ row['B'] * x['adjustment_2'] + \ row['C'] * x['adjustment_3'] + \ row['D'] * x['adjustment_4'] + \ row['E'] * x['adjustment_5'] total += curr_sum # In real life I want the total as high as possible, but for the minimizer, it has to negative a negative value total_as_neg = total * -1 print(total_as_neg) return total_as_neg space = {'adjustment_1': hp.quniform('adjustment_1', 0, 1, 0.001), 'adjustment_2': hp.quniform('adjustment_2', 0, 1, 0.001), 'adjustment_3': hp.quniform('adjustment_3', 0, 1, 0.001), 'adjustment_4': hp.quniform('adjustment_4', 0, 1, 0.001), 'adjustment_5': hp.quniform('adjustment_5', 0, 1, 0.001)} trials = Trials() best = fmin(fn = calc_result, space = space, algo = tpe.suggest, max_evals = 20000, trials = trials) As of now, I have 4 cores but I can basically get as many as I need. How can I get hyperopt to use more than 1 core, or is there a library that can multiprocess?
tagged with: machine-learning
tagged with: hyperparameters
favorite count: 0
has answer: http://stackoverflow.com/a/61151880
tagged with: pandas

http://stackoverflow.com/q/49409446
has body: I am asking a kind of generalisation of this question: Best way to extract elements from nested lists. It is also somehow related to these questions: recursive function for extract elements from deep nested lists/tuples Scheme - find most deeply values nested lists Scheme - find most deeply nested lists Essentially, I have some arbitrary nested list structure, where at the bottom there are various numpy arrays that are all the same shape. I want to iterate or slice all these bottom-level arrays whilst preserving the nested list structure in which they live. It is this part about preserving the nested structure in the output which doesn't seem to be answered in these other questions. So, for example: A = np.ones((3,3,3)) nest = [[A,A,A],[[A,A,[A,A]],[A,A]],A] and we want, schematically, nest[0,...] == [[A[0,...],A[0,...],A[0,...]],[[A[0,...],A[0,...],[A[0,...],A[0,...]]],[A[0,...],A[0,...]]],A[0,...]] or nest[1:3,5,:] == [[A[1:3,5,:],A[1:3,5,:],A[1:3,5,:]],[[A[1:3,5,:],A[1:3,5,:],[A[1:3,5,:],A[1:3,5,:]]],[A[1:3,5,:],A[1:3,5,:]]],A[1:3,5,:]] I'm sure some clever recursive function or something can do this, my brain is just not coming up with it right now... I guess it would also be best if this returns views onto the bottom level arrays rather than copies parts of them. edit: Perhaps something like this can work: https://stackoverflow.com/a/43357135/1447953. That method would require that numpy slicing operations be converted into functions somehow, which I guess can be done on a case-by-case basis, so perhaps this is the way to go.
linked to: http://stackoverflow.com/q/30060970
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49515317
tagged with: python
has title: Extract elements from arrays in deeply nested lists, preserving list structure
has answer: http://stackoverflow.com/a/49410254
linked to: http://stackoverflow.com/q/49247894
tagged with: recursion
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/85827138
upvote count: 3
has answer: http://stackoverflow.com/a/49413478
downvote count: 0
linked to: http://stackoverflow.com/q/8389649
linked to: http://stackoverflow.com/q/8355428
favorite count: 0
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/27029300

http://stackoverflow.com/q/49401840
has body: I am trying to create a new Model using the django-ldapdb library. When I try to run python manage.py makemigrations, it tells me that the bytes mode is off. I do not really know where this is and how to activate it. This is my model: class LdapUser(ldapdb.models.Model): base_dn = "CN=XXX,CN=Users,DC=domain,DC=com" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) I looked it up, but could not find anything helpful. I hope someone can help me. Thanks in advance.
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/49403452
tagged with: ldap
tagged with: python-2.7
score: 0
has title: TypeError: All provided fields *must* be text when bytes mode is off; got 'CN=XXX,CN=Users,DC=domain,DC=com'
answer count: 1
type: Question

http://stackoverflow.com/a/49294130
type: Answer
answers question: http://stackoverflow.com/q/49293962
downvote count: 0
upvote count: 1
score: 1
has body: I have found some answer for Python: First check where the global packages are installed: Command: python -m site --user-site Output: /home/ubuntu/.local/lib/python2.7/site-packages Go to this directory and find the package you are looking for. Thereafter, we can use: pip show -f package_name This will show us some thing as follows: Entry-points: [console_scripts] syntribos = syntribos.runner:entry_point [oslo.config.opts] syntribos.config = syntribos.config:list_opts Then from here on, we can start debugging our scripts? e.g: [console_scripts] will be the entry point for the package. Is it fine? or is there more to it? And I am still looking for Node.

http://stackoverflow.com/q/49324889
has title: django - inlineformset - crispy - how to display non_field_errors
score: 0
answer count: 1
type: Question
tagged with: inline-formset
has body: I have the following CreateView class CreatePerson(CreateView): model=Person form_class=PersonForm def get_context_data(self, **kwargs): context = super(CreatePerson, self).get_context_data(**kwargs) if self.request.POST: context['address_formset'] = AddressInlineFormSet(self.request.POST) else: context['address_formset'] = AddressInlineFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['address_formset'] if formset.is_valid(): self.object = form.save() formset.instance = self.object formset.save() return super().form_valid(form) else: return self.render_to_response(self.get_context_data(form=form)) and the following form {% load static crispy_forms_tags %} ... {% csrf_token %} {% crispy form %} {{ address_formset.management_form }} {% for formset in address_formset %} {% crispy formset %} {% endfor %} ... How do I display the duplicate key error (occurred in the formset model) in the form? I have tried this way. form_errors = formset.errors return self.render_to_response(self.get_context_data(form=form,form_errors=form_errors)) and {{ form_errors }} which gives the following display in the form. [{}, {'__all__': ['Please correct the duplicate values below.']}] How do I render it in crispy way? Thanks
tagged with: django
tagged with: django-crispy-forms
tagged with: python
accepted answer: http://stackoverflow.com/a/49708733
has answer: http://stackoverflow.com/a/49708733
type: AnsweredQuestion

http://stackoverflow.com/a/49412784
answers question: http://stackoverflow.com/q/49412694
type: Answer
has body: Similar to @cᴏʟᴅsᴘᴇᴇᴅ's answer, but you can stay within Pandas with .select_dtypes(). This will attempt to do index-aligned division on any non-object dtypes. &gt;&gt;&gt; b.select_dtypes(exclude='object').div( ... a.select_dtypes(exclude='object')).combine_first(a) ... A B Group 0 7.0 4.0 group1 1 3.0 2.5 group1 2 2.2 2.0 group1 To retain column ordering: &gt;&gt;&gt; desired_output = b.select_dtypes(exclude='object')\ ... .div(a.select_dtypes(exclude='object'))\ ... .combine_first(a)[a.columns] &gt;&gt;&gt; desired_output Group A B 0 group1 7.0 4.0 1 group1 3.0 2.5 2 group1 2.2 2.0
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/q/49293962
tagged with: pip
upvote count: 1
has body: I want to debug some globally installed packages, both in Python as well as Node. I checked my environment variables in windows as well as on ubuntu, but could not find them declared in the environment variables. Firstly, how do I find their locations. Secondly, how do I know which file is executed when I call some globally declared package. e.g: For Node: grunt someFile.js For Python: syntribos someFiles.conf
has comment: http://stackoverflow.com/comment/85591035
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49294130
has comment: http://stackoverflow.com/comment/85590264
linked to: http://stackoverflow.com/q/5926672
type: UnansweredQuestion
tagged with: python
tagged with: node.js
has title: Where does the global packages get installed and how do they get executed in Python as well as Node?
tagged with: npm
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49400865
downvote count: 1
has title: Adding the name of the corresponding file to the plot in matplotlib
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85804189
has comment: http://stackoverflow.com/comment/85803166
tagged with: pandas
duplicate of: http://stackoverflow.com/q/517355
tagged with: matplotlib
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49400977
has body: I am new in Python (and in programming at all) and trying to build the program for .csv data analysis. I have multiple .csv files and for each of them I build a plot. How do I add the name of the corresponding file to the title of the plot? Thanks! Below is the coresponding part of the code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import glob for fName in glob.glob('*.csv'): df, loops = openF(fName) fig, ax = plt.subplots(1, 1) for i in range(loops): df.loc[df['loop']==i+1]'freq','phase'.plot(x='freq', y='phase', logx=True, ax=ax) ax.set_title('Phase/Freq'.format(fName)) ax.set_xlabel('Frequency, [Hz]') ax.set_ylabel('Phase, [rad]') plt.show()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49400977
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/517355

http://stackoverflow.com/q/49409550
score: 0
tagged with: mod-wsgi
has body: I am trying to use Bottle.py and mod_wsgi together but I am getting a strange error that I cannot fix. When I try to make a curl request ("curl http://localhost/myapi/hello1") I get the error: "ImportError: No module named server". However, if I take out the "import server" line in my app.wsgi file and try "curl http://localhost/myapi/hello2" it works just fine. I have tried adding to the WSGIPythonPath, WSGIDaemonProcess, etc. and nothing has worked. Does anyone see anything I may be doing wrong? Note: The "/usr/local/www/wsgi-script" path is successfully being added to sys.path, so that isn't the issue. I also do have a init.py file in the "/usr/local/www/wsgi-scripts" directory and the permissions are all 777. [root@my_vm httpd]# ls -lt /usr/local/www/wsgi-scripts/ total 8 -rwxrwxrwx. 1 root root 95 Mar 21 14:42 server.py -rwxrwxrwx. 1 root root 318 Mar 21 14:37 app.wsgi -rwxrwxrwx. 1 root root 0 Mar 20 19:53 __init__.py Using Versions: Apache/2.4.6 (Red Hat Enterprise Linux) Python 2.7.5 Bottle 0.12.9 /usr/local/www/wsgi-scripts/server.py import bottle from bottle import route @route('/hello1') def hello(): return "Hello World!" /usr/local/www/wsgi-scripts/app.wsgi import os import sys import bottle from bottle import route server_loc = "/usr/local/www/wsgi-scripts" if not server_loc in sys.path: sys.path.insert(0, server_loc) os.chdir(os.path.dirname(__file__)) print(sys.path) @route('/hello2') def hello(): return "Hello World!\n" import server application = bottle.default_app() /etc/httpd/conf.d/myapi.conf &lt;VirtualHost *:80&gt; ServerName localhost WSGIScriptAlias /myapi /usr/local/www/wsgi-scripts/app.wsgi &lt;Directory /usr/local/www/wsgi-scripts&gt; Require all granted &lt;/Directory&gt; &lt;/VirtualHost&gt; EDIT: Adding python traceback /etc/httpd/logs/error_log [Thu Mar 22 13:39:18.234573 2018] [core:notice] [pid 18172] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Thu Mar 22 13:39:29.628352 2018] [:error] [pid 18174] ['/usr/local/www/wsgi-sc…
tagged with: apache
answer count: 1
has comment: http://stackoverflow.com/comment/85837091
type: Question
tagged with: server
has title: Mod_wsgi Apache Bottle.py: Cannot import python module "server"
has comment: http://stackoverflow.com/comment/85861935
tagged with: python
tagged with: bottle
accepted answer: http://stackoverflow.com/a/50004865
has comment: http://stackoverflow.com/comment/85879318
has comment: http://stackoverflow.com/comment/85862312
has answer: http://stackoverflow.com/a/50004865
type: AnsweredQuestion

http://stackoverflow.com/q/49414737
has comment: http://stackoverflow.com/comment/85831468
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/85831818
has title: Kivy nested TabbedPanels unable to click on vertical tabs
has comment: http://stackoverflow.com/comment/85831701
tagged with: kivy-language
score: 0
has comment: http://stackoverflow.com/comment/85831877
answer count: 0
type: UnansweredQuestion
type: Question
has body: I am attempting to create a nested TabbedPanel layout (in essence, you could think of it like a Battleship grid if that simplifies things). I have accomplished obtaining the visual representation that I want, however the vertical tabs of the nested TabbedPanel widget are unable to be clicked. This may be due to the fact that it resides within the parent TabbedPanel widget, and this may be interfering with the ability to trigger the on_click (or similar) property of the tabs themselves. I have provided a bare-bones example below. I should also clarify that the content contained within the vertical tabs will dynamically change based on the selection of a different horizontal tab (along the top). Any insight would be much appreciated, thanks in advance! Python: import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.gridlayout import GridLayout from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition #Load kv file Builder.load_file('test.kv') class Main_Panel(Screen): pass class Nested_Panel(TabbedPanel): pass class MyScreenManager(ScreenManager): pass class TestingApp(App): def build(self): self.sm = MyScreenManager() return self.sm if __name__ == '__main__': TestingApp().run() kv: &lt;MyScreenManager&gt;: Main_Panel: name: 'main' &lt;Main_Panel&gt;: BoxLayout: orientation: 'vertical' padding: 20 spacing: 20 TabbedPanel: do_default_tab: False TabbedPanelItem: text: 'A' Nested_Panel: TabbedPanelItem: text: 'B' Nested_Panel: TabbedPanelItem: text: 'C' Nested_Panel: GridLayout: cols: 1 size_hint: 1, .1 Button: text: 'Quit App' on_release: app.stop() &lt;Nested_Panel&gt;: do_default_tab: False tab_pos: 'left_top' TabbedPanelItem: text: '1' TabbedPanelItem: text: '2' TabbedPanelItem: text: '3' TabbedPanelItem: text: '4' TabbedPanelItem: text: '5' TabbedPanelItem: text: '6'

http://stackoverflow.com/q/49392967
has answer: http://stackoverflow.com/a/49393075
has comment: http://stackoverflow.com/comment/85787980
type: Question
has body: if rounds == 20: response2 = input("Ok the game has now finished. I hope you had fun playing because I sure did. If you want, type 'restart' to play again.") if response2.lower() == "restart": start_game() elif playerpoints &gt;= 10: print("Wow you did quite well. Your score is " + str(playerpoints) (img = pygame.image.load('TrophyImage.png')) (pygame.init()) (size = (1000, 1000)) (screen = pygame.display.set_mode(size)) (done = False) (clock = pygame.time.Clock()) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill(WHITE) screen.blit(img,(0,0)) pygame.display.flip() clock.tick(60) pygame.quit() I've already defined the colors at the beginning of the code so they aren't the issue. I'm trying to load a picture of a trophy which I have saved. When I run this program, it says invalid syntax but doesn't highlight anything. The I beam pointer just goes to the "while not done" so I'm guessing therein lies the problem.
tagged with: python
has comment: http://stackoverflow.com/comment/85787702
score: 0
has title: Invalid Syntax coming up for while loop
tagged with: while-loop
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/49322320
has comment: http://stackoverflow.com/comment/85646628
score: 0
has body: You could get the output from systemctl by using subprocess.check_output() and parse it afterwards.
answers question: http://stackoverflow.com/q/49321549
has comment: http://stackoverflow.com/comment/85645803
type: Answer

http://stackoverflow.com/comment/85640406
comment on: http://stackoverflow.com/q/49319760
type: Comment
type: QuestionComment
has text: If anyone know this help
score: 0

http://stackoverflow.com/comment/85843207
comment on: http://stackoverflow.com/q/49399471
has text: Take your existing example, but change Matt to a QB. What are the groups, and why?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49282033
type: Question
possible better answer: http://stackoverflow.com/a/49282174
has answer: http://stackoverflow.com/a/49282174
has answer: http://stackoverflow.com/a/49282061
downvote count: 0
tagged with: python
has title: How to make a dummy column determining whether a column cell value is a duplicate?
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49282061
has answer: http://stackoverflow.com/a/49282253
has body: So, my data is travel data. I want to create a column df['user_type'] in which it'll determine if the df['user_id'] occurs more than once. If it does occur more than once, I'll list them as a frequent user. Here is my code below, but it takes way too long: #Column that determines user type def determine_user_type(val): df_freq = df[df['user_id'].duplicated()] user_type = "" if(val in df_freq['user_id'].values): user_type = "Frequent" else: user_type = "Single" return user_type df['user_type'] = df['user_id'].apply(lambda x: determine_user_type(x))
answer count: 3
tagged with: pandas
upvote count: 3
tagged with: duplicates
favorite count: 0

http://stackoverflow.com/comment/85741253
type: AnswerComment
score: 0
has text: maybe it's the version of python I have?
comment on: http://stackoverflow.com/a/49370152
type: Comment

http://stackoverflow.com/q/49434711
has answer: http://stackoverflow.com/a/49436005
has body: I was trying to overwrite SetPasswordForm to add a placeholder and a class but it seems that it is not working. I managed to do it for login page and password reset page but here I got stuck. class MySetPasswordForm(SetPasswordForm): new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={'placeholder': 'New Password', 'class': 'password1'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Repeat Password', 'class': 'password2'}), ) urlpatterns = [ path('accounts/password_reset/', auth_views.PasswordResetView.as_view( form_class=MyPasswordResetForm)), path('accounts/password_reset_confirm/', auth_views.PasswordResetConfirmView.as_view( form_class=MySetPasswordForm)), path('accounts/', include('django.contrib.auth.urls')),] Is this accurate ?
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49436005
type: Question
possible better answer: http://stackoverflow.com/a/55414713
has answer: http://stackoverflow.com/a/55414713
tagged with: django
tagged with: python
has title: Trying to customize the Django SetPasswordForm
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2

http://stackoverflow.com/a/57694832
type: Answer
answers question: http://stackoverflow.com/q/49311195
has body: Install Instead of the official version (which has issues with python 3) use an alternative one. Install it on your local machine, globally (i.e., outside any virtual environment). You can do this by: pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI Check if it is installed globally: pip freeze | grep "pycocotools" You should see something like pycocotools==2.0.0 in your output. Now, inside your virtual-env (conda or whatever), first install numpy and cython (and maybe setuptools if it's not installed) using pip, and then: pip install pycocotools Verify Inside your project, import (for example) from pycocotools import mask as mask and then print(mask.__author__). This should print out the author's name, which is tsungyi. Where Is It? The installed package, like any other packages that are locally installed inside a virtual-env using pip, will go to External Libraries of your project, under site-packages. That means it is now part of your virtual-env and not part of your project. So, other users who may want to use your code, must repeat this installation on their virtual-env as well. Troubleshooting: The main source of confusion is that either you did not install the required packages before installing cocoapi, or you did install the required packages but for a different python version. And when you want to check if something is installed, you may check with, for instance, python3.6 and see that it exists, but you are actually running all your commands with python3.7. So suppose you are using python3.7. You need to make sure that: python -V gives you python3.7 and NOT other version, and pip -V gives you pip 19.2.3 from /home/&lt;USER&gt;/.local/lib/python3.7/site-packages/pip (python3.7), that actually matches with your default python version. If this is not the case, you can change your default python using sudo update-alternatives --config python, and following the one-step instruction. All the required packages are installed usin…
downvote count: 0
score: 5
upvote count: 5

http://stackoverflow.com/a/51142648
has comment: http://stackoverflow.com/comment/96308231
type: Answer
answers question: http://stackoverflow.com/q/49395819
has comment: http://stackoverflow.com/comment/93596523
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49395819
score: 6
upvote count: 7
has comment: http://stackoverflow.com/comment/119903990
downvote count: 1
has body: I had this similar problem in windows 10... Solution: Download win-64/intel-openmp-2018.0.0-8.tar.bz2 from https://anaconda.org/anaconda/intel-openmp/files Extract it and put the dll files in Library\bin into C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin Make sure your cuda directory is added to your %PATH% environment variable
has comment: http://stackoverflow.com/comment/94803386
has comment: http://stackoverflow.com/comment/101285352

http://stackoverflow.com/q/49417648
has title: Tweepy 401 error in python due to server time difference
linked to: http://stackoverflow.com/q/28412683
answer count: 1
tagged with: twitter
has comment: http://stackoverflow.com/comment/85837175
type: Question
has body: I am trying to retrieve Twitter data using Tweepy, using that below code, but it returns 401 error, and I regenerated the access and secret tokens but didnt make a difference #Import the necessary methods from tweepy library from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream #Variables that contains the user credentials to access Twitter API access_token = "ENTER YOUR ACCESS TOKEN" access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET" consumer_key = "ENTER YOUR API KEY" consumer_secret = "ENTER YOUR API SECRET" #This is a basic listener that just prints received tweets to stdout. class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == '__main__': #This handles Twitter authetification and the connection to Twitter Streaming API l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) #This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby' stream.filter(track=['python', 'javascript', 'ruby']) The code is available here I know for a fact that all the other things in the code are right and there are no syntax or authentication error. I read in an answer for the question that 401 error is also because of server-client time difference. My question is: To what do I set my system time to overcome this error? Or in other words how do I know the server time so as to change my system time?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49458971
tagged with: python
tagged with: tweepy
tagged with: http-status-code-401
score: 0

http://stackoverflow.com/a/49361098
score: 0
has comment: http://stackoverflow.com/comment/85722408
answers question: http://stackoverflow.com/q/49361038
has comment: http://stackoverflow.com/comment/85722422
has body: Python is case sensitive. Use this: from textblob import TextBlob tweet = TextBlob(tweet) python != vba
has comment: http://stackoverflow.com/comment/85722435
type: Answer
has comment: http://stackoverflow.com/comment/85722375

http://stackoverflow.com/comment/85626934
score: 0
has text: yes, i was just doing both.Trying
comment on: http://stackoverflow.com/q/49311845
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85787712
type: Comment
type: QuestionComment
has text: @Greesha0 Yes, that's right
score: 0
comment on: http://stackoverflow.com/q/49392795

http://stackoverflow.com/comment/85740348
type: QuestionComment
comment on: http://stackoverflow.com/q/49369629
has text: Your threads are each trying to just do what your non-thread part does. And your threads are trying to write to the same file, my guess thread 1 is writing and the rest of the threads have to wait for it to finish, then thread 2, etc
score: 1
type: Comment

http://stackoverflow.com/q/49400208
accepted answer: http://stackoverflow.com/a/49401517
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/49401517
has title: Is there something like onFirendRequestAccepted?
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm starting to work with discord API via discord.py module. I've been through docs, but I've not found anything like this. So, here's the question: Is there some event trigger like onFirendRequestAccepted which runs the function when someone accept your friend request?
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: discord.py
score: 1

http://stackoverflow.com/q/49436590
has body: This is a follow-up on this question I have two dataframes that I want to merge, but I want to avoid to have duplicate columns, so I'm doing: cols_to_use = df2.columns-df1.columns If I print cols_to_use I get this: Index([col1,col2,col3...],dtype=object) However, I have one column that I need it to be kept in both dfs, it is the co_code. That's because I'm going to merge on that column. My question is: how to add one extra column to cols_to_use? I need it to look like this: Index([co_code,col1,col2,col3...],dtype=object) I tried different synthaxes but nothing seemed to work: cols_to_use = df2.columns-df1.columns+'co_code' cols_to_use = df2.columns-df1.columns+['co_code'] cols_to_use = df2.columns-df1.columns+df2['co_code'].columns
favorite count: 0
type: Question
answer count: 2
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49436642
linked to: http://stackoverflow.com/q/19125091
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49436618
has answer: http://stackoverflow.com/a/49436642
downvote count: 0
has answer: http://stackoverflow.com/a/49436618
has title: Merge avoiding duplicate columns but keeping only one duplicate

http://stackoverflow.com/comment/85742298
has text: @ITiger Each epoch takes around 7-8 minutes on my system how will I be able to run 500? And there is nothing wrong with my code right?
score: 0
comment on: http://stackoverflow.com/q/49357582
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49431823
type: Answer
answers question: http://stackoverflow.com/q/49430785
has body: You can use scipy.special.xlogy. For example, In [10]: import numpy as np In [11]: from scipy.special import xlogy Create some data: In [12]: y_true = np.random.randint(1, 10, size=(8, 200, 200)) In [13]: y_pred = np.random.randint(1, 10, size=(8, 200, 200)) Compute the result using xlogy: In [14]: -xlogy(y_true, y_pred).sum(axis=(1, 2)) Out[14]: array([-283574.67634307, -283388.18672431, -284720.65206688, -285517.06983709, -286383.26148469, -282200.33634505, -285781.78641736, -285862.91148953]) Verify the result by computing it with your function: In [15]: categorical_cross_entropy(y_true, y_pred) Out[15]: array([-283574.67634309, -283388.18672432, -284720.65206689, -285517.0698371 , -286383.2614847 , -282200.33634506, -285781.78641737, -285862.91148954]) If you don't want the dependence on scipy, you can do the same thing with np.log, but you might get a warning if any value in y_pred is 0: In [20]: -(y_true*np.log(y_pred)).sum(axis=(1, 2)) Out[20]: array([-283574.67634307, -283388.18672431, -284720.65206688, -285517.06983709, -286383.26148469, -282200.33634505, -285781.78641736, -285862.91148953])
accepted answer of: http://stackoverflow.com/q/49430785
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49321790
type: AcceptedAnswer
has body: The reason you're getting this error is that you're assigning an instance method from A to B's __exit__, this results in too many arguments because you're passing the instance again with exit: exit(mgr, None, None, None), and it being a bound method, it will append the instance again resulting in too many arguments. Hence, you can get rid of mgr argument from the exit calls. Based on your code: In [21]: B.__exit__.__self__ Out[21]: &lt;__main__.A at 0x110bb65d0&gt; In [22]: A.__exit__.__self__ Out[22]: None
accepted answer of: http://stackoverflow.com/q/49321567
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49321567
downvote count: 0

http://stackoverflow.com/comment/85881655
type: AnswerComment
has text: That system mod_wsgi was still installed, or that ``WSGIPythonHome`` didn't have correct path?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49438521

if-statement
tags question: http://stackoverflow.com/q/49282686
tags question: http://stackoverflow.com/q/49433777
tags question: http://stackoverflow.com/q/49295620
tags question: http://stackoverflow.com/q/49304494
tag name: if-statement
tags question: http://stackoverflow.com/q/49414434
tags question: http://stackoverflow.com/q/49422442
type: Tag
tags question: http://stackoverflow.com/q/49417023
tags question: http://stackoverflow.com/q/49389920
tags question: http://stackoverflow.com/q/49384368
tags question: http://stackoverflow.com/q/49289685
tags question: http://stackoverflow.com/q/49421449
tags question: http://stackoverflow.com/q/49348469
tags question: http://stackoverflow.com/q/49437777
tags question: http://stackoverflow.com/q/49309862
tags question: http://stackoverflow.com/q/49316345
tags question: http://stackoverflow.com/q/49349200
tags question: http://stackoverflow.com/q/49374819
tags question: http://stackoverflow.com/q/49416871
tags question: http://stackoverflow.com/q/49332044
tags question: http://stackoverflow.com/q/49437751

http://stackoverflow.com/comment/85727200
type: AnswerComment
has text: Well, it does not get stuck now... But the problem is different now... I've checked if there's connection between MITM machine and both endpoints, each from a different interface, ant indeed, there is. But, when I try to ping from one endpoint to the other, it does not work. I can see by x.summary() that ARP requests are being sent, but no responses nor ICMP packets are shown...
comment on: http://stackoverflow.com/a/49325167
type: Comment
score: 0

http://stackoverflow.com/comment/85707094
comment on: http://stackoverflow.com/a/49353274
score: 0
type: Comment
has text: In what way is it failing?
type: AnswerComment

scikit-learn
tags question: http://stackoverflow.com/q/49398255
tags question: http://stackoverflow.com/q/49282889
tags question: http://stackoverflow.com/q/49365009
tags question: http://stackoverflow.com/q/49347738
tags question: http://stackoverflow.com/q/49342218
tags question: http://stackoverflow.com/q/49428870
tags question: http://stackoverflow.com/q/49420191
tags question: http://stackoverflow.com/q/49300212
tags question: http://stackoverflow.com/q/49300193
tags question: http://stackoverflow.com/q/49386389
tags question: http://stackoverflow.com/q/49307047
tags question: http://stackoverflow.com/q/49375609
tag name: scikit-learn
tags question: http://stackoverflow.com/q/49371486
tags question: http://stackoverflow.com/q/49293905
tags question: http://stackoverflow.com/q/49314988
tags question: http://stackoverflow.com/q/49323857
tags question: http://stackoverflow.com/q/49381661
tags question: http://stackoverflow.com/q/49321083
tags question: http://stackoverflow.com/q/49289187
tags question: http://stackoverflow.com/q/49324767
tags question: http://stackoverflow.com/q/49282800
tags question: http://stackoverflow.com/q/49355804
tags question: http://stackoverflow.com/q/49391637
tags question: http://stackoverflow.com/q/49346045
tags question: http://stackoverflow.com/q/49437136
type: Tag
tags question: http://stackoverflow.com/q/49298542
tags question: http://stackoverflow.com/q/49422283
tags question: http://stackoverflow.com/q/49341132
tags question: http://stackoverflow.com/q/49353916
tags question: http://stackoverflow.com/q/49438764
tags question: http://stackoverflow.com/q/49432083
tags question: http://stackoverflow.com/q/49394654
tags question: http://stackoverflow.com/q/49307967
tags question: http://stackoverflow.com/q/49340540
tags question: http://stackoverflow.com/q/49352416
tags question: http://stackoverflow.com/q/49328229
tags question: http://stackoverflow.com/q/49336649
tags question: http://stackoverflow.com/q/49429160
tags question: http://stackoverflow.com/q/49400413
tags question: http://stackoverflow.com/q/49428469
tags question: http://stackoverflow.com/q/49393946
tags question: http://stackoverflow.com/q/49380998
tags question: http://stackoverflow.com/q/49383083
tags question: http://stackoverflow.com/q/49318813
tags question: http://stackoverflow.com/q/49398834
tags question: http://stackoverflow.com/q/49416716
tags question: http://stackoverflow.com/q/49283341
tags question: http://stackoverflow.com/q/49345578
tags question: http://stackoverflow.com/q/49339350
tags question: http://stackoverflow.com/q/49280675
tags question: http://stackoverflow.com/q/49368361
tags question: http://stackoverflow.com/q/49311064
tags question: http://stackoverflow.com/q/49333249
tags question: http://stackoverflow.com/q/49375927
tags question: http://stackoverflow.com/q/49403678
tags question: http://stackoverflow.com/q/49293443
tags question: http://stackoverflow.com/q/49437487
tags question: http://stackoverflow.com/q/49328243
tags question: http://stackoverflow.com/q/49351616
tags question: http://stackoverflow.com/q/49420274
tags question: http://stackoverflow.com/q/49382403
tags question: http://stackoverflow.com/q/49291593
tags question: http://stackoverflow.com/q/49381027
tags question: http://stackoverflow.com/q/49352302
tags question: http://stackoverflow.com/q/49305149
tags question: http://stackoverflow.com/q/49296167
tags question: http://stackoverflow.com/q/49433462
tags question: http://stackoverflow.com/q/49391855
tags question: http://stackoverflow.com/q/49337960
tags question: http://stackoverflow.com/q/49330195
tags question: http://stackoverflow.com/q/49329403
tags question: http://stackoverflow.com/q/49386581
tags question: http://stackoverflow.com/q/49332590
tags question: http://stackoverflow.com/q/49353243

selenium-webdriver
tags question: http://stackoverflow.com/q/49283265
tags question: http://stackoverflow.com/q/49344994
tags question: http://stackoverflow.com/q/49322696
tags question: http://stackoverflow.com/q/49436756
tags question: http://stackoverflow.com/q/49325855
tags question: http://stackoverflow.com/q/49297380
tags question: http://stackoverflow.com/q/49352180
tags question: http://stackoverflow.com/q/49375222
tags question: http://stackoverflow.com/q/49387548
tags question: http://stackoverflow.com/q/49406625
tags question: http://stackoverflow.com/q/49329719
tags question: http://stackoverflow.com/q/49418185
tags question: http://stackoverflow.com/q/49289709
tags question: http://stackoverflow.com/q/49384229
tags question: http://stackoverflow.com/q/49292221
tags question: http://stackoverflow.com/q/49435873
tags question: http://stackoverflow.com/q/49386564
tags question: http://stackoverflow.com/q/49303798
tags question: http://stackoverflow.com/q/49345497
tags question: http://stackoverflow.com/q/49322891
tags question: http://stackoverflow.com/q/49422023
tags question: http://stackoverflow.com/q/49387871
tags question: http://stackoverflow.com/q/49309668
tags question: http://stackoverflow.com/q/49396106
tags question: http://stackoverflow.com/q/49354201
type: Tag
tags question: http://stackoverflow.com/q/49379075
tags question: http://stackoverflow.com/q/49403203
tags question: http://stackoverflow.com/q/49347498
tags question: http://stackoverflow.com/q/49323099
tags question: http://stackoverflow.com/q/49359146
tags question: http://stackoverflow.com/q/49372642
tags question: http://stackoverflow.com/q/49355434
tags question: http://stackoverflow.com/q/49424277
tags question: http://stackoverflow.com/q/49417445
tags question: http://stackoverflow.com/q/49411184
tags question: http://stackoverflow.com/q/49378655
tags question: http://stackoverflow.com/q/49291304
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/49321748

svd
type: Tag
tag name: svd
tags question: http://stackoverflow.com/q/49355804

http://stackoverflow.com/a/49388455
has body: If you take a look at the page source, the contains the following HTML: Everything else are the tags (JavaScript). This website is heavily driven by JavaScript. That is, all the other contents are added dynamically. As you can see, there is no div tag with class="row nr-p-0 nr-mb-10" in the page source (which is what requests.get(...) returns). This is why, price_container is an empty list. You need to use other tools like Selenium to scrape this page.
type: Answer
answers question: http://stackoverflow.com/q/49388091
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49388091

http://stackoverflow.com/comment/85633651
type: Comment
type: QuestionComment
has text: `\x` indicates Hexadecimal.
comment on: http://stackoverflow.com/q/49315547
score: 0

http://stackoverflow.com/comment/85624531
score: 0
has text: However, you don't need to call out to `ls` to get a list of files; use `os.listdir` for that.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49311270

http://stackoverflow.com/a/49349672
has comment: http://stackoverflow.com/comment/85699636
has body: MySQLdb doesn’t support Python 3. Try using an alternative MySQL Python package. I successfully used MySQL Connector Python, specifically http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip with Python 3 — have a look at the latest version and the usage documentation. pip install http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip then import mysql.connector Using the latest version available (I believe 2.1.7).
has comment: http://stackoverflow.com/comment/85699115
type: Answer
has comment: http://stackoverflow.com/comment/85699386
has comment: http://stackoverflow.com/comment/85699518
has comment: http://stackoverflow.com/comment/85699162
accepted answer of: http://stackoverflow.com/q/49349329
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85699093
has comment: http://stackoverflow.com/comment/85699698
answers question: http://stackoverflow.com/q/49349329
has comment: http://stackoverflow.com/comment/85699262
has comment: http://stackoverflow.com/comment/85699580
has comment: http://stackoverflow.com/comment/85699346
upvote count: 5
has comment: http://stackoverflow.com/comment/85699139
score: 5

http://stackoverflow.com/q/49298892
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Saving Excel sheet from python using xlwings
tagged with: python
has body: I use a propriety addin in Excel to calculate financial maths functions. I would like to save the results in a csv file for further manipulation. How do I save Sheet2 as mytestfile.csv and then save and close Excel? wb = xw.Book(path1 + "1VALVBA.xlsm") wb.app.api.RegisterXLL("C:/Windows/System32/vsoft15.xll")`enter code here` # activate addin wb.macro("ScreenASX1")() # Run the VBA in Excel. Results appear in Sheet2 sheet = wb.sheets['Sheet2']
tagged with: xlwings

python-jira
tags question: http://stackoverflow.com/q/49436308
tags question: http://stackoverflow.com/q/49396670
tag name: python-jira
type: Tag

http://stackoverflow.com/comment/85582688
type: Comment
has text: he should change it to `loading_choose.title()` this will capitalise the first letter which is what the options are..
type: AnswerComment
comment on: http://stackoverflow.com/a/49288134
score: 0

http://stackoverflow.com/q/49364859
score: 3
has comment: http://stackoverflow.com/comment/85730371
answer count: 2
has comment: http://stackoverflow.com/comment/85730959
has answer: http://stackoverflow.com/a/49365190
downvote count: 1
accepted answer: http://stackoverflow.com/a/49365190
has title: Exception propagation in python
has comment: http://stackoverflow.com/comment/85752790
has comment: http://stackoverflow.com/comment/85730305
has comment: http://stackoverflow.com/comment/85736423
favorite count: 0
has comment: http://stackoverflow.com/comment/85753204
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85730188
has comment: http://stackoverflow.com/comment/85752990
tagged with: exception
has body: My application uses a third party API that throws an exception belonging to another api-handling module. The code looks something like this: #API Module def getdatafromapi(req): # Trying to get data ... if response_err in data: raise APIModuleException('API error') if conn_err in data: raise APIConnectionError('API error') # Do some processing return response # My Module def get_data_and_crunch(req): response = getdatafromapi(req) if not response: raise ValueError('Something happened') # Proceed to number crunch # Main script def main(): # Sanitize api request... try: get_data_and_crunch(req) except ValueError: print('Something happened') The main module behaves the same way no matter if APIModuleException or APIConnectionError occurs, but I would still like to log which exception class actually caused the exception. Is there a way I could avoid having APIModuleException and APIConnectionError classes in my main script and still propagate the exceptions up just using ValueError to tell which exception class actually caused the exception in the API Module?
possible better answer: http://stackoverflow.com/a/49365107
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/49365107
type: AnsweredQuestion

http://stackoverflow.com/q/49312650
has answer: http://stackoverflow.com/a/49312690
has answer: http://stackoverflow.com/a/49312700
has title: Creating Dictionary from Pandas DataFrame Column Based on Unique Values in Column
tagged with: dataframe
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85627186
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49312700
possible better answer: http://stackoverflow.com/a/49312690
score: 0
answer count: 2
tagged with: pandas
has body: I've got a head-scratcher that I'm not sure can be solved in one or two lines of code, which I'm trying. I can more or less do it without a dataframe (e.g., if the data is simply .txt), but I want to see if it can be done with pandas. Below is the df.head(10), and I want to create a dictionary in which the keys are the parsed unique day_of_week numericals (1-7, for Sunday-Saturday) and the values are the sum of the births that occur on each of the individual day_of_week values. year month date_of_month day_of_week births 0 1994 1 1 6 8096 1 1994 1 2 7 7772 2 1994 1 3 1 10142 3 1994 1 4 2 11248 4 1994 1 5 3 11053 5 1994 1 6 4 11406 6 1994 1 7 5 11251 7 1994 1 8 6 8653 8 1994 1 9 7 7910 9 1994 1 10 1 10498 I can create the SUM for respective day_of_week values easily with: df.groupby[df['day_of_week'] == 1, 'births'].sum() which sums all the births that occur on day_of_week == 1. And I can create a dictionary of the day_of_week values with: d = {i : 0 for i in df['day_of_week']} which yeilds a dictionary, d: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0} But I cannot connect the two so that I can parse the day_of_week numbers, assign those numbers to the key of a dictionary, then sum the births that occur on each respective day_of_week, then assign those sum values to their respective keys. If anyone has suggestions! I've created a dummy dataframe below that replicates the conditions, if that helps, since the day_of_week values do repeat in my dataframe (though you can't tell from df.head()). d = {'day_of_week' : pd.Series([1, 6, 6, 5, 3, 2, 6, 4, 4, 7, 1]), 'births' : pd.Series([5544, 23456, 473, 34885, 3498, 324, 6898, 83845, 959, 8923, 39577])} df_dummy = pd.DataFrame(d)
type: Question
tagged with: numpy

http://stackoverflow.com/a/49419933
accepted answer of: http://stackoverflow.com/q/49353023
downvote count: 0
answers question: http://stackoverflow.com/q/49353023
upvote count: 2
type: Answer
score: 2
has body: I was playing around with this myself and I found an answer that will work with win32com I used myRange._print_details_() to show what is accessible from the com object and I got the following: Methods: GetValue SetValue Props: Get Props: Value = 0x6 - &lt;win32com.client.build.MapEntry object at 0x00000184975AA160&gt; Put Props: Value = 0x6 - &lt;win32com.client.build.MapEntry object at 0x00000184975AA1D0&gt; So from I can tell Value is a proptery that allows you to get or set the value using myRange.value But there is also a GetValue and SetValue... So instead of myRange.Value(11).. you want to use: myRange.GetValue(11) # you can now pass the paramter to get xlRangeValueXMLSpreadsheet
type: AcceptedAnswer

http://stackoverflow.com/q/49317229
tagged with: contour
accepted answer: http://stackoverflow.com/a/49358804
has answer: http://stackoverflow.com/a/49331231
has answer: http://stackoverflow.com/a/49358804
type: Question
tagged with: opencv
has title: Crop phone screen using contour
possible better answer: http://stackoverflow.com/a/49331231
tagged with: python
has comment: http://stackoverflow.com/comment/85636260
type: AnsweredQuestion
score: 0
answer count: 2
has body: I want to crop phone screen given on the image. I tried this code but the result is not what i wanted. Phone Screen import cv2 import numpy as np img = cv2.imread('phone_test.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) _,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY) _, contours, _= cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) x,y,w,h = cv2.boundingRect(contours[0]) crop = img[y:y+h,x:x+w] cv2.imwrite('phone_test_crop.jpg',crop) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image',img) #show the image cv2.waitKey(0) The result would be just this Crop Result any solutions?

http://stackoverflow.com/comment/85844406
has text: FYI this wont work if input list is `a = [[1,1,2],[4,5],[8,9],[6,7]]`.
comment on: http://stackoverflow.com/a/49421402
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85794432
has text: See my explanation. Im sorry but i dont know how to fill the array with random circle labels or label areas at all
score: 0
comment on: http://stackoverflow.com/q/49396180
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49297430
has body: os.makedirs will recreate the directory hierarchy if you use e.g. os.makedirs("output/flower/rose")
score: 1
has comment: http://stackoverflow.com/comment/85596839
downvote count: 0
answers question: http://stackoverflow.com/q/49297363
upvote count: 1
has comment: http://stackoverflow.com/comment/85598059
type: Answer

http://stackoverflow.com/comment/85722768
has text: Yes, `suborder = ["B", "A", "C"]`, this is what the anwer does, right?
type: AnswerComment
comment on: http://stackoverflow.com/a/49360488
score: 0
type: Comment

http://stackoverflow.com/comment/85622595
has text: @CharlesDuffy correct, except the uid is the primary value extracted from my database, the user never sees, knows or defines his/her uid. But you're right so I'l use your suggestion and research how to use shell=False (it was just cause of laziness)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49310057

http://stackoverflow.com/comment/85805223
type: Comment
type: QuestionComment
score: 0
has text: I know but I run infinity loop, and if I do this in the main thread the program is gonna freezing, so I need a new thread. And in that infinity loop I have to add new element to the QListWidget
comment on: http://stackoverflow.com/q/49401730

pandas-groupby
tags question: http://stackoverflow.com/q/49324988
tags question: http://stackoverflow.com/q/49438025
tags question: http://stackoverflow.com/q/49426076
tags question: http://stackoverflow.com/q/49281663
tags question: http://stackoverflow.com/q/49391089
type: Tag
tags question: http://stackoverflow.com/q/49416548
tags question: http://stackoverflow.com/q/49439182
tags question: http://stackoverflow.com/q/49308330
tags question: http://stackoverflow.com/q/49407172
tags question: http://stackoverflow.com/q/49301242
tags question: http://stackoverflow.com/q/49284420
tags question: http://stackoverflow.com/q/49333494
tags question: http://stackoverflow.com/q/49336086
tags question: http://stackoverflow.com/q/49322597
tags question: http://stackoverflow.com/q/49356018
tags question: http://stackoverflow.com/q/49423186
tags question: http://stackoverflow.com/q/49348398
tags question: http://stackoverflow.com/q/49376488
tags question: http://stackoverflow.com/q/49286456
tags question: http://stackoverflow.com/q/49320935
tags question: http://stackoverflow.com/q/49290471
tags question: http://stackoverflow.com/q/49434712
tags question: http://stackoverflow.com/q/49382992
tags question: http://stackoverflow.com/q/49316012
tags question: http://stackoverflow.com/q/49352746
tags question: http://stackoverflow.com/q/49281423
tags question: http://stackoverflow.com/q/49297480
tags question: http://stackoverflow.com/q/49390300
tags question: http://stackoverflow.com/q/49395100
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/49390682
tags question: http://stackoverflow.com/q/49406669
tags question: http://stackoverflow.com/q/49288557
tags question: http://stackoverflow.com/q/49379689

http://stackoverflow.com/comment/97250558
comment on: http://stackoverflow.com/a/49413054
type: Comment
type: AnswerComment
score: 0
has text: @Johngoldenboy In the case you describe you would need a relationship between the units of both axes. If you have that, you can use a `xlim_changed` event and set the limits of the other axes.

http://stackoverflow.com/a/49403146
accepted answer of: http://stackoverflow.com/q/49401845
has comment: http://stackoverflow.com/comment/85809860
has comment: http://stackoverflow.com/comment/85807617
upvote count: 2
answers question: http://stackoverflow.com/q/49401845
type: AcceptedAnswer
downvote count: 0
has body: You can take help of dictionary: import re mbt_d = { "mn": "Million", "bn": "Billion", "tn": "Trillion", #include your needs. } dol_d = { "$": "dollar", #include your needs. } inputs = [ "Deal to invest $1000 mn in market.", "Deal to invest $10bn in market.", "Deal to invest $ 1tn in market." ] for s in inputs: res = re.findall(r"([£$€]\s?)(\d+)(\s?[mbt]n)", s)[0] s = s.replace(res[0], "") print(s.replace( res[2], " {} {}".format(mbt_d[res[2].strip()], dol_d[res[0].strip()]) )) out: Deal to invest 1000 Million dollar in market. Deal to invest 1000 Billion dollar in market. Deal to invest 1000 Trillion dollar in market.
score: 2
type: Answer

http://stackoverflow.com/comment/85872666
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49335599
has text: It's printing out `<module 'mods.submod1.submod2' from '..\mods\submod1\submod2\__init__.py'>` and I'm using Python 2.7.2 (can't change it as this is done by my job)
type: Comment

http://stackoverflow.com/comment/85690750
has text: if OP is worried about complexity he can check the wiki page on [time complexity for common python structures](https://wiki.python.org/moin/TimeComplexity)
comment on: http://stackoverflow.com/a/49345443
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85687285
comment on: http://stackoverflow.com/q/49343511
type: Comment
type: QuestionComment
has text: I could do, yes, but what if the number `num` change ? I would like to automatize it..
score: 0

http://stackoverflow.com/q/49401575
has answer: http://stackoverflow.com/a/49401682
favorite count: 0
possible better answer: http://stackoverflow.com/a/49401632
upvote count: 2
score: 2
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49401681
has body: Suppose the following code. try: some_code_1 except: # will it be called twice, if an error occures in finally? some_code_2 finally: some_code_3 Suppose an exception occurs in some_code_3. Do I need an extra try-except clause around some_code_3 (see below) or will the exception with some_code_2 be called again, which in principle could cause an infinite loop? Is this saver? try: some_code_1 except: # will it be called twice, if an error occures in finally? some_code_2 finally: try: some_code_3 except: pass
has comment: http://stackoverflow.com/comment/85804474
tagged with: except
tagged with: finally
has comment: http://stackoverflow.com/comment/85804459
linked to: http://stackoverflow.com/q/43586041
type: Question
has answer: http://stackoverflow.com/a/49401632
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49401681
tagged with: python
has title: Python: Does finally needs a try-except clause?

binary
tags question: http://stackoverflow.com/q/49384272
tags question: http://stackoverflow.com/q/49396718
tags question: http://stackoverflow.com/q/49315429
tag name: binary
tags question: http://stackoverflow.com/q/49397709
tags question: http://stackoverflow.com/q/49411721
tags question: http://stackoverflow.com/q/49391213
tags question: http://stackoverflow.com/q/49287398
tags question: http://stackoverflow.com/q/49401085
type: Tag

http://stackoverflow.com/q/49286313
has comment: http://stackoverflow.com/comment/85611807
tagged with: python
has comment: http://stackoverflow.com/comment/85609925
has comment: http://stackoverflow.com/comment/85598507
has comment: http://stackoverflow.com/comment/85612090
has comment: http://stackoverflow.com/comment/85612206
linked to: http://stackoverflow.com/q/6539944
has comment: http://stackoverflow.com/comment/85611404
has comment: http://stackoverflow.com/comment/90421694
has comment: http://stackoverflow.com/comment/85577031
answer count: 0
has comment: http://stackoverflow.com/comment/85610070
has comment: http://stackoverflow.com/comment/85598848
tagged with: matplotlib
score: 0
has comment: http://stackoverflow.com/comment/85576849
type: Question
has body: Currently I am trying to get a glimpse of how a certain value is depending from different input parameters. Thus I created a function in python with this parameters as input. Now I'd like to plot the result. I already managed to get a 3D plot, meaning 2 variables can be taken into consideration at once. I hope there are ways to extend this by using colors etc. Sample code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def calculation(v,w,x,y,z): return v+w+x+y+z #Part for 3D plotting so far: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x=np.arange(1, 10, 1) y=np.arange(1, 10, 1) X, Y = np.meshgrid(x, y) zs = np.array([calculation(1, 1, x, y, 1) for x,y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) ax.plot_surface(X, Y, Z) plt.show() Edit: With scatter I have come a little further now, so I can display influence of three different parameters now: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x=np.arange(1, 10, 1) y=np.arange(1, 10, 1) z=np.arange(1, 10, 1) X, Y, Z = np.meshgrid(x,y,z) zs = np.array([calculation(1,1,x,y,z) for x,y,z in zip(np.ravel(X), np.ravel(Y), np.ravel(Z))]) C = zs.reshape(X.shape) surf = ax.scatter(X, Y, Z, c=C, linewidth=0, antialiased=False, norm=MidpointNormalize(midpoint=0.), cmap=cm.seismic) fig.colorbar(surf) plt.show()
has comment: http://stackoverflow.com/comment/85612891
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/85575524
type: UnansweredQuestion
has title: Displaying dependency of a value from 5 different variables in a multi-dimensional plot

http://stackoverflow.com/a/49700852
score: 0
answers question: http://stackoverflow.com/q/49390354
has body: You need to manually install a compiler, after installing Tools 2017: 1. Re-open the installer 2. Modify your solution (eg. Community 2017) 3. Search for the compiler you need (eg. Tool kit VC++ 2015.3 v140 for desktop (x86, x64)) 4. Press modify button
type: Answer

http://stackoverflow.com/comment/85874276
type: AnswerComment
comment on: http://stackoverflow.com/a/49436069
type: Comment
score: 0
has text: thanks for the suggestion I tried and I am still getting a syntax error on the same line. thanks for resource.

http://stackoverflow.com/q/49310708
tagged with: dictionary-comprehension
has body: I am trying to create a dictionary through a comprehension but I have to use keys from a specific range of numbers and values from a predefined list: pssmList=[] for column in columns: pssmList.append(collections.Counter(column)) pssmDict = {key:value for key in range(0, len(pssmList)) for value in pssmList} Now, I know that the Counter object is a type of dict but I need those objects inside of pssmDict assigned to keys from a numerical range specified above and all I get is the last element in pssmList repeated over and over again, although each line should be different (and yes, I checked the list and it really contains different records): Key Number 0 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) 1 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) 2 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) 3 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) 4 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) 5 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) Desired output: Key Number 0 Counter({'V': 14, 'L': 2, 'A': 1}) 1 Counter({'D': 17}) 2 Counter({'F': 17}) 3 Counter({'S': 8, 'W': 5, 'Y': 3, 'T': 1}) 4 Counter({'A': 17}) 5 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1}) Does anyone have any idea why this does not work? I've searched StackOverflow for similar problems but either I'm bad at searching or such questions haven't appeared. Please excuse me if my mistake is trivial, I'm in my third month of learning Python (and coding altogether).
downvote count: 0
answer count: 1
upvote count: 1
duplicate of: http://stackoverflow.com/q/1663807
accepted answer: http://stackoverflow.com/a/49310841
tagged with: key
favorite count: 0
has answer: http://stackoverflow.com/a/49310841
type: Question
has title: Dictionary comprehensions using two different sources for keys and values
score: 1
has comment: http://stackoverflow.com/comment/85623569
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/1663807
type: AnsweredQuestion

http://stackoverflow.com/comment/86610880
score: 0
has text: @ImportanceOfBeingErnest, sorry for the delay, I was working on something else. I'll put as an edit the exemple and a jupyter notebook one also. Thanks
comment on: http://stackoverflow.com/q/49325050
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49429160
has answer: http://stackoverflow.com/a/49429314
tagged with: epoch
tagged with: python
type: Question
has body: I would like to test the accuracy by epoch in scikit-learn. However, so far, i have been unsuccessful. This is my code part of classifying with mlpclassifier: NUM_EPOCHS = 1000 LOG_FOR_EVERY = 10 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) clf = MLPClassifier(hidden_layer_sizes=(18, 175, 256), batch_size=528, learning_rate_init=0.0001, beta_1=0.001, beta_2=0.001, max_iter=1, warm_start=True) for i in range(NUM_EPOCHS): clf.fit(X_train, y_train.ravel()) I have also made a graph with this result but i need to make it continuous and further increase accuracy. Why is the accuracy not increasing?
score: 0
has title: Make a graph of accuracy by epoch with mlpclassifier in scikit-learn
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85861496
has comment: http://stackoverflow.com/comment/85859726
tagged with: scikit-learn
tagged with: tensorflow
tagged with: plot

http://stackoverflow.com/comment/85796951
type: Comment
comment on: http://stackoverflow.com/q/49397385
score: 1
type: QuestionComment
has text: You want `sys.argv[1]` (the first argument), not `sys.argv[1:]` (a list containing the first, and any other, arguments).

http://stackoverflow.com/q/49422219
has answer: http://stackoverflow.com/a/49424209
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49422303
has answer: http://stackoverflow.com/a/49422325
tagged with: xpath
answer count: 4
upvote count: 2
has body: The HTML structure is this: The code to extract the text: buyers = doc.xpath("//div[@class='image']/a[0]/text()") The output is: [] What did I do wrong?
score: 0
downvote count: 2
has title: How can I extract the href with XPath?
has answer: http://stackoverflow.com/a/49422342
tagged with: scrapy
favorite count: 0
has comment: http://stackoverflow.com/comment/85845258
type: Question
tagged with: lxml

http://stackoverflow.com/a/49342215
has body: You can complete your bstlist function using list: def bstlist(arr, st, end): newlst = [] if st &gt; end: return [] mid = st + (end-st)/2 # adding the root list root = [arr[mid]] # getting the left list left = bstlist(arr, st, mid-1) # getting the right list right = bstlist(arr, mid+1, end) newlst = root + left+ right return newlst calling the bstlist function will return you list, which is the order in which you should insert the number to get a balanced tree. Example: arr = [1,2,3,4,5] bstarr = bstlist(arr, 0, len(arr)-1) you will get bstarr as [3, 1, 2, 4, 5] it means you have to insert 3 first then 1 and so on. The tree will look like this: 3 / \ 1 4 \ \ 2 5 To get the output as [3, 1, 4, 2, 5] you have to do level order traversal on the above formed binary search tree.
answers question: http://stackoverflow.com/q/49341551
score: 0
type: Answer

http://stackoverflow.com/comment/85623097
score: 0
comment on: http://stackoverflow.com/q/49310429
type: Comment
type: QuestionComment
has text: I wanted and thought that my chart would run through the tops of the unsmoothed line. As the value "s" increases, the graph has a different shape.

http://stackoverflow.com/q/49347055
answer count: 2
has answer: http://stackoverflow.com/a/49347323
possible better answer: http://stackoverflow.com/a/49347248
accepted answer: http://stackoverflow.com/a/49347323
has comment: http://stackoverflow.com/comment/85693992
has answer: http://stackoverflow.com/a/49347248
tagged with: python
score: -1
has body: I have the following code: x = range(100) M = len(x) sample=np.zeros((M,41632)) for i in range(M): lista=np.load('sample'+str(i)+'.npy') for j in range(41632): sample[i,j]=np.array(lista[j]) print i to create an array made of sample_i numpy arrays. sample0, sample1, sample3, etc. are numpy arrays and my expected output is a Mx41632 array like this: sample = [[sample0],[sample1],[sample2],...] How can I compact and make more quick this operation without loop for? M can reach also 1 million. Or, how can I append my sample array if the starting point is, for example, 1000 instead of 0? Thanks in advance
tagged with: vectorization
has comment: http://stackoverflow.com/comment/85696289
type: AnsweredQuestion
has title: Vectorization - how to append array without loop for
downvote count: 1
has comment: http://stackoverflow.com/comment/85693845
favorite count: 0
type: Question
tagged with: numpy
upvote count: 0

http://stackoverflow.com/q/49285897
score: 2
answer count: 0
has title: Django Formset: saving only the first form of formset
downvote count: 0
tagged with: django-forms
favorite count: 0
type: Question
has body: SubTaskFormSet are my SubTasks Forms that i'm having troubles to save properly. In html template i'm dynamically adding/removing inputs thats correspond to elements of my formset, the problem is: only the first form from de formset is being saved. This is how its being created the formset(extra=1 displays 1 input when page loads). SubTaskFormSet = inlineformset_factory(Task, SubTask, form=SubTaskCreateForm, extra=1) This is how im passing the formset to context dict in "get_context_data" method from TemplateView context['form_sub_tasks'] = SubTaskFormSet(self.request.POST or None) Saving a task form and forms of the formset: if all((task.is_valid(), sub_tasks.is_valid())): task.user = self.request.user task = task.save() sub_tasks.instance = task sub_tasks.save() I noticed that when the value of this field changes, the equivalent number of forms from formset is successfully saved in database. &lt;input name="sub_tasks-TOTAL_FORMS" value="1" id="id_sub_tasks-TOTAL_FORMS" type="hidden"&gt; So my question is: how can i change this TOTAL_FORMS input to be possible save more than one form from formset? Of course it could be done via javascript or manually but i'm searching for a better way to accomplish it.
has comment: http://stackoverflow.com/comment/86458721
upvote count: 2
type: UnansweredQuestion
tagged with: inline-formset
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/501719

apache-beam-io
type: Tag
tags question: http://stackoverflow.com/q/49334778
tags question: http://stackoverflow.com/q/49355883
tag name: apache-beam-io

http://stackoverflow.com/comment/85626722
comment on: http://stackoverflow.com/a/49312424
type: Comment
score: 0
type: AnswerComment
has text: Hi JanKnows, I need to print x value also just edited question

http://stackoverflow.com/comment/85691347
has text: I solved it using the pos you gave me. I do not understand this part yet, so I think I need to study. Thank you so much.
comment on: http://stackoverflow.com/a/49345704
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85803697
comment on: http://stackoverflow.com/a/49400266
type: Comment
type: AnswerComment
score: 1
has text: geopandas can also give a colorbar, but then you cannot use `scheme='quantiles'`

http://stackoverflow.com/a/70969230
answers question: http://stackoverflow.com/q/49314624
downvote count: 0
score: 4
type: Answer
upvote count: 4
has body: if you want to apply to particular column you can try col_name 123.1 456 df["col_name"] = df["col_name"].apply(lambda x: format(float(x),".2f")) **after applying format** col_name 123.10 456.00

http://stackoverflow.com/q/49342018
type: Question
has title: How do I plot 3 contours in 3D in matplotlib
has answer: http://stackoverflow.com/a/49342392
linked to: http://stackoverflow.com/q/41699494
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85684367
has body: I have 3 contours, generated by the following: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import stats mean0 = [ 3.1627717, 2.74815376] cov0 = [[0.44675818, -0.04885433], [-0.04885433, 0.52484173]] mean1 = [ 6.63373967, 6.82700035] cov1 = [[ 0.46269969, 0.11528141], [0.11528141, 0.50237073]] mean2 = [ 7.20726944, 2.61513787] cov2 = [[ 0.38486096, -0.13042758], [-0.13042758, 0.40928813]] x = np.linspace(0, 10, 100) y = np.linspace(0, 10, 100) X, Y = np.meshgrid(x, y) Z0 = np.random.random((len(x),len(y))) Z1 = np.random.random((len(x),len(y))) Z2 = np.random.random((len(x),len(y))) def pdf0(arg1,arg2): return (stats.multivariate_normal.pdf((arg1,arg2), mean0, cov0)) def pdf1(arg1,arg2): return (stats.multivariate_normal.pdf((arg1,arg2), mean1, cov1)) def pdf2(arg1,arg2): return (stats.multivariate_normal.pdf((arg1,arg2), mean2, cov2)) for i in range (0, len(x)): for j in range(0,len(y)): Z0[i,j] = pdf0(x[i],y[j]) Z1[i,j] = pdf1(x[i],y[j]) Z2[i,j] = pdf2(x[i],y[j]) Z0=Z0.T Z1=Z1.T Z2=Z2.T fig3 = plt.figure() ax3 = fig3.add_subplot(111) ax3.contour(X,Y,Z0) ax3.contour(X,Y,Z1) ax3.contour(X,Y,Z2) plt.show() Which, visually, is plotted as the following: I am wishing to plot all of these in a 3D plot, but when I try do so with: fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') # 3D plots for each contour. surf1 = ax.plot_surface(X, Y, Z0, cmap=cm.coolwarm, linewidth=0, antialiased=False) surf2 = ax.plot_surface(X, Y, Z1, cmap=cm.coolwarm, linewidth=0, antialiased=False) surf3 = ax.plot_surface(X, Y, Z2, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.contour(X, Y, Z0, zdir='z', offset=-0.5) ax.contour(X, Y, Z1, zdir='z', offset=-0.5) ax.contour(X, Y, Z2, zdir='z', offset=-0.5) ax.set_zlim(-0.5, 0.31) plt.show() The resulting graph is this: How can I get the other two 3D contours to show nicely?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49342392
downvote count: 0
tagged with: contour
tagged with: 3d
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85684486
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85752936
type: Comment
has text: FYI: The function `find_transition_times(t, y, threshold)` in [my answer here](https://stackoverflow.com/questions/15112964/digitizing-an-analog-signal/15114952#15114952) might be something you can use.
comment on: http://stackoverflow.com/q/49375579
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85668881
has text: Why do you have input_shape in layers beyond the first? That's probably your issue.
comment on: http://stackoverflow.com/q/49333001
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86118207
score: 1
comment on: http://stackoverflow.com/q/49424261
type: QuestionComment
has text: "Obviously when trying to filter on description, this fails ..." is not quite obvious at all and seems a bit XYish. Please provide a [mcve]. Also provide full tracebacks instead of just the message part of an exception.
type: Comment

http://stackoverflow.com/q/49381140
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85767629
has comment: http://stackoverflow.com/comment/85764752
has title: Is there a way to get only data codeword modules of a qr code in Python?
tagged with: qr-code
tagged with: python
linked to: http://stackoverflow.com/q/27233351
has body: Before a qr code is created , the data to be embedded is converted to binary bits using alphanumeric, utf-8 etc. Then error codewords are added to it and final msg is structured. Is there a way to get only embedded data codewords modules along with its padding as 0's and 1's and not error correction codewords , using Python libraries or functions ? Example: HELLO WORLD if is to be encoded using alphanumeric mode of version 1 qr code, then after its conversion to the mentioned mode and addtion of padding bits it is 00100000 01011011 00001011 01111000 11010001 01110010 11011100 01001101 01000011 01000000 11101100 00010001 11101100 This is what embedded in qr code using black and white modules after adding error codewords. i need to extract only this data message if its already embedded in a qr code using python
score: 0
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/85768569

http://stackoverflow.com/a/76147690
score: 0
has body: You can use glom assignment to get and modify the value in-place: from glom import glom, assign, Assign, Spec d = {'a': {'b': {'c': 'value'}}} Option 1 with regular glom assignment: value_to_encrypt = glom(d,'a.b.c') # deep-get _ = assign(d, 'a.b.c', encrypt(value_to_encrypt)) # deep-modify 'c' in place Option 2 with deep-apply: _ = glom(d, Assign('a.b.c', Spec(('a.b.c', encrypt)))) # applies 'encrypt' on a.b.c and modifies the value in place
type: Answer
answers question: http://stackoverflow.com/q/49427002

http://stackoverflow.com/comment/124012395
score: 0
type: Comment
has text: Whatever you are hoping to accomplish, **`chmod 777` is *wrong* and *dangerous.*** You absolutely do not want to grant write access to executable or system files to all users under any circumstances. You will want to revert to sane permissions ASAP (for your use case, probably `chmod 755`) and learn about the Unix permissions model before you try to use it again. If this happened on a system with Internet access, check whether an intruder could have exploited this to escalate their privileges.
type: QuestionComment
comment on: http://stackoverflow.com/q/49308355

http://stackoverflow.com/q/49318427
downvote count: 0
tagged with: wrapper
answer count: 1
tagged with: cython
has title: Cython with Python3.5: convert list of string to char**
linked to: http://stackoverflow.com/q/9665177
linked to: http://stackoverflow.com/q/17511309
accepted answer: http://stackoverflow.com/a/49385912
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85644623
score: 3
has body: I am trying to pass a list of string to a C++ function that takes a char** as argument using Cython. I tried other solutions I can't remember but I mainly tried the two following options: Using a convertion function extracted from here, which is basically the same answer than here, but it raises an error, on the g++ compilation which is cy_wrapper.cpp: In function 'char** _pyx_f_10cy_wrapper_to_cstring_array(PyObject*)': cy_wrapper.cpp:1223:44: error 'PyString_AsString' was not declared in this scope __pyx_t_5 = PyString_AsString(__pyx_t_4); if (unlikely(__pyx_t_5 == ((char *)NULL)) Using the encoding method of python strings, as suggested in here but the answer is not satisfying since it raises the error: cy_wrapper.pyx:14:35: Storing unsafe C derivative of temporary Python reference I looked in the library files at ~/.local/lib/python3.5/site-packages/Cython/Includes/cpython and I found the file string.pxd which contains the function PyString_AsString I need. Why is it not found? If there is no possibility to use it, is there a workaround? I am working on Ubuntu 16.04.4 LTS (tegra kernel) on a arm64 arch. My cy_wrapper.pyx is exactly like this: from cpython.string cimport PyString_AsString from libc.stdlib cimport malloc cdef extern: cdef cppclass imageNet: imageNet* Create(int argc, char** argv) cdef char** to_cstring_array(list_str): cdef char** ret = &lt;char **&gt;malloc(len(list_str) * sizeof(char *)) for i in range(len(list_str)): ret[i] = PyString_AsString(list_str[i]) return ret cdef class PyImageNet: cdef imageNet* c_net def Create(self, argc, kwargs): cdef char** c_argv = to_cstring_array(kwargs) return PyImageNetFactory(self.c_net.Create(argc, c_argv)) cdef object PyImageNetFactory(imageNet* ptr): cdef PyImageNet py_obj = PyImageNet() py_obj.c_net = ptr return py_obj My setup.py: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {"build_ext": build_ext}, ext_modules = [ Ex…
tagged with: python
has comment: http://stackoverflow.com/comment/85642444
has answer: http://stackoverflow.com/a/49385912
linked to: http://stackoverflow.com/q/29109685
tagged with: type-conversion
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/85782891
type: QuestionComment
has text: Out of curiosity, why can't it be placed in one cell? You can also use a hidden sheet.
comment on: http://stackoverflow.com/q/49390447
score: 0
type: Comment

http://stackoverflow.com/q/49333494
accepted answer: http://stackoverflow.com/a/49333515
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49333515
has comment: http://stackoverflow.com/comment/85668623
has comment: http://stackoverflow.com/comment/85668734
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
answer count: 1
has title: python pandas select top 'n' from multiple sub group
favorite count: 0
type: Question
has body: I have a DataFrame, with lets say 3 columns: col1 | col2 | col3 A | x | p A | x | q A | x | r A | x | r A | y | s A | y | t A | z | u B | x | q B | x | r B | y | t I want to group this by the number of occurrences of the unique combination of the 3 columns &amp; then select only the records per the top 2 (n) values of col3 So if the combination of (A, x) has 9 counts of p, 8 counts of q &amp; 3 counts of r in col3 - then it should display only top 2 counts of col3: A | x | p | 9 A | x | q | 8 I have tried nlargest, head &amp; some other options from other forums, but none of it works in sub groups - they only display the top n of the group as a whole

http://stackoverflow.com/comment/85743508
type: QuestionComment
has text: Alternatively, the bare `threading` module, and `multiprocessing.dummy`, will both work with both versions (maybe with a bit of `six`-ing, but you probably want to use `six` or something equivalent for dual-version code anyway).
comment on: http://stackoverflow.com/q/49371214
score: 0
type: Comment

http://stackoverflow.com/q/49296552
answer count: 1
has title: How to get progress bar to stay on one line
type: Question
tagged with: python-3.x
has body: import time import sys progressbar = [] dashes = 1 spaces = 10 for i in range(11): print("Logging In[", end = "") for x in range(dashes): dash = "|" progressbar.append(dash) print(progressbar[x], end = "") for y in range(spaces): print(end = " ") dashes += 1 spaces -= 1 print("]") sys.stdout.write() sys.stdout.flush() I was wondering how to get this progress bar to print on only one line like a game or loading screen. It prints over and over again on a new line each time and I have no clue how to fix it.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85595049
tagged with: python
has comment: http://stackoverflow.com/comment/85595390
has comment: http://stackoverflow.com/comment/85595386
linked to: http://stackoverflow.com/q/3173320
score: 0
has answer: http://stackoverflow.com/a/49297038

sql-server
tags question: http://stackoverflow.com/q/49387281
type: Tag
tags question: http://stackoverflow.com/q/49417784
tags question: http://stackoverflow.com/q/49411277
tag name: sql-server

http://stackoverflow.com/a/49431609
has body: The problem is that you are saving only the structure of the model. This does not include the weights you got from training the model. To quote Keras FAQ: If you only need to save the architecture of a model, and not its weights or its training configuration, you can do: json_string = model.to_json() Alternatively, try doing model.save(filepath). This will save both the model structure and the weights that you got from training the model into the file specified with filepath.
type: AcceptedAnswer
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49425632
downvote count: 0
answers question: http://stackoverflow.com/q/49425632
has comment: http://stackoverflow.com/comment/85865568

http://stackoverflow.com/comment/95320040
type: QuestionComment
has text: Try new tutorial https://www.tensorflow.org/hub/tutorials/image_retraining
comment on: http://stackoverflow.com/q/49375586
score: 0
type: Comment

http://stackoverflow.com/q/49397677
has answer: http://stackoverflow.com/a/49397945
has body: Hard to describe it, ref below codes, pls For the var item1, I wonder: Section1, item1's value is an element of lst, a tuple. but from Section2, items1's value goes to next level, is an element of an element of lst. how to understand this? import random lst1 = [random.randint(1, 100) for i in range(10)] lst2 = [random.randint(1, 100) for i in range(10)] lst = list(zip(lst1, lst2)) print(lst) # section 1 for item1 in lst: print(item1) # section 2 for item1, item2 in lst: print(item1, item2) output example: [(34, 85), (9, 18), (56, 89), (69, 82), (21, 69), (21, 46), (39, 78), (19, 27), (33, 71), (94, 2)] section1: (34, 85) ... (94, 2) section2: 34 85 ... 94 2 how come from section1 item1 = (34, 85) but item1 just = 34 from section2
accepted answer: http://stackoverflow.com/a/49397945
has comment: http://stackoverflow.com/comment/85797057
tagged with: python
has title: Environment: Python(3.6.4), how come the value(level) is different?
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/10867882
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85797281

sensors
type: Tag
tags question: http://stackoverflow.com/q/49432605
tag name: sensors
tags question: http://stackoverflow.com/q/49307863

http://stackoverflow.com/comment/85633166
type: QuestionComment
comment on: http://stackoverflow.com/q/49296843
has text: Well, I am glad you solved it. Kind of tricky, since [the PEP](https://www.python.org/dev/peps/pep-0484/) was accepted for 3.5. I wonder why pycharm can't work it out on that version.
score: 0
type: Comment

http://stackoverflow.com/comment/85655722
type: Comment
comment on: http://stackoverflow.com/a/49326484
score: 0
type: AnswerComment
has text: Understood, cheers mate

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/49387281
tags question: http://stackoverflow.com/q/49323551
type: Tag

http://stackoverflow.com/comment/85747290
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49371931
has text: @abarnert Thanks for the advice. (I have changed the title) Could you tell me how I know if the file is utf-16-le or -be ?
type: Comment

http://stackoverflow.com/a/49311370
downvote count: 0
has body: Filenames are strings. That's what you pass to open to get a file object, which you can then get data from. For example, let's say you have a script called spam.py: filename = 'spam.py' with open(filename) as fileobj: data = fileobj.read() print(data) When you run it, it prints itself out. Now, the output you got back from calling subprocess.run on ls and reading its stdout is not a string for each file, but one big string. The simple answer here is to just not call out to ls. Python can already get a list of filenames for you: filenames = os.listdir(path) for filename in filenames: with open(filename) as fileobj: # do stuff with fileobj But if you really must, you can use, e.g., the splitlines method to turn the output you have into a list of lines, which will be much the same as what listdir returns, just retrieved in a more convoluted way.
accepted answer of: http://stackoverflow.com/q/49311270
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49311270
type: AcceptedAnswer

http://stackoverflow.com/comment/85775874
score: 0
comment on: http://stackoverflow.com/a/49387025
type: AnswerComment
has text: @ Mert Yes this runs and generated the expected output.
type: Comment

http://stackoverflow.com/a/49310927
answers question: http://stackoverflow.com/q/49301489
upvote count: 1
has comment: http://stackoverflow.com/comment/85628917
downvote count: 0
score: 1
has body: The problem is that the target of a thread is a callable. What you're passing to Thread, on the other hand, is not receive_data, but receive_data(). Long story short, the receive_data function is called on the current thread when you reach the point of the parameter evaluation for the Thread constructor, and you stay inside of it until it ends. You just need to remove the parentheses, and create your thread as follows: thread = threading.Thread(target=receive_data)
type: Answer

http://stackoverflow.com/comment/85652758
comment on: http://stackoverflow.com/q/49320481
has text: Create a new environment? `conda create -n matlabenv python=3.4 matlab_kernel`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85583453
has text: i would prefer if THEINCREDIBLES and IRONMAN have it's own sum of ordinal representation rather than combining the sum of both movies
comment on: http://stackoverflow.com/a/49290126
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49428186
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49428015
type: Answer
has body: I believe you need create dictionary for map with enumerate, compare with Time column and filter by boolean indexing: print (df) ID Time op1 0 1 1 -0.0007 1 1 2 0.0019 2 1 3 -0.0043 3 2 4 0.0007 4 2 5 -0.0019 difference = [2, 6, 53, 83] d = dict(enumerate(difference, 1)) print (d) {1: 2, 2: 6, 3: 53, 4: 83} df = df[df['Time'] &lt; df['ID'].map(d)] print (df) ID Time op1 0 1 1 -0.0007 3 2 4 0.0007 4 2 5 -0.0019 Detail: print (df['ID'].map(d)) 0 2 1 2 2 2 3 6 4 6 Name: ID, dtype: int64
score: 2
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49428015

http://stackoverflow.com/comment/85760404
score: 3
type: QuestionComment
has text: And if you're using `round` to try to test for equality… don't do that either. Use `math.isclose` (or `np.isclose` if you're using numpy).
type: Comment
comment on: http://stackoverflow.com/q/49379847

http://stackoverflow.com/q/49380995
type: Question
has title: pyqtgraph rotate ScatterplotItems as spots
tagged with: python
tagged with: pyqtgraph
accepted answer: http://stackoverflow.com/a/51788553
has answer: http://stackoverflow.com/a/51788553
has body: In pyqtgraph you can scatterplot each item for itself or a whole bunch of them as bulk (using spots). working with large datasets i prefer the last method since the figure stays light and is movable without lagging all over the screen. my problem some of my symbols i need an angle... that isn't that much of a problem, however if i add them separately to the plot it results in a laggy figure. so my problem is that i am currently unable to find a suitable way to subclass the whole thing and implement a small method for the keyword argument "rotation"/"angle". has anyone finished this task already or has someone an idea? thank you very much in advance!
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/comment/85759675
comment on: http://stackoverflow.com/q/49379254
has text: in python indentation matters, it indicates what code is in what block. you get the error because you haven't indented any code for the `for line in f:` so its expecting an indented block that isn't there. I'm voting to close this as a typographical error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49413208
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49413139
has body: Since you start with a dictionary, it's very unlikely this can benefit from numpy vectorization; So solution would be bare loops, and you can pad zeros either in numpy way with np.pad: np.array([np.pad(v, (0, m - len(v)), 'constant') for v in h.values()]) #array([[1, 2, 0], # [3, 4, 5]]) Or vanilla list way: np.array([v + [0] * (m - len(v)) for v in h.values()]) #array([[1, 2, 0], # [3, 4, 5]])
answers question: http://stackoverflow.com/q/49413139
type: AcceptedAnswer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/49393705
tagged with: regex
has answer: http://stackoverflow.com/a/49393822
has body: I'm learning about regex. If I want to find all the 5 letter words in a string, I could use: import re text = 'The quick brown fox jumps over the lazy dog.' print(re.findall(r"\b[a-zA-z]{5}\b", text)) But I want to write a simple function whose argument includes the string and the length of the word being found. I tried this: import re def findwords(text, n): return re.findall(r"\b[a-zA-z]{n}\b", text) print(findwords('The quick brown fox jumps over the lazy dog.', 5)) But this returns an empty list. The n is not being recognized. How can I specify an argument with the number of repetitions (or in this case, the length of the word)?
upvote count: 4
has comment: http://stackoverflow.com/comment/85789811
answer count: 3
linked to: http://stackoverflow.com/q/2960772
type: UnansweredQuestion
has title: How to pass an argument for regex repetitions (python)
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49394026
score: 3
has answer: http://stackoverflow.com/a/49393795
has comment: http://stackoverflow.com/comment/85789306
tagged with: repeat
tagged with: python

http://stackoverflow.com/comment/85573719
comment on: http://stackoverflow.com/a/49285337
type: AnswerComment
score: 0
type: Comment
has text: What's the second date column in your output?

http://stackoverflow.com/comment/85605223
type: QuestionComment
comment on: http://stackoverflow.com/q/49301389
score: 0
has text: so basically: (xmin,ymin,boxwidth,boxheight) ?
type: Comment

http://stackoverflow.com/comment/85879161
type: AnswerComment
comment on: http://stackoverflow.com/a/49436607
score: 0
type: Comment
has text: Added an explanation, hopefully that helps

http://stackoverflow.com/comment/85870604
has text: What are the categories you are trying to get? Business, Sports, etc?
comment on: http://stackoverflow.com/q/49434230
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49310591
downvote count: 0
tagged with: gcloud
has comment: http://stackoverflow.com/comment/85624396
has answer: http://stackoverflow.com/a/53784607
has answer: http://stackoverflow.com/a/49335683
favorite count: 0
has comment: http://stackoverflow.com/comment/85623706
has body: I'm using gcloud on Windows to develop GAE stuff. The network here has a MITM root certificate by design so all SSL traffic can be snooped; I can install the root cert easily into a browser or Windows certificate store, but can't successfully get this work for Python, or more specifically, gcloud (which has its own Python bundled). The answers at How to add a custom CA Root certificate to the CA Store used by Python in Windows? don't work - I've tried setting SSL_CERT_DIR and SSL_CERT_FILE environment variables to no avail, and the pip.ini solution isn't applicable as I'm not using pip.
score: 8
upvote count: 8
linked to: http://stackoverflow.com/q/39356413
type: Question
has comment: http://stackoverflow.com/comment/85629817
tagged with: google-app-engine
has title: Adding a custom CA Root certificate to GCloud utility (or Python generally) on Windows
answer count: 2
tagged with: windows
has comment: http://stackoverflow.com/comment/85626589
tagged with: ssl
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85625170
has comment: http://stackoverflow.com/comment/85625148

http://stackoverflow.com/a/49352359
downvote count: 0
has comment: http://stackoverflow.com/comment/85705124
answers question: http://stackoverflow.com/q/49352285
has comment: http://stackoverflow.com/comment/85704753
type: Answer
has comment: http://stackoverflow.com/comment/85704785
upvote count: 2
has body: You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by @Ajax1234 in their answer). It is a lot more Pythonic to use the built-in function sum, a generator expression and range: def problem2(n): return sum(x**2 for x in range(n)) This would be a lot more readable and better (unless of course you are being forced to use while).
score: 2

http://stackoverflow.com/a/49292268
accepted answer of: http://stackoverflow.com/q/49292151
answers question: http://stackoverflow.com/q/49292151
type: Answer
score: 4
upvote count: 4
downvote count: 0
has body: This is why Python's sum function has an optional "start" argument: so you can initialize it with a "zero object" of the kind you are adding. In this case, with a zero matrix. &gt;&gt;&gt; print(sum(ls, sp.zeros(2))) Matrix([[9, 0], [0, 9]])
type: AcceptedAnswer

http://stackoverflow.com/a/49296246
score: 0
answers question: http://stackoverflow.com/q/49291275
has body: You are using a settings file from an old version of Django. Change MIDDLEWARE_CLASSES to just MIDDLEWARE.
type: Answer

http://stackoverflow.com/comment/85727057
type: QuestionComment
has text: @GrahamDumpleton Thanks for your comment. I set 'MOD_WSGI_APACHE_ROOTDIR', so I think the problem of Apache's location has already solved. I also installed Visual C++ and Visual Studio. Now I added a part of the errors for 'pip install mod_wsgi' to my question. If it is enough, could you tell me what to do in order to make 'pip install mod_wsgi' work, please?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49331945

http://stackoverflow.com/q/49399107
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50407536
has title: Python for predefined Junit XML
has answer: http://stackoverflow.com/a/50407536
tagged with: python
type: AnsweredQuestion
tagged with: junit
has body: I have to develop a python script that produces a Junit XML in following format <?xml version="1.0" encoding="UTF-8"?> <skipped /> Failed 1 times. I did a basic python code but not able to mark as shown above from junit_xml import TestSuite, TestCase test_cases = [] for result in results: tc_name, tc_result = result if tc_result == "PASS": test_cases.append(TestCase(tc_name)) ts = TestSuite("S", test_cases) print(TestSuite.to_xml_string([ts]))enter code here Please do give your suggestion for the above
answer count: 1
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85734743
comment on: http://stackoverflow.com/a/49366942
type: Comment
type: AnswerComment
score: 0
has text: thanks , it worked content = [x.strip('\n').split(',') for x in content]

http://stackoverflow.com/comment/86005364
type: Comment
comment on: http://stackoverflow.com/a/49440751
score: 0
type: AnswerComment
has text: Thank you that helped me a lot

traitsui
tag name: traitsui
type: Tag
tags question: http://stackoverflow.com/q/49336128
tags question: http://stackoverflow.com/q/49371365

http://stackoverflow.com/comment/85738796
has text: I think the best rule of thumb here is slightly more complicated. (Assuming you don't need a closure, and the performance cost of a global lookup is irrelevant to your problem) the key difference is that nested functions are not reusable, but they also don't pollute the global namespace. So, if you might want to reuse the function, make it global; if you definitely don't want anyone reusing it, make it nested; if you're not sure, at least you know the metric you're trying to decide on.
score: 0
comment on: http://stackoverflow.com/q/49366928
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49303483
type: Answer
has body: If your file contains fancy unicode quotes, then you'll need to first convert them to regular '/" quotes. You can do this using the unidecode module: from unidecode import unidecode contents = unidecode(contents).replace('"', '').replace("'", '') Now if you want to remove all punctuation, then you'll need to use a slightly different approach: from unidecode import unidecode import string trans_table = str.maketrans('', '', string.punctuation) contents = unidecode(contents).translate(trans_table)
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49303116
has comment: http://stackoverflow.com/comment/85668901
has comment: http://stackoverflow.com/comment/85609152
has comment: http://stackoverflow.com/comment/85609244

http://stackoverflow.com/comment/85783747
type: Comment
comment on: http://stackoverflow.com/q/49324886
score: 0
has text: AFAICS, you rather need client_id per _application_, not per user. You enter the user's login and password in the browser at `authorization_url`.
type: QuestionComment

http://stackoverflow.com/a/49288052
has comment: http://stackoverflow.com/comment/85603445
has comment: http://stackoverflow.com/comment/103670352
has comment: http://stackoverflow.com/comment/85590976
downvote count: 1
has comment: http://stackoverflow.com/comment/85601687
has comment: http://stackoverflow.com/comment/85590106
has comment: http://stackoverflow.com/comment/85590816
upvote count: 8
has comment: http://stackoverflow.com/comment/103684017
has body: To answer your question: use a different (non interactive) backend: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt Your code is probably not working because you created the figure instance after your plot. Try: fig = plt.figure() plt.plot([2,5,1,2] fig.text(.5, .05, "text", ha="center") plt.show()
type: Answer
has comment: http://stackoverflow.com/comment/85589890
answers question: http://stackoverflow.com/q/49284893
has comment: http://stackoverflow.com/comment/85632006
score: 7
has comment: http://stackoverflow.com/comment/85632042

http://stackoverflow.com/comment/85815607
type: AnswerComment
score: 0
has text: @asdasd You do not need to override the save method. read that query. As I said, the query is the key to making this work. Retrieve the row with the lowest weight that is not less than the quantity for the order. That will give the price for the appropriate "bucket"
comment on: http://stackoverflow.com/a/49393847
type: Comment

http://stackoverflow.com/comment/86377786
type: QuestionComment
comment on: http://stackoverflow.com/q/49431056
score: 0
has text: Side note: [arrays](https://docs.python.org/3/library/array.html) support the buffer interface as well as fromfile/tofile, and are more efficient for this data handling than struct.
type: Comment

http://stackoverflow.com/q/49348647
linked to: http://stackoverflow.com/q/15017072
has body: import csv import pandas as pd df_1 = pd.read_csv("result4.csv") df_1.to_csv('dataset_1.txt', sep='\n', index=False) This returns a text file with both columns, I only want the second column.
answer count: 1
tagged with: dataset
downvote count: 1
duplicate of: http://stackoverflow.com/q/15017072
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49348719
has comment: http://stackoverflow.com/comment/85697106
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85697132
has title: I have a Python data frame with 2 columns. I want to copy data from the second column into a text file. How can I do this?
upvote count: 0
has comment: http://stackoverflow.com/comment/85696967
tagged with: pandas

http://stackoverflow.com/a/49314284
type: Answer
score: 0
has body: The result is the conflict without a specific command. Use python2.7 -m pip or python2 -m pip for a specific command. Vice versa, on python3, use python3 -m pip or python3.4 -m pip for a specific command. In addition, use python or python3 to get into interactive mode. Then, use import sys and sys.path to get the path of python package.
answers question: http://stackoverflow.com/q/49311839

http://stackoverflow.com/q/49346819
downvote count: 0
answer count: 1
has title: How to fix sphinx extension when two sphinx builders generates different doctrees?
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49639324
has answer: http://stackoverflow.com/a/49639324
score: 1
type: Question
has body: In my pylatest sphinx extension, I define custom rst directive test_action and custom sphinx builder xmlexport so that when I build a sphinx project with default sphinx html builder (via make html), the test_action directives are transformed into single html table, while with xmlexport builder, the directives are just wrapped in div html tags without any additional processing. To achieve this, the test_action directives generates custom doctree nodes which are either directly translated into html (extending html translator) when xmlexport builder is used, or with html builder the custom nodes are transformed into html table via custom rst transformation class. I achieve this by checking which builder is used and adding transform classes accordingly: def pylatest_transform_handler(app): if isinstance(app.builder, builders.XmlExportBuilder): ... else: # pylatest transforms for human readable html output, # translates pylatest nodes into nice sections or tables app.add_transform(transforms.TestActionsTableTransform) In a function which handles builder-inited event in my sphinx extension: def setup(app): ... # pylatest transforms are added based on app.builder value app.connect('builder-inited', pylatest_transform_handler) This hack works, but it has one problem: when html builder is used, doctree cached in _build/doctree/ is diferent compared to one cached after xmlexport builder run. This means that when I run make html after I executed make xmlexport, the build fails because sphinx uses wrong doctree. So the question I have is: How do I make sure that sphinx doctree cache is regenerated when different builders are used after each other, but kept when the same builder is used again?
tagged with: python-sphinx

http://stackoverflow.com/a/49396881
type: Answer
has body: String are imutable in python. You can simply strip the leading or trailing whitespaces using list comprehension to make new list. [x.strip() for x in string]
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49396796
has comment: http://stackoverflow.com/comment/85795510
accepted answer of: http://stackoverflow.com/q/49396796

http://stackoverflow.com/a/49408821
score: 1
upvote count: 1
has body: The response headers for this request include content-type: application/json as your browser will tell you. So it is JSON.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49408762
downvote count: 0
answers question: http://stackoverflow.com/q/49408762

http://stackoverflow.com/a/49414907
type: Answer
answers question: http://stackoverflow.com/q/49414841
score: 77
type: AcceptedAnswer
has body: The SIGSEGV signal indicates a "segmentation violation" or a "segfault". More or less, this equates to a read or write of a memory address that's not mapped in the process. This indicates a bug in your program. In a Python program, this is either a bug in the interpreter or in an extension module being used (and the latter is the most common cause). To fix the problem, you have several options. One option is to produce a minimal, self-contained, complete example which replicates the problem and then submit it as a bug report to the maintainers of the extension module it uses. Another option is to try to track down the cause yourself. gdb is a valuable tool in such an endeavor, as is a debug build of Python and all of the extension modules in use. After you have gdb installed, you can use it to run your Python program: gdb --args python &lt;more args if you want&gt; And then use gdb commands to track down the problem. If you use run then your program will run until it would have crashed and you will have a chance to inspect the state using other gdb commands.
accepted answer of: http://stackoverflow.com/q/49414841
upvote count: 77
downvote count: 0

http://stackoverflow.com/comment/85571333
comment on: http://stackoverflow.com/q/49284224
type: Comment
type: QuestionComment
score: 0
has text: As to why it does not change `a`: https://stackoverflow.com/questions/15148496/passing-an-integer-by-reference-in-python, for your array you can have a look here: https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.copy.html

http://stackoverflow.com/q/49422643
has comment: http://stackoverflow.com/comment/113092592
answer count: 1
has body: I am trying to execute a nodejs script with python program and get the return output. b.js data : { "1":[], "2":[], "3":[], "4":[], "5":[], "6":[], "7":[], "8":[], "9":[], "10":[], "11":[{"id":"1","domain":"www.xxxxx.com","keywords":"白银交易平台","type":"Type1","time":["11","14","15","18"]}] } console.log(JSON.stringify(data)) a.py if response.exitcode == 0: print(response.stdout) else: sys.stderr.write(response.stderr) b'{"1":[],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":[],"9":[],"10":[],"11":[{"id":"1","domain":"www.xxxx.com","keywords":"\xe7\x99\xbd\xe9\x93\xb6\xe4\xba\xa4\xe6\x98\x93\xe5\xb9\xb3\xe5\x8f\xb0","type":"Type1","time":["11","14","15","18"]}]}\n' From official docs of naked, response.stdout is returned NakedObject. How can I convert the returned NakedObject to python dictionary ?
has title: return nodejs script output to python
type: Question
has answer: http://stackoverflow.com/a/49422686
type: UnansweredQuestion
tagged with: python
tagged with: node.js
score: 0

http://stackoverflow.com/q/49293754
accepted answer: http://stackoverflow.com/a/49309123
has title: How to mock __version__ in Python unittest
has comment: http://stackoverflow.com/comment/85590122
answer count: 1
tagged with: unit-testing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85617920
has answer: http://stackoverflow.com/a/49309123
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has body: In my release_exporter/version.py I have __version__ = '1.0.6' and I want to mock its stdout. check_version() prints out the latest version to the stdout. I did mock stdout by doing @patch('sys.stdout', new_callable=io.StringIO) def assert_stdout_1(self, n, expected_output, mock_stdout): request = check_version() self.assertIn(expected_output, mock_stdout.getvalue()) Which works fine. I tried doing something like this to mock the version number: def test_check_version_pass(self): version.__version__ = '1' self.assert_stdout_1('', 'New version') I know this is wrong because I am not mocking it (though this works fine). Then I tried doing @patch.object(version.__version__, 'version.__version__', return_value='1') def test_check_version_pass(self): self.assert_stdout_1('', 'New version') But I get an error as AttributeError: 1.0.6 does not have the attribute 'version.__version__'. I also tried using @patch('release_exporter.version.__version__', return_value='1') but I get an error as TypeError: test_check_version_pass() takes 1 positional argument but 2 were given. I don't know what I am doing wrong. Help!
downvote count: 0

http://stackoverflow.com/comment/85852394
score: 0
has text: Ok I understand! But the issue is alive even if i write the code similar but not in an explicit function. But there must be a way to delete an object with all its attributes forever. But with 'del', this not the case..
type: Comment
comment on: http://stackoverflow.com/q/49424252
type: QuestionComment

mne-python
type: Tag
tags question: http://stackoverflow.com/q/49285843
tag name: mne-python

http://stackoverflow.com/a/49413053
has body: The Access-Control-Allow-Origin header is a response header - you don't pass it in your request (from the website JS) - you pass it in the response from your Flask app. If you pass it in the request, it does nothing, EXCEPT make the browser send a preflight OPTIONS request, since it's not a basic request header. So. Remove the Access-Control-Allow-Origin request header from your JS Add the Access-Control-Allow-Options: * response header to your Flask app (I'm not sure how you add response headers in Flask)
score: 0
answers question: http://stackoverflow.com/q/49392595
type: Answer

http://stackoverflow.com/comment/85683063
type: QuestionComment
comment on: http://stackoverflow.com/q/49339569
has text: and pass json back which you can then display through javascript
score: 0
type: Comment

http://stackoverflow.com/comment/85621143
type: QuestionComment
score: 0
has text: I am generating a new database backup prior to the move, so the file does exist.
type: Comment
comment on: http://stackoverflow.com/q/49309508

http://stackoverflow.com/a/49399421
score: 37
has comment: http://stackoverflow.com/comment/85805315
downvote count: 0
has body: Your understanding is correct but pytorch doesn't compute cross entropy in that way. Pytorch uses the following formula. loss(x, class) = -log(exp(x[class]) / (\sum_j exp(x[j]))) = -x[class] + log(\sum_j exp(x[j])) Since, in your scenario, x = [0, 0, 0, 1] and class = 3, if you evaluate the above expression, you would get: loss(x, class) = -1 + log(exp(0) + exp(0) + exp(0) + exp(1)) = 0.7437 Pytorch considers natural logarithm.
upvote count: 37
has comment: http://stackoverflow.com/comment/136120594
type: Answer
answers question: http://stackoverflow.com/q/49390842

http://stackoverflow.com/a/49343229
downvote count: 0
score: 3
has body: ATTENTION To all who want to copy the code and want to use it in other projects: you will have to tweak and adapt it (especially threshold/kernel/iterations values). This version works at it's best on the user provided image. import cv2 image = cv2.imread("image.jpg") image_c = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale cv2.imshow('gray', gray) cv2.waitKey(0) _, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) # threshold cv2.imshow('thresh', thresh) cv2.waitKey(0) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) dilated = cv2.dilate(thresh, kernel, iterations=13) # dilate cv2.imshow('dilated', dilated) cv2.waitKey(0) image, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # get contours # for each contour found, draw a rectangle around it on original image for i, contour in enumerate(contours): # get rectangle bounding contour x, y, w, h = cv2.boundingRect(contour) roi = image_c[y:y + h, x:x + w] if 50 &lt; h &lt; 100 or 200 &lt; w &lt; 420: # these values are specific for this example # draw rectangle around contour on original image rect = cv2.rectangle(image_c, (x, y), (x + w, y + h), (255, 255, 255), 1) cv2.imshow('rectangles', rect) cv2.waitKey(0) cv2.imwrite('extracted{}.png'.format(i), roi) # write original image with added contours to disk - change values above to (255,0,255) to see clearly the contours cv2.imwrite("contoured.jpg", image_c)
type: Answer
answers question: http://stackoverflow.com/q/49316237
upvote count: 3

http://stackoverflow.com/comment/85740577
type: QuestionComment
type: Comment
has text: If performance isn't an issue, for output to myself, I usually like to be as explicit as possible about what I'm printing out so I can modify it easily, like `''.join(f'\\x{ch:02X}' for ch in b)`. For output I definitely _don't_ want to change later, of course, I'd use a nice stdlib function. Either way, `print` that, and you'll see `\x14\xFF\x81\x83\x06\x08\x00\x0F\x00\x3E`, which is (I think) exactly what you want here, right? And that's how you verify that you added the right data after all.
comment on: http://stackoverflow.com/q/49369650
score: 0

http://stackoverflow.com/comment/85849877
has text: Sorry to disagree, you'll have to find a better duplicate. `os.listdir` returns the file _names_, `os.walk` returns a triplet root+list of files+list of dirs for each dir. Not as easy to grasp. That plus the fact that user used current directory and hoped it would solve it magically.
comment on: http://stackoverflow.com/q/49424274
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85880567
has text: Thanks! `a.mask(missing_vals, -1)` also works in my case.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49439285

http://stackoverflow.com/comment/85798415
comment on: http://stackoverflow.com/q/49398463
type: Comment
type: QuestionComment
score: 0
has text: And (2): the problem is that `for student in students:` is looping over the _keys_ of your dictionary. So, that format string you build is `"100: {100}"`. That means you're trying to insert positional argument #100 out of 0.

http://stackoverflow.com/comment/85847985
type: Comment
type: QuestionComment
has text: I took this code from this video :D
comment on: http://stackoverflow.com/q/49423183
score: 1

http://stackoverflow.com/comment/85826706
type: QuestionComment
comment on: http://stackoverflow.com/q/49412349
score: 2
has text: Based on how you write the ball_response.txt the line `n = int(line)` will always error since non of the lines are int. Also you are reading only one line then it looks like you are trying to loop through the lines?
type: Comment

http://stackoverflow.com/q/49329139
score: 1
has comment: http://stackoverflow.com/comment/85660692
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49330651
favorite count: 0
type: Question
has title: request to IB responds differently when in a loop
tagged with: quantitative-finance
tagged with: interactive-brokers
has body: I just don't understand what is going on here. I'm a bit new to wrappers and IB. Here is my function that overrides and parses the XML. Should the XML be parsed in the main? I just want to get the fundamental data for all the symbols in my CSV file. When I comment out the loop and run an individual request it works, sometimes. What's going on here? class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, wrapper=self) self.csv = pd.read_csv('getfund.csv'); self.symbols = self.csv['Symbol'] self.exchanges = self.csv['Exchange'] def nextValidId(self, reqId: int): reqs_do() def reqs_do(): for i in range(len(symbols)): contract = Contract() contract.symbol = self.symbols[i] contract.secType = "STK" contract.exchange = self.exchanges[i] contract.currency = "USD" contract.primaryExchange = "NASDAQ" print(contract) print(symbols[i]) print(exchanges[i]) print(i) app.reqFundamentalData(8001 , contract, "ReportsFinSummary", []) def error(self, reqID:TickerId, errorCode:int, errorString:str): print("Error: ", reqID, " " , errorCode, " ", errorString) def fundamentalData(self, reqId: TickerId, data: str): super().fundamentalData(reqId, data) print("FundamentalData. ", reqId, data) e = ET.fromstring(data) e.tag e.attrib ##code to parse the XML file returned from the ib reqfundamentaldata function. ##there are multiple report types and I am uncertain what they mean, worth ##looking into later. row_list = [] for atype in e.iter('TotalRevenue'): if atype.attrib['reportType']=="A" and atype.attrib['period']=="3M": dict1 = {"Date": atype.attrib['asofDate'], 'Revenue':atype.text} row_list.append(dict1) columns = ['Date', 'Revenue'] tr = pd.DataFrame(row_list, columns=columns) row_list = [] for atype in e.iter('DividendPerShare'): if atype.attrib['reportType']=="A" and atype.attrib['period']=="3M": dict1 = {"Date": atype.attrib['asofDate'], 'Dividend':atype.text} row_list.append(dict1) columns = ['Date', 'Dividend'] dps = pd.DataFrame(row_lis…
tagged with: python
has answer: http://stackoverflow.com/a/49330651
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/85830862
comment on: http://stackoverflow.com/a/49414591
type: Comment
score: 0
type: AnswerComment
has text: @Shashank Das make sure you give feedback after following the procedure

http://stackoverflow.com/q/49339025
answer count: 1
has title: PyQt: mainWindow closed, but process still running
score: 1
favorite count: 0
type: Question
has body: I'm writing a Python application with PyQt 5.10. It seems I have some sort of bug/memory leak, since when I call close() on my MainWindow the process keeps running. After a bit of research and debugging I was able to circumscribe the supposedly faulty code. This is my main: if __name__ == '__main__': app = QApplication(sys.argv) matteo = God() matteo.runApp() sys.exit(app.exec()) Here you will find the runApp function from God class: def runApp(self): self.painter = Painter() self.dbManager = DBManager() self.userInput = UserInput() self.excelFile = ExcelFile() self.painter.connectToClasses(self, ["god","db","ui"]) self.excelFile.connectToClasses(self, ["god",]) self.painter.drawMainWindow() self.loadConf() self.openDB(True) if self.dbManager.error==None: self.painter.drawSearchWidget() else: print("Closed.") The process keeps running when the app is not able to find the configuration file, and so it creates a new one from scratch and it asks the user to select the database which he wants to connect to. This prompts an error message - if the selected file is corrupted or it's not the right format - and I think there might lie my problem. That's the code: def checkError(self, classType): if classType=="db": error = self.dbManager.error elif classType=="excel": error = self.excelFile.error if error!=None: self.painter.drawError(classType) self.userInput.error = self.painter.error.clickedButton() self.userInput.error = self.painter.error.buttonRole(self.userInput.error) if (self.userInput.error==1): self.painter.mainWindow.close() return 0 return 1 def drawError(self, classType): if (classType=="db"): title = "Database" error = self.dbManager.error otherButton = "Browse" elif (classType=="excel"): title = "Excel file" error = self.excelFile.error try: self.setErrorText(False, error) if error[0]: if self.error.icon()!=3: self.error.setIcon(3) buttons = self.error.buttons() for button in buttons: if button.text()!="Quit": button.hide() button.deleteLater() except Attribu…
tagged with: pyqt
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: qt
has answer: http://stackoverflow.com/a/49531963

http://stackoverflow.com/comment/85875971
has text: .. Try `np.ix_`?
comment on: http://stackoverflow.com/q/49437047
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85746613
has text: Your nested package name is `package.config_files`, not `config_files`.
comment on: http://stackoverflow.com/q/49372505
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85983821
comment on: http://stackoverflow.com/a/49454711
has text: Deployment here refers to the fact that the web application sometimes needs to be updated (new code replaces old codes). But I want the processes launched by the app to keep running since they are atomic computations, i.e. unrelated to the web app itself. Turning them to UNIX deamon seems a good option to me.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49420350
type: Answer
has body: I think this is what you want: ((?:and )?\w+ talked to) The (?:and ) is a non capturing group, so it matches but isn't captured.
accepted answer of: http://stackoverflow.com/q/49420276
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85842974
answers question: http://stackoverflow.com/q/49420276
score: 5
upvote count: 5

http://stackoverflow.com/a/49418827
has comment: http://stackoverflow.com/comment/85839316
has comment: http://stackoverflow.com/comment/85839336
type: AcceptedAnswer
type: Answer
score: 0
has body: The problem is that you're not using a global variable. To use a global variable in a function, you have to put the global statement in that function, not at the top level. Because you didn't, the Counter inside doit is a local variable. Any variable that you assign to anywhere in a function is local, unless you have a global (or nonlocal) declaration. And the first time you use that local Counter is right at the top of the while loop, before you've assigned anything to it. So, it's going to raise an UnboundLocalError immediately. This exception will be propagated back to the main thread as the result of the future. Which you would have seen, except that you never actually evaluate your futures. You just do this: tGen = {executor.submit(doit, PinS): PinS for PinS in NList} for NLister in concurrent.futures.as_completed(tGen): PinS = tGen[NLister] So, you get the PinS corresponding to the function you ran, but you don't look at the result or exception; you just ignore it. Hence you don't see that you're getting back 100 exceptions, any of which would have told you what was actually wrong. This is equivalent to having a bare except: pass in non-threaded code. Even if you don't want to check the result of your futures in "production" for some reason, you definitely should do it when debugging a problem. Anyway, just put the global in the right place, and your bug is fixed. However, you do have at least two other problems. First, sharing globals between threads without synchronizing them is not safe. In CPython, thanks to the GIL, you never get a segfault because of it, and you often get away with it completely, but you often don't. You can miss counts because two threads tried to do Counter = Counter + 1 at the same time, so they both incremented it from 42 to 43. And you can get a stale value in the while Counter &lt; 10000: check and go through the loop an extra time. Second, you don't check the Counter until you've finished downloading and processing a complete requ…
answers question: http://stackoverflow.com/q/49418638
accepted answer of: http://stackoverflow.com/q/49418638
has comment: http://stackoverflow.com/comment/85839329

http://stackoverflow.com/comment/85839949
comment on: http://stackoverflow.com/q/49419243
score: 0
type: Comment
type: QuestionComment
has text: What do the two nested `while True` do?

http://stackoverflow.com/q/49325796
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85653241
accepted answer: http://stackoverflow.com/a/49326143
type: AnsweredQuestion
has body: I have this list: n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135', '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121'] And this dictionary: i = {'10.2.94.38': {'area': '0.0.1.8'}} As you can see, there is only one item inside the list, which is a valid key for the dictionary: 10.2.94.38. If I do the following, I can get the inner diciontary {'area':'0.0.1.8'}: &gt;&gt;&gt; [i.get(x,'NA') for x in n] ['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', {'area': '0.0.1.8'}, 'NA', 'NA'] If I do the following, I can get the value 0.0.1.8, as usual: &gt;&gt;&gt; i[n[8]]['area'] '0.0.1.8' The problem I'm facing is that I cannot reach the ultimate value 0.0.1.8. I've tried the following without success: &gt;&gt;&gt; [i.get(x['area'],'NA') for x in n] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;listcomp&gt; TypeError: string indices must be integers How can I do it? The final result that I want to achieve is: ['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '0.0.1.8', 'NA', 'NA'] Thanks! Lucas
has title: Get inner nested dictionary with key stored in list
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49326143
score: 1
has comment: http://stackoverflow.com/comment/85653130
has answer: http://stackoverflow.com/a/49333363
tagged with: nested
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85653291
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49333363
tagged with: python

http://stackoverflow.com/a/64833436
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49392972
has body: For me, this worked. from keras.utils import to_categorical num_labels=10 #for my case train_labels=to_categorical(train_labels,10) test_labels=to_categorical(test_labels,10) Specifying the number of labels as an argument while categorically encoding my labels helped train effectively on my training set.

http://stackoverflow.com/comment/85796477
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49397259
has text: @user2357112 Yeah, there is a gap there. The real problem is trying to come up with a way to handle `KeyboardInterrupt` and friends without either requiring 2.6+, requiring 2.x only, or writing a separate `except` for each special exception.

http://stackoverflow.com/a/49353254
upvote count: 4
answers question: http://stackoverflow.com/q/49353201
has body: super is working correctly; however, after the super call, you override every attribute with the values passed to the child constructor. Instead, simply call super and do not initialize the child class with the same attributes: class Engineer(Person): def __init__(self, *args): super().__init__("Bla bla", 10, 100) def describe(self): return super().describe() my_engineer = Engineer("Larry", 17, 120) print(my_engineer.describe()) Output: Bla bla, 10, 100
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/comment/85844907
type: QuestionComment
has text: Sure. I'm trying to get data from this page http://killedbypolice.net/
comment on: http://stackoverflow.com/q/49421764
score: 0
type: Comment

http://stackoverflow.com/a/49302503
has body: Make sure that you already installed cron with your Dockerfile It should be something like RUN apt-get install -y cron
has comment: http://stackoverflow.com/comment/132936923
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49302298
score: 40
upvote count: 40
answers question: http://stackoverflow.com/q/49302298
type: Answer

http://stackoverflow.com/a/49308968
answers question: http://stackoverflow.com/q/49308718
downvote count: 1
has comment: http://stackoverflow.com/comment/85620144
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85620431
score: -1
has comment: http://stackoverflow.com/comment/85620261
has body: The only thing you need to do is walk the list, counting the number of times sequence[i] &gt; sequence[i+1]. If it happens at most once, your list is almost monotonically increasing. def almostIncreasingSequence(sequence): count = 0 for i in range(0, len(sequence) - 1): if sequence[i] &gt; sequence[i+1]: count += 1 return count &lt; 2 You can also avoid counting, since the number of exceptions is small. Just return False as soon as you find the second exception, as tracked by the value of a Boolean variable initialized to True. def almostIncreasingSequence(sequence): increasing = True for i in range(0, len(sequence) - 1): if sequence[i] &gt; sequence[i+1]: if increasing: increasing = False else: return False return True

http://stackoverflow.com/comment/92817917
score: 0
has text: What happens if you pass `test()` into `consumer`? According to python 3.7 `type(test)` is `function`, while `type(test())` is `coroutine`, despite `test` being a coroutine and pyre-check finding no errors in your code.
comment on: http://stackoverflow.com/q/49360480
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85727670
has text: Sure! 1) https://pastebin.com/KcUZZkp9 2) https://pastebin.com/sAtXvbjx 3) https://pastebin.com/M09xL466 4) https://pastebin.com/PYDb7k6p this is in raw geojson format
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49352969
score: 0

http://stackoverflow.com/q/49321617
has answer: http://stackoverflow.com/a/49321761
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85644285
has comment: http://stackoverflow.com/comment/85645230
tagged with: python
possible better answer: http://stackoverflow.com/a/49321732
answer count: 4
has title: Pythonic way of splitting loop over list in two parts with one iterator
has answer: http://stackoverflow.com/a/49322792
has answer: http://stackoverflow.com/a/49321782
has comment: http://stackoverflow.com/comment/85645535
has answer: http://stackoverflow.com/a/49321732
type: AnsweredQuestion
has body: I am processing a text file with an irregular structure that consists of a header and of data in different sections. What I aim to do is walk through a list and jump to the next section once a certain character is encountered. I made a simple example below. What is the elegant way of dealing with this problem? lines = ['a','b','c','$', 1, 2, 3] for line in lines: if line == '$': print("FOUND END OF HEADER") break else: print("Reading letters") # Here, I start again, but I would like to continue with the actual # state of the iterator, in order to only read the remaining elements. for line in lines: print("Reading numbers")
tagged with: list
tagged with: iterator
has comment: http://stackoverflow.com/comment/85645200
accepted answer: http://stackoverflow.com/a/49321761
score: 3
upvote count: 3

mining
type: Tag
tags question: http://stackoverflow.com/q/49369171
tag name: mining

joystick
type: Tag
tags question: http://stackoverflow.com/q/49352561
tag name: joystick

http://stackoverflow.com/comment/85673757
comment on: http://stackoverflow.com/a/49329047
type: AnswerComment
has text: Its not harsh at all. Bad code is bad code. Now that you have made the change I can change my vote.
score: 0
type: Comment

http://stackoverflow.com/a/49356953
type: Answer
score: 0
has body: I found an answer based on a similar problem. before creating the connection / the engine I set the NLS_LANG to the settings of the database: os.environ["NLS_LANG"] = 'AMERICAN_AMERICA.WE8ISO8859P1' This avoids a transformation made by cx_oracle which causes the error.
answers question: http://stackoverflow.com/q/49326271

http://stackoverflow.com/comment/85773959
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49386402
type: QuestionComment
has text: As pointed out above there are many services but Amazon's is easy to use, see this answer: https://stackoverflow.com/questions/6030115/how-to-run-a-code-in-an-amazones-ec2-instance

http://stackoverflow.com/q/49323159
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85729164
score: 0
has title: Pandas Pivot causes all values to be NaN
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85717307
tagged with: dataframe
has answer: http://stackoverflow.com/a/49324826
has body: I have a pandas dataframe consisting of 12 columns and 900 entries which looks like this: In [1]: df Out[2]: Id BestInGen Ceiling Fitness Floor Generation Name Precision Runid SolutionId Timestamp Value 0 1 True 2.5 2.416582e+11 0.500 1 H1001Thickness1 0.010 20180214142319 4 2018-02-14 14:28:41.391908 0.500 1 2 False 0.1 2.830500e+11 0.015 1 H6512Diameter8 0.005 20180214142319 3 2018-02-14 14:28:41.423109 0.015 2 3 False 2.5 2.830500e+11 0.500 1 H2201Thickness1 0.010 20180214142319 3 2018-02-14 14:28:41.423109 0.500 3 4 False 0.1 2.830500e+11 0.015 1 H2201Diameter1 0.005 20180214142319 3 2018-02-14 14:28:41.423109 0.015 4 5 False 2.5 2.830500e+11 0.500 1 H2201Thickness2 0.010 20180214142319 3 2018-02-14 14:28:41.423109 0.500 I want to pivot this dataframe such that 'Name' is turned into columns, and the rows populated by 'Value'. Currently I have tried the following: dfPivot = df.pivot(index='Id',columns='Name',values='Value) I thought this would create the results I need, and that has been the case for the other threads ive seen. But in my case the following happens In [3]: dfPivot Out [4]: Name H1001Diameter1 H1001Diameter10 H1001Diameter12 Id 1 Nan Nan Nan And the same continues to the end of the dataframe, all values being Nan. The original datatype is a float64, and there are no Nans in the original data. Any pointers on how to solve this? Sorry if this is a noob question, or please let me know if you need me to edit my question/example.
has comment: http://stackoverflow.com/comment/85651765

http://stackoverflow.com/q/49286123
has comment: http://stackoverflow.com/comment/100199556
tagged with: python-3.x
has body: I am looking for a way to obtain a Python list and display it on my website using PHP. I've checked out and tried many online help-requests so I was hoping someone would be able to explain to me what it is I am doing wrong. My Python script scrapes a website and puts the result in a Python list. What I am trying to achieve is the following: I want to display (a part) of the list on my website. I've tried to accomplish this with the following code: PHP &lt;?php $outputArray = []; $returnStatus; exec('python ./scrapeWebsite.py', $outputArray, $returnStatus); var_dump($outputArray); echo $returnStatus; ?&gt; Python: print(newsHeadlines) -> returning a list like this: ['item 1','item 2','item 3','item 4'] However, the array comes back as array(0) { } and the $returnStatus value is 1.
has comment: http://stackoverflow.com/comment/85575190
has answer: http://stackoverflow.com/a/49298626
tagged with: python
type: UnansweredQuestion
tagged with: php
has title: Get python list in PHP
answer count: 1
has comment: http://stackoverflow.com/comment/85581030
linked to: http://stackoverflow.com/q/46226655
type: Question
has comment: http://stackoverflow.com/comment/85575403
score: 0

http://stackoverflow.com/a/49351598
has comment: http://stackoverflow.com/comment/85708967
has body: Since it's difficult to reproduce the exact data you are working on, this solution should give you enough hint: # create minimal sample data df1 = pd.DataFrame({'employee_id':[1,2,3,4,5,6], 'gps':[1,1,1,1,1,1], 'event_params' : ['{"type":"Down","maximumangle":0,"duration":0}', '{"type":"Left","maximumangle":-38.57,"duration":203}', '{"type":"Right","maximumangle":52.975,"duration":17}', '{"type":"Down","maximumangle":0,"duration":0}', '{"type":"Down","maximumangle":0,"duration":0}', '{"type":"Left","maximumangle":-10.866,"duration":40}']}) # save event_params column to a new value while removing from df1 df2 = df1.pop('event_params') # convert values to dictionary format using ast library import ast df2 = df2.apply(ast.literal_eval) # convert dictionary to column format and add back to df1 df2 = pd.DataFrame(list(df2)) df1 = pd.concat([df1, df2], axis=1) print(df1) employee_id gps duration maximumangle type 0 1 1 0 0.000 Down 1 2 1 203 -38.570 Left 2 3 1 17 52.975 Right 3 4 1 0 0.000 Down 4 5 1 0 0.000 Down 5 6 1 40 -10.866 Left Edit 1: To convert all event_params in dictionary format: df2 = df2.apply(lambda x: ast.literal_eval(x) if isinstance(x, dict) else x)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85710016
has comment: http://stackoverflow.com/comment/85913788
downvote count: 0
has comment: http://stackoverflow.com/comment/85710634
upvote count: 1
has comment: http://stackoverflow.com/comment/85708283
answers question: http://stackoverflow.com/q/49351190
has comment: http://stackoverflow.com/comment/85912269
has comment: http://stackoverflow.com/comment/85913973

http://stackoverflow.com/q/49417315
favorite count: 0
type: Question
has body: Suppose I pass a 1D array: &gt;&gt;&gt; np.arange(0,20) array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) &gt;&gt;&gt; np.arange(0,20).shape (20,) into argwhere: &gt;&gt;&gt; np.argwhere(np.arange(0,20)&lt;10) array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]) &gt;&gt;&gt; np.argwhere(np.arange(0,20)&lt;10).shape (10, 1) why has the result changed into a 2D array? What's the benefit of this?
type: AnsweredQuestion
has title: Why does np.argwhere's result shape not match it's input?
has answer: http://stackoverflow.com/a/49417564
upvote count: 5
has answer: http://stackoverflow.com/a/49417471
possible better answer: http://stackoverflow.com/a/49417471
tagged with: python
tagged with: numpy
answer count: 3
score: 5
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/49417394
accepted answer: http://stackoverflow.com/a/49417394

http://stackoverflow.com/q/49323740
has comment: http://stackoverflow.com/comment/85649783
has comment: http://stackoverflow.com/comment/85649043
has answer: http://stackoverflow.com/a/49324184
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49325667
has comment: http://stackoverflow.com/comment/85649157
has comment: http://stackoverflow.com/comment/85649045
has body: I have CSV files with up to 10M+ rows. I am attempting to get the total line numbers of a file so I can split the processing of each file into a multiprocessing approach. To do this, I will set a start and end line for each sub-process to handle. This cuts down my processing time from 180s to 110s for a file size of 2GB. However, in order to do this, It requires to know the line number count. If I attempt to get the exact line number count, it will take ~30seconds. I feel like this time is wasted as an approximate with the final thread possibly having to read an extra hundred thousand lines or so, would only add a couple seconds as apposed to the 30 seconds it takes to get the exact line count. How would I go about getting an approximate line count for files? I would like this estimate to be within 1 million lines (Preferably within a couple hundred thousand lines). Would something like this be possible?
favorite count: 0
has comment: http://stackoverflow.com/comment/85649685
has comment: http://stackoverflow.com/comment/85648888
has comment: http://stackoverflow.com/comment/85649504
score: -2
has title: How to get approximate line number of large files
has comment: http://stackoverflow.com/comment/85648810
tagged with: python
tagged with: filereader
has comment: http://stackoverflow.com/comment/85649420
has comment: http://stackoverflow.com/comment/85649180
has comment: http://stackoverflow.com/comment/85649152
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85648952
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/85787259
has text: Not quite sure what your data looks like, or how you intend to average? Are you averaging the 3 vals in the file? Or the 30 vals for each participant? The following code may help you to the next step- have a look at it, and I can update once I have a better idea of where you are going with this.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49392523

http://stackoverflow.com/q/49438167
answer count: 0
tagged with: sentiment-analysis
score: 1
downvote count: 0
upvote count: 1
has body: I have to use machine learning in class where I have a training data set and a test data set, its very difficult for me as I don't come from a coding background and they told me before i chose it that the class would be suitable for people without much prior knowledge. I have processed the training data into a csv file where the first column is the review and the second column is its sentiment in the form of 1 or 0 I have loaded the file and processed it like this: def load_file(): with open('trainingdatafile.csv') as csv_file: reader = csv.reader(csv_file, delimiter=",", quotechar='"') reader.next() data = [] target = [] for row in reader: # skip missing data if row[0] and row[1]: data.append(row[0]) target.append(row[1]) return data, target And I have processed the data like this : def preprocess(): data, target = load_file() count_vectorizer = CountVectorizer(binary='true') data = count_vectorizer.fit_transform(data) tfidf_data = TfidfTransformer(use_idf=False).fit_transform(data) return tfidf_data I have found a way to make it work where I split the training data up and use part of it to train and the rest to test like so: def learn_model(data, target): # preparing data for split validation. 60% training, 40% test data_train, data_test, target_train, target_test = cross_validation.train_test_split(data, target, test_size=.2, random_state=1) classifier = BernoulliNB().fit(data_train, target_train) predicted = classifier.predict(data_test) evaluate_model(target_test, predicted) the rest of the code is here: def evaluate_model(target_true, target_predicted): print classification_report(target_true, target_predicted) print "The accuracy score is {:.2%}".format(accuracy_score(target_true, target_predicted)) def main(): data, target = load_file() tf_idf = preprocess() learn_model(tf_idf, target) What would be the best way to adapt my code so that I can evaluate my test.csv file with the training data? I am really stuck with how to achieve what I want so any help would…
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to use seperate training and test file for python machine learning?
tagged with: naivebayes
tagged with: machine-learning
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/a/49378740
has comment: http://stackoverflow.com/comment/85801014
has body: You should do the seek on the file before decompressing. Usually, WARC files are compressed record by record and the offset and length in the CDXJ allow to clip out a single WARC record, then do a gzip.open() then on the single record. In doubt, better use a library. Warcio even provides a command-line tool to extract a single record by offset: warcio extract xyz.warc.gz offset.
has comment: http://stackoverflow.com/comment/85760380
accepted answer of: http://stackoverflow.com/q/49377839
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49377839
has comment: http://stackoverflow.com/comment/85760681
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85804754
downvote count: 0
has comment: http://stackoverflow.com/comment/85776082
type: Answer

http://stackoverflow.com/q/49287434
favorite count: 0
type: Question
tagged with: python-3.x
has body: How do I get otherImages to return the string in it so that I can replace a word within it when called from 'narrow' method? def otherImages(self): self.wfile.write(bytes("&lt;div id='menu_button'&gt;&lt;a href='/narrow'&gt;&lt;img src='../images/menu_button.png'&gt;&lt;/a&gt;&lt;/div&gt;", "utf8")) #^word I want to replace def contentList(self, skip_name=''): # All content methods in list methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages] for m in methods: if m.__name__ != skip_name: m() def narrow(self): try: self.reply() self.contentList('onlineSection') # removed onlineSection for words in self.otherImages(): words.replace("narrow", "index")
has answer: http://stackoverflow.com/a/49288150
accepted answer: http://stackoverflow.com/a/49288150
has comment: http://stackoverflow.com/comment/85577967
tagged with: python
score: -1
tagged with: basehttpserver
has answer: http://stackoverflow.com/a/49287473
possible better answer: http://stackoverflow.com/a/49287473
type: AnsweredQuestion
upvote count: 0
answer count: 2
has title: Object is not iterable when replacing word called by function
downvote count: 1

http://stackoverflow.com/a/49328741
has body: Try This: import os path = raw_input('Please enter the directory: ') for root, directories, filenames in os.walk(path): for filename in filenames: full_path = os.path.join(root, filename) size = os.path.getsize(full_path) print full_path + ' &gt;&gt; ' + str(size)
score: 0
accepted answer of: http://stackoverflow.com/q/49328339
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85660006
type: Answer
answers question: http://stackoverflow.com/q/49328339

http://stackoverflow.com/q/49335297
type: Question
has comment: http://stackoverflow.com/comment/85673015
has body: I am making a tkinter project for school. In the project, I need to use transparent images. In my school, the tkinter only supports GIFs so I cannot use a PNG. Moreover, only the modules that come with python 3 when installing are supported. We cannot download more. Is there a way to solve my problem?
score: -2
has answer: http://stackoverflow.com/a/49353569
linked to: http://stackoverflow.com/q/22583035
tagged with: python
has comment: http://stackoverflow.com/comment/85672137
has comment: http://stackoverflow.com/comment/85672112
tagged with: python-3.x
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/49335351
upvote count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: transparent
has title: How can I use transparent images in tkinter without png?
favorite count: 0

http://stackoverflow.com/comment/85795173
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49396695
type: QuestionComment
has text: What exactly do you mean by "convert float number to binary"? You can't pack a string as a float, and I'm not sure why you'd even want to pack a float and then unpack the first half of the result as an int, so… it's very hard to guess what this is even trying to do.

http://stackoverflow.com/comment/85751961
type: AnswerComment
has text: Your explanation is *almost* correct
comment on: http://stackoverflow.com/a/49356663
score: 0
type: Comment

http://stackoverflow.com/q/49399658
has answer: http://stackoverflow.com/a/49401351
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49400455
answer count: 3
possible better answer: http://stackoverflow.com/a/49400455
has comment: http://stackoverflow.com/comment/85800449
downvote count: 3
has body: I want to print Hello World n**n times without calculating the value of n**n in python. eg, if n is 2, it should print 'Hello World' 4 times. if n is 3 it should print 'Hello World' 27 times and so on. I am allowed to use loops and recursion but now allowed to use any inbuilt function or calculate the value of n **n and print that many times. Thank you in advance.
has comment: http://stackoverflow.com/comment/85800531
accepted answer: http://stackoverflow.com/a/49400020
tagged with: loops
has comment: http://stackoverflow.com/comment/85800520
favorite count: 0
type: Question
tagged with: exponent
tagged with: recursion
has comment: http://stackoverflow.com/comment/85800458
has comment: http://stackoverflow.com/comment/85800457
has title: n power n print 'Hello World' without calculating the value
has comment: http://stackoverflow.com/comment/85800598
score: -3
has comment: http://stackoverflow.com/comment/85801117
has answer: http://stackoverflow.com/a/49400020
tagged with: python

http://stackoverflow.com/q/49338836
has title: Calculation on Trilateration in Python
type: Question
has body: i have 3 nodes that will send the package that consist of coordinates (latitude, longitude) and rssi value to the gateway at the same time i using the formula of *distance = 10** ((measured power - rssi) / (10*n))* to obtained the distance. Which mean i have 3 (latitude, longitude, distance).I tried to get the distance but the unknown target location is confused.
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/85677938
answer count: 0
has comment: http://stackoverflow.com/comment/85690128

http://stackoverflow.com/a/49350502
score: 0
accepted answer of: http://stackoverflow.com/q/49347864
has body: This is still probably not as efficient as you could get, but is better I think. This would replace from your "#create D matrix, dataframe containing..." comment onwards # create prices P P = pd.DataFrame() for index, row in F.iterrows(): new_P_row = pd.Series() for date in pd.date_range(row['startdate'], row['enddate']): new_P_row[date] = row['price'] P = P.append(new_P_row, ignore_index=True) P.fillna(0, inplace=True)
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49347864

http://stackoverflow.com/comment/85842513
has text: Anyway, a general way to start at this: for each property, first do `sorted(players, key=itemgetter(propname))`, then do `groupby` on the same key. So for the school, you have a group of all the WSU players, a group of all the ASU players, etc. Then from the position, you get a group of all QBs, a group of all RBs, etc. If you need to do any merging or filtering, you can do that after the fact. Depending on what that merging or filtering is, it may be less efficient to build up more than you need just to merge, but only by a constant factor, and it's a lot simpler to think about.
comment on: http://stackoverflow.com/q/49399471
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85845669
type: AnswerComment
comment on: http://stackoverflow.com/a/49419180
type: Comment
has text: A variant `[var for arg, var in zip(input, var_list) if arg]`.
score: 0

http://stackoverflow.com/comment/85620037
has text: It depends on how you want to store the values. Do you want just to save them like this `[93.400000000000006, "high"]` or like this `93.400000000000006,"high"`. Pleasge give us an example how your output should look like
type: QuestionComment
comment on: http://stackoverflow.com/q/49308879
score: 1
type: Comment

http://stackoverflow.com/q/49375655
type: UnansweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85755115
answer count: 0
has body: I'm trying to write an application that acts as an event listener on a server. I'm currently deploying a test server with python SimpleHTTPServer and tunneling it out using ngrok, so I can have a public url in order to add a callback url to each contract. Below is a picture of the callback I am receiving from the SimpleHTTPServer terminal. I also have a simple GUI using tkinter called gui.py shown below: If the user clicks scan, the application should start scanning the server for any events and process the response if found. I tried tried to create a client.py and using socket to connect to the server and I was able to successfully connect with the following code below. import socket class Client: def __init__(self): # Assign ip &amp; port number to instance variable self.HOST = '127.0.0.1' self.PORT = 4040 # Set up our main socket self.main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self): # Try and connect the socket to the server try: # Binding out host and ip to the socket self.main_socket.connect((self.HOST, self.PORT)) return 'Server Connected...' # Print any error message for not being able to connect except Exception as e: return str(e) def disconnect(self): # Try and disconnect the socket from the server try: # Call the disconnect function to disconnect the socket self.main_socket.close() return 'Server Disconnected...' # Print any error message from not being able to connect except Exception as e: return 'Cannot disconnect from the server: ' + e Question: Is there anyway for me to capture the event from the SimpleHTTPServer terminal (Picture 1) and store them into variables? I read up on using subprocesses, but not sure if that would apply in this case.
upvote count: 1
has comment: http://stackoverflow.com/comment/85754612
downvote count: 0
has comment: http://stackoverflow.com/comment/85754862
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85753950
has title: Extracting Get / Post events from server terminal using Python

http://stackoverflow.com/a/49333365
accepted answer of: http://stackoverflow.com/q/49333333
has body: Here's how I'd do it. You need two checks in your while - one to make sure i does not cross position, and the other is to ensure that you do not fall off the end of the linked list (possible when position is greater than the size of your linked list). If you are to insert at position, i should stop at position - 1. Then, set cur.next to be temp, and temp.next to be cur.next's old value. You do not need a surrogate object for swapping pointers (next_node, in your code is unnecessary). def insert(head, data, position): temp = Node(data) # handle all the base cases - empty list or position == 0 if not head or position == 0: temp.next = head head = temp else: cur = head i = 0 while i &lt; position - 1 and cur.next is not None: cur = cur.next i += 1 temp.next = cur.next cur.next = temp return head Follow PEP8 standards please, snake case for identifier names only. Challenge can be found at https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49333333
has comment: http://stackoverflow.com/comment/85668725
type: Answer
has comment: http://stackoverflow.com/comment/85668659
has comment: http://stackoverflow.com/comment/85668632
has comment: http://stackoverflow.com/comment/85669205
has comment: http://stackoverflow.com/comment/85668878
score: 0

http://stackoverflow.com/comment/110795505
comment on: http://stackoverflow.com/q/49369254
score: 0
type: Comment
has text: Hi , did you find any help about this?
type: QuestionComment

http://stackoverflow.com/comment/85645193
has text: "*the *= operator changed the original deep copy to shallow copy!*" - I think this reveals the fundmental misunderstanding. The `=` operator on "*the previous line*" does **not** copy anything. There is no copy implied by `=`, only binding a new name to an existing object.
comment on: http://stackoverflow.com/q/49321725
score: 1
type: Comment
type: QuestionComment

google-calendar-api
tags question: http://stackoverflow.com/q/49374112
type: Tag
tag name: google-calendar-api

http://stackoverflow.com/q/49425220
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85851389
has comment: http://stackoverflow.com/comment/85851478
accepted answer: http://stackoverflow.com/a/49425249
has body: I am new Python Programmer. I want to solve this problem, series1 = pd.Series([1,2,3,4,5]) series2 = pd.Series([1,3,3,4,6]) data1 = pd.DataFrame([series1,series2]) data_frame = pd.DataFrame(index=[], columns=['column1', 'column2']) data_frame['column1'] = series1 data_frame['column2'] = series2 There are two columns, column1, column2. And I want to judge from these two columns to see I tried these code below. But, It doesn't work. Please give me the advice? judgeList = [] def judgeBool(x): judgeList.append(x) if len(judgeList) == 2: if judgeList[0] == judgeList[1]: series = pd.Series([True]) data_frame = data_frame.append(series, ignore_index = True) else: series = pd.Series([False]) data_frame = data_frame.append(series, ignore_index = True) data_frame.apply(lambda x: judgeBool(x), axis = 1)
tagged with: python
has answer: http://stackoverflow.com/a/49425249
has title: Judge two columns of row to see equal or not. and create the Bool Column
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/44067524
upvote count: 1
score: 1

http://stackoverflow.com/comment/85874245
type: Comment
has text: When using a web framework like Flask, an asynchronous queue like Celery is way more popular than threading.
type: QuestionComment
comment on: http://stackoverflow.com/q/49434727
score: 0

http://stackoverflow.com/comment/86027237
type: QuestionComment
score: 0
has text: The method `save` of `ItemForm` makes no sense to me. First you call the parent method with `item = super().save(commit=False)` but you don't return `item`. Assigning values to `item.box_one` and `item.box_two` goes with the wind. At the end you're just trying to save an instance of the related `Code` model.
type: Comment
comment on: http://stackoverflow.com/q/49350041

http://stackoverflow.com/comment/85712755
comment on: http://stackoverflow.com/q/49356294
score: 0
has text: 1 of the above, since condition 1 and 2 are mutually exclusive, right?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49370132
downvote count: 0
has comment: http://stackoverflow.com/comment/85792139
has comment: http://stackoverflow.com/comment/85754241
upvote count: 1
has body: Since there are a few parts to your question: You can save JSON to Firebase and the data will be mapped to child locations: Using PUT, we can write a string, number, boolean, array or any JSON object to our Firebase database...When a JSON object is saved to the database, the object properties are automatically mapped to child locations in a nested fashion. https://firebase.google.com/docs/database/rest/save-data And for your next question: And would it be possible to filter this json with python for example; when I add region=eu in the url this returns the objects which have Europe as region Looks like you should be able to jimmy something together with Firebase's filters, startAt and endAt: We can combine startAt and endAt to limit both ends of our query. https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-filtering For your example you might do something like this: curl 'https://yourfirebase.firebaseio.com/yourendpoint.json?orderBy="$REGION_NAME"&amp;startAt="EU"&amp;endAt="EU"&amp;print=pretty' ...or do I absolutely need to request the entire json file and parse in my code (java android) ? The facts that JSON objects are stored hierarchically in Firebase and that you can filter based on those object values makes me think you do not, in fact, have to request the entire JSON file. However, I don't have personal experience with this particular aspect of Firebase, so give it a shot! As @ackushiw mentions in the comments, you can also use the equalTo query (https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo): curl 'https://yourfirebase.firebaseio.com/yourendpoint.json?orderBy="$REGION_NAME"&amp;equalTo="EU"&amp;print=pretty'
has comment: http://stackoverflow.com/comment/85743675
accepted answer of: http://stackoverflow.com/q/49369867
type: Answer
has comment: http://stackoverflow.com/comment/85768801
answers question: http://stackoverflow.com/q/49369867
has comment: http://stackoverflow.com/comment/85741576
score: 1
has comment: http://stackoverflow.com/comment/85741705
type: AcceptedAnswer

http://stackoverflow.com/comment/85584511
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49290736
type: Comment
has text: please fix your indentations so ppl can help you

http://stackoverflow.com/a/49318021
has comment: http://stackoverflow.com/comment/85693797
type: Answer
has comment: http://stackoverflow.com/comment/85692571
has body: This might help. You can use the csv module to read your file. Ex: import csv s = "PATH_TO.csv" res = [] with open(s, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=';') for line in reader: if line: if ")" in line[0]: print "; ".join(line[:7]), "-"*46 Output: 1) Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ---------------------------------------------- 2) Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ----------------------------------------------
score: 0
has comment: http://stackoverflow.com/comment/85717449
answers question: http://stackoverflow.com/q/49316645
has comment: http://stackoverflow.com/comment/85725349

http://stackoverflow.com/q/49348839
has title: How to unit test Neo4j in python ?
tagged with: neo4j
favorite count: 0
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/134830641
upvote count: 12
tagged with: python
has answer: http://stackoverflow.com/a/60401081
score: 12
type: AnsweredQuestion
has body: I have an application backed by Neo4j database written in python. Does anyone know what is the best approach to unit test my application ? I have found this can be easily done in Java with usage of ImpermanentGraphDatabase. Is there a similar approach in python ? Any tips are appreciated.
answer count: 2
has comment: http://stackoverflow.com/comment/87602257
accepted answer: http://stackoverflow.com/a/50343238
downvote count: 0
has answer: http://stackoverflow.com/a/50343238
possible better answer: http://stackoverflow.com/a/60401081

http://stackoverflow.com/comment/132190867
type: Comment
score: 0
type: AnswerComment
has text: I would be more comfortable doing `except KeyboardInterrupt as e` then using `raise e` instead just in case some module higher up in the call chain catches it...
comment on: http://stackoverflow.com/a/49372905

http://stackoverflow.com/a/49322483
score: 0
has body: Use merge with query: df = pd.merge(df1, df2, on='ITEM').query('PRICE &gt;SELLLING_PRICE') print (df) ITEM PRICE SELLLING_PRICE 0 MANGO 5.0 4.0 1 MANGO 5.0 3.0 3 BANANA 2.0 1.0 4 ORANGE 1.5 0.5
type: Answer
answers question: http://stackoverflow.com/q/49322418

http://stackoverflow.com/comment/85697988
comment on: http://stackoverflow.com/a/49349048
has text: Yes, we're allowed to do that. I tried it out but it ended up replacing "AWAY FROM KEYBOARD" with just "AFK FROM KEYBOARD"
type: AnswerComment
score: 0
type: Comment

robotframework
tags question: http://stackoverflow.com/q/49392658
tags question: http://stackoverflow.com/q/49394329
tags question: http://stackoverflow.com/q/49326440
tag name: robotframework
tags question: http://stackoverflow.com/q/49291601
tags question: http://stackoverflow.com/q/49323532
tags question: http://stackoverflow.com/q/49398152
type: Tag

http://stackoverflow.com/comment/85755567
score: 0
comment on: http://stackoverflow.com/q/49376811
type: Comment
type: QuestionComment
has text: @CrisLuengo I do not have any color assumptions.

http://stackoverflow.com/q/49414928
has answer: http://stackoverflow.com/a/49470202
type: AnsweredQuestion
has title: Scapy Exception: Bad condition in format string?
score: 1
tagged with: scapy
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49470202
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have this packet sniffer I made: from scapy.all import * def decode(rawload): #still trying to figure out how to decode the payload return str(rawload) #temporary try: sniff(iface = "wlan0", filter="host 192.168.1.13", prn=lambda x:x.sprintf("src: %IP.src% (%Ether.src%) receiver: %IP.dst% load: {}".format(decode(x.payload)))) #Error right here except KeyboardInterrupt: sys.exit(1) And the error I get is "Scapy Exception: Bad condition in format string: []". Could anyone explain what I'm doing wrong here?
tagged with: byte
tagged with: python
tagged with: python-3.6

http://stackoverflow.com/q/49341093
score: 0
answer count: 1
tagged with: gitlab
has title: deploy Django application to heroku by GitLab
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50077624
has body: I have a Django repository on Django and want to deploy the application on Heroku. I was going through the documentation of GitLab https://docs.gitlab.com/ce/ci/examples/test-and-deploy-python-application-to-heroku.html#configure-project Which is asking to create two variables HEROKU_STAGING_API_KEY HEROKU_PRODUCTION_API_KEY It also states You'll need to create two variables in Project &gt; Variables: and Find your Heroku API key in Manage Account (https://dashboard.heroku.com/account) The link to heroku dashboard revels only API key which might be used but for which variable, I'm not getting it. Also from where to get another variable value? Also there is no option like Project > Variables in GitLab project, so where should I create the specified variables?
tagged with: django
tagged with: python
tagged with: heroku

http://stackoverflow.com/a/49459430
type: Answer
answers question: http://stackoverflow.com/q/49414300
score: 0
has body: I got my code to work by running the file outside my IDE (spyder), in a command window. I guess this counts as a solution, though I still don't know why there was an error in the first place. FWIW, I still got the same ImportError even after adding dependencies to the workers, when I ran the code in my IDE. I'm still interested if anyone knows why this is an issue or what I can do to fix it ...

http://stackoverflow.com/q/49371071
has comment: http://stackoverflow.com/comment/85743356
has comment: http://stackoverflow.com/comment/85743411
type: AnsweredQuestion
downvote count: 4
has comment: http://stackoverflow.com/comment/85743307
has comment: http://stackoverflow.com/comment/85743367
upvote count: 0
score: -4
accepted answer: http://stackoverflow.com/a/49371267
answer count: 1
has comment: http://stackoverflow.com/comment/85743410
has title: n is not defined
has body: if n in range(6, 21) or n % 2 != 0: print("Weird") else: print("Not Weird") if __name__ == '__main__': n = int(input()) The following code is supposed to print "weird" output for odd numbers and "Not weird" for even numbers but instead it is crashing.
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85743296
has comment: http://stackoverflow.com/comment/85743139
has comment: http://stackoverflow.com/comment/85743594
has comment: http://stackoverflow.com/comment/85743345
has answer: http://stackoverflow.com/a/49371267
tagged with: python
has comment: http://stackoverflow.com/comment/85743274

http://stackoverflow.com/comment/85642074
comment on: http://stackoverflow.com/a/49320133
type: AnswerComment
score: 1
has text: Thanks for your comment. I was afraid this could not work, the image is pretty noisy. Sauvola threshold looks promising, i will try that too!
type: Comment

http://stackoverflow.com/comment/85669590
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49333948
has text: You use Python 2 to learn the language? [Is there a specific reason for this?](https://pythonclock.org/)
type: Comment

http://stackoverflow.com/comment/85801590
type: QuestionComment
has text: @ekhumoro Thanks for response but you are not right with second comment. I tested it with infinity recursion and i got one msgbox and crash log without any problem. There is a quit() after msgBox.
score: 0
comment on: http://stackoverflow.com/q/49386039
type: Comment

http://stackoverflow.com/q/49417352
has answer: http://stackoverflow.com/a/49417621
tagged with: python
has comment: http://stackoverflow.com/comment/85836595
has answer: http://stackoverflow.com/a/49417525
has comment: http://stackoverflow.com/comment/85836677
linked to: http://stackoverflow.com/q/16060899
downvote count: 0
has answer: http://stackoverflow.com/a/49417422
score: 1
upvote count: 1
has body: Trying to get this program to translate letters into numbers so a telephone number with words can be input and will output the number version. (1800GOTJUNK = 18004685865) Not sure where Im going wrong but every output just gives whatever the last letter is and repeats its number for all numbers (1800adgjmptw = 18009999999). Any help would be greatly appreciated, thanks. def transNum(string): number = 1 for ch in string: if ch.lower() in "abc": number = 2 elif ch.lower() in "def": number = 3 elif ch.lower() in "ghi": number = 4 elif ch.lower() in "jkl": number = 5 elif ch.lower() in "mno": number = 6 elif ch.lower() in "pqrs": number = 7 elif ch.lower() in "tuv": number = 8 elif ch.lower() in "wxyz": number = 9 return number def translate(phone): newNum = "" for ch in phone: if ch in ["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"]: newNum = newNum + str(transNum(phone)) else: newNum = newNum + ch return newNum def main(): phone = input("enter a phone number") noLetters = translate(phone) print("The number you entered: ", phone) print("Translates to: ", noLetters) main()
has answer: http://stackoverflow.com/a/49417449
favorite count: 0
has answer: http://stackoverflow.com/a/49417542
type: Question
has comment: http://stackoverflow.com/comment/85836632
answer count: 5
type: UnansweredQuestion
has title: Python 3.6 - How to translate a telephone number with words

http://stackoverflow.com/comment/94899356
type: Comment
comment on: http://stackoverflow.com/q/49432252
score: 0
has text: Thanks @JanŠpaček. It seems there is an example here https://github.com/svn2github/pylucene/blob/master/test2/test_Similarity.py
type: QuestionComment

http://stackoverflow.com/comment/85719043
comment on: http://stackoverflow.com/q/49359470
type: Comment
type: QuestionComment
has text: It would help if you could explicitly state what you want to do: "I want to add spaces around the `=`-sign in `total = XXX`". Makes your question easier to understand with a fraction of the text.
score: 1

http://stackoverflow.com/q/49281663
has body: I have a dataframe and I am looking to calculate the mean based on store and all stores. I created code to calculate the mean but I am looking for a way that is more efficient. DF Cashier# Store# Sales Refunds 001 001 100 1 002 001 150 2 003 001 200 2 004 002 400 1 005 002 600 4 DF-Desired Cashier# Store# Sales Refunds Sales_StoreAvg Sales_All_Stores_Avg 001 001 100 1 150 290 002 001 150 2 150 290 003 001 200 2 150 290 004 002 400 1 500 290 005 002 600 4 500 290 My Attempt I created two additional dataframes then did a left join df.groupby(['Store#']).sum().reset_index().groupby('Sales').mean()
has title: Assign group averages to each row in python/pandas
has answer: http://stackoverflow.com/a/49281819
possible better answer: http://stackoverflow.com/a/49281787
score: 10
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
tagged with: mean
type: AnsweredQuestion
downvote count: 0
upvote count: 10
favorite count: 0
has answer: http://stackoverflow.com/a/49281787
type: Question
tagged with: group-by
accepted answer: http://stackoverflow.com/a/49281819
tagged with: python

http://stackoverflow.com/q/49358640
has title: Is it possible to find out from which module a class instance come from?
has body: I would like to know if it is possible to obtain the module name and directory path from a class instance of that module. I need that because I save a class instance with pickle and I need to know from where this class come from when I load it from another software (on the same computer). update So I tried the aswer of @albar &gt;&gt;&gt; from Models import Model_physio_moyen &gt;&gt;&gt; b = Model_physio_moyen.pop_Sigmoid_outside_noise &gt;&gt;&gt; module_name = sys.modules[b.__module__].__name__ &gt;&gt;&gt; module_name 'Models.Model_physio_moyen' So that working except if the class has been compiled with jitclassof numba: &gt;&gt;&gt; from Models.Pops_Stim import ATN &gt;&gt;&gt; a = ATN.pop_ATN() &gt;&gt;&gt; module_name = sys.modules[a.__module__].__name__ &gt;&gt;&gt; module_name 'numba.jitclass.boxing' In this condition, I wish I could find Models.Pops_Stim but I'm getting 'numba.jitclass.boxing'instead.
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: module
tagged with: class
has answer: http://stackoverflow.com/a/49360003
tagged with: instance
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/49347300
tagged with: window
answer count: 1
tagged with: frame
type: Question
has comment: http://stackoverflow.com/comment/85694781
has title: Create Frame from Tkinter Button
tagged with: python
has comment: http://stackoverflow.com/comment/85694687
has comment: http://stackoverflow.com/comment/85694766
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49347605
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85694723
has body: my program currently is used as a gym tracker and so has a frame which displays a users routine. However at the minute I have only got one routine and so to be able to create multiple routines I need a button which creates a frame for a new routine. To do this I have a button on the first frame which links to a command which should create the new frame, however it is returning an error. This is the code: def AddRoutine(self, window): self.window = window window.state("zoomed") self.window.title('Routine') window.update_idletasks() h = self.window.winfo_height() w = self.window.winfo_width() Center_h = h/2 Center_w = w/2 self.newFr = Frame(window, bg = "PaleTurquoise1") self.RFrame.append(self.newFr) self.newFr.place(x = Center_w , y = Center_h, anchor = "center", width = 1024, height = 800) I currently have a list RFrame which is added to every time a new frame is created, this is so the program knows how many frames their are. When I run the code the error is TypeError: AddRoutine() missing 1 required positional argument: 'window' however I do not know how this error is coming up.
has comment: http://stackoverflow.com/comment/85694653
has answer: http://stackoverflow.com/a/49347605
has comment: http://stackoverflow.com/comment/85694752

http://stackoverflow.com/comment/85672736
comment on: http://stackoverflow.com/q/49335427
type: Comment
has text: `print('"Hello [your_name]"')`
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85840039
type: AnswerComment
has text: Thank you very much! It solved my problem o(∩_∩)o~~
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49419235

http://stackoverflow.com/comment/85784289
comment on: http://stackoverflow.com/q/49391349
score: 0
type: Comment
type: QuestionComment
has text: Try `df.apply(func_replace, args=(1,), axis=1)`. If you just do `(1)` python doesn't treat it as a `tuple`, where as `(1, )` will be treated as a `tuple` with one element.

http://stackoverflow.com/q/49437807
has answer: http://stackoverflow.com/a/49437904
has comment: http://stackoverflow.com/comment/85877812
tagged with: arrays
has answer: http://stackoverflow.com/a/49437954
has comment: http://stackoverflow.com/comment/85877872
has title: How to print a numpy.array in one line?
has comment: http://stackoverflow.com/comment/85877747
tagged with: python
score: 22
tagged with: line
has body: I tested PyCharm and IDLE, both of them print the 7th number to a second line. Input: import numpy as np a=np.array([ 1.02090721, 1.02763091, 1.03899317, 1.00630297, 1.00127454, 0.89916715, 1.04486896]) print(a) Output: [ 1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896] How can I print them in one line?
answer count: 4
has answer: http://stackoverflow.com/a/78602312
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49437904
upvote count: 22
accepted answer: http://stackoverflow.com/a/49437893
has comment: http://stackoverflow.com/comment/85877643
downvote count: 0
has answer: http://stackoverflow.com/a/49437893
has comment: http://stackoverflow.com/comment/85877657
linked to: http://stackoverflow.com/q/1987694
has comment: http://stackoverflow.com/comment/85877707
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44139508

http://stackoverflow.com/comment/85695831
comment on: http://stackoverflow.com/q/49348091
type: QuestionComment
has text: Questions seeking help debugging should include a [mcve]
score: 0
type: Comment

http://stackoverflow.com/comment/85752604
comment on: http://stackoverflow.com/a/49375636
type: Comment
score: 0
type: AnswerComment
has text: i have a feeling that the command may be run in the shell instead of an python interpreter

http://stackoverflow.com/a/49338228
type: Answer
has body: The problem turned out to be that a single row at the end of my X array was not the same size as the other rows, and this broke sklearn's/Numpy's ability to convert that to a 2D Numpy array. That caused it to instead, convert it to a 1D Numpy array of lists, resulting in the error. I stripped out the bad row, and that caused my X array to be converted to a proper 2D Numpy array.
answers question: http://stackoverflow.com/q/49332590
score: 0

http://stackoverflow.com/a/49282684
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/49282238
has body: I believe that scipy.stats.binom can take advantage of broadcasting in the way that you're looking for. # Binomial PMF: Pr(X=k) = choose(n, k) * p**k * (1-p)**(n-k) # Probability of getting exactly k successes in n trials &gt;&gt;&gt; from scipy.stats import binom &gt;&gt;&gt; n = np.arange(1, N+1, dtype=np.int64) &gt;&gt;&gt; dist = binom(p=0.25, n=n) &gt;&gt;&gt; M = dist.pmf(k=np.arange(N+1, dtype=np.int64)[:, None]) &gt;&gt;&gt; M.round(2) array([[0.75, 0.56, 0.42, 0.32, 0.24, 0.18, 0.13, 0.1 , 0.08, 0.06], [0.25, 0.38, 0.42, 0.42, 0.4 , 0.36, 0.31, 0.27, 0.23, 0.19], [0. , 0.06, 0.14, 0.21, 0.26, 0.3 , 0.31, 0.31, 0.3 , 0.28], [0. , 0. , 0.02, 0.05, 0.09, 0.13, 0.17, 0.21, 0.23, 0.25], [0. , 0. , 0. , 0. , 0.01, 0.03, 0.06, 0.09, 0.12, 0.15], [0. , 0. , 0. , 0. , 0. , 0. , 0.01, 0.02, 0.04, 0.06], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.01, 0.02], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]]) Here, the rows are k (0-indexed) and the columns are n (1-indexed): &gt;&gt;&gt; from math import factorial as fac &gt;&gt;&gt; def manual_pmf(p, n, k): ... return fac(n) / (fac(k) * fac(n - k)) * p**k * (1-p)**(n-k) &gt;&gt;&gt; manual_pmf(p=0.25, n=3, k=2) 0.140625 # (2, 2) in M because M's columns are effectively 1-indexed You could also start n at zero to get an array that is 0-indexed on both rows and columns: &gt;&gt;&gt; n = np.arange(N+1, dtype=np.int64) # M.shape is (11, 11)
type: Answer
answers question: http://stackoverflow.com/q/49282238
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/49311901
accepted answer of: http://stackoverflow.com/q/49311848
has body: The flow: for i in range(100): continue if i % 2 == 0 Would be equivalent to: for i in range(1, 100, 2): ... Or, more generically, to: for i in range(100): if i % 2 == 0: continue Python language designers have a history of voting against changes to the grammar which are only offering slightly different ways of doing the same thing ("There should be one obvious way to do it"). The type of one-liner construct which you've mentioned x if cond else y was an exception made, here. It was added to the language to offer a less error-prone way of achieving what many users were already attempting to achieve with and and or short-circuiting hacks (source: Guido). Code in the wild was using: cond and x or y Which is not logically equivalent, yet it's an easy mistake to make for users who were already familiar with the ternary cond ? : x : y syntax from C. A correct equivalent is: (cond and [x] or [y])[0] But, that's ugly. So, the rationale for the addition of an expression x if cond else y was stronger than a mere convenience.
upvote count: 13
score: 12
answers question: http://stackoverflow.com/q/49311848
has comment: http://stackoverflow.com/comment/85627913
downvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85594293
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49280863
type: Comment
has text: Dont you need text only? Just do //text() in your xpath

http://stackoverflow.com/comment/85855569
has text: @the.salman.a I've tagged macos
comment on: http://stackoverflow.com/q/49427239
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49434811
score: 1
has comment: http://stackoverflow.com/comment/86178136
answers question: http://stackoverflow.com/q/49434810
type: Answer
has comment: http://stackoverflow.com/comment/110667700
downvote count: 0
upvote count: 1
has body: The solution involves modifying the Makefile generated by sphinx-quickstart as well as writing a little wrapper script around sphinx.cmd.build: Replace the SPHINXBUILD variable in the Makefile: SPHINXBUILD = blender --background --python blender_sphinx.py -- and make sure that the actual recipe line at the end of the file contains the -M flag. Then create a file blender_sphinx.py in the same directory as the Makefile with the following contents: import sys from sphinx.cmd import build first_sphinx_arg = sys.argv.index('-M') build.make_main(sys.argv[first_sphinx_arg:]) Now if you run $ make html from the doc/ directory it will allow autodoc to find bpy and import all the modules.

http://stackoverflow.com/comment/90421694
type: QuestionComment
comment on: http://stackoverflow.com/q/49286313
has text: Possible duplicate of [Color matplotlib plot\_surface command with surface gradient](https://stackoverflow.com/questions/6539944/color-matplotlib-plot-surface-command-with-surface-gradient)
score: 0
type: Comment

http://stackoverflow.com/comment/85855511
has text: afaik pip comes with python, so you already have it
comment on: http://stackoverflow.com/q/49427239
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49436063
downvote count: 2
has comment: http://stackoverflow.com/comment/85875122
answer count: 1
tagged with: mapreduce
favorite count: 0
type: Question
tagged with: hadoop
has comment: http://stackoverflow.com/comment/85874921
has comment: http://stackoverflow.com/comment/85875008
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/85874654
has comment: http://stackoverflow.com/comment/85881086
has answer: http://stackoverflow.com/a/49437412
has body: I am New to MapReduce and I am working on a project to increase my knowledge. Now I have to write a MapReduce Program in Hadoop for mutual friend finding from a chunk of data. Input file is in the format &lt;User&gt;&lt;TAB&gt;&lt;Friends&gt; It is a text file with data like 0 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94 1 0,5,20,135,2409,8715,8932,10623,12347,12846,13840,13845,14005,20075,21556,22939,23520,28193,29724,29791,29826,30691,31232,31435,32317,32489,34394,35589,35605,35606,35613,35633,35648,35678,38737,43447,44846,44887,49226,49985,623,629,4999,6156,13912,14248,15190,17636,19217,20074,27536,29481,29726,29767,30257,33060,34250,34280,34392,34406,34418,34420,34439,34450,34651,45054,49592 2 0,117,135,1220,2755,12453,24539,24714,41456,45046,49927,6893,13795,16659,32828,41878 3 0,12,41,55,1532,12636,13185,27552,38737 4 0,8,14,15,18,27,72,80,15326,19068,19079,24596,42697,46126,74,77,33269,38792,38822 5 0,1,20,2022,22939,23527,30257,32503,35633,41457,43262,44846,49574,31140,32828 So, 1,2,3,4,5, and so on means the tag while the numbers that are written in front of them are their friends. What I have to do is: provide mutual friends recommendations from this chunk of data Only one MapReduce job can solve this problem. Output should be the format &lt;User&gt;&lt;TAB&gt;&lt;Recommendations&gt; I do not know where to start.
has title: How to find mutual number from the text file using MapReduce?
has comment: http://stackoverflow.com/comment/85874929
upvote count: 0

http://stackoverflow.com/a/49398924
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49398393
has body: You can build a column with the last char of the cells col and then groupby Site and the last char column. Finally fill na accordingly. df_new = ( df1.assign(cells_last=df1.cells.str.slice(-1)) .groupby(['Site','cells_last']) .apply(lambda x: x.bfill().ffill()) .fillna('no-cosector') .reindex(columns=df1.columns) ) df_new Out[104]: Site cells national_plan_value 0 T13630 G13630B 225 1 T13631 G13631A 57 2 T13631 U13631A 57 3 T13672 G13672A 310 4 T13802 G13802A 150 5 T13802 G13802B 151 6 T13802 U13802A 150 7 T13880 G13880A 274 8 T13880 U13880B no-cosector 9 T33281 U33281A no-cosector
score: 2
upvote count: 2

http://stackoverflow.com/a/49404621
has body: In the code below, I created a function to check NaN separately, as I think in real data you will have np.NaN and not 'NaN' (strings). You can modify the string accordingly def isNaN(num): return num == 'NaN' def getval(x): if not isNaN(x['a FINSEC_SA']) : return 'a FINSEC_SA' if not isNaN(x['b FINSEC_A']) : return 'b FINSEC_A' if not isNaN(x['c FINSEC_NO']) : return 'c FINSEC_NO' if not isNaN(x['d FINSEC_D']) : return 'd FINSEC_D' if not isNaN(x['e FINSEC_SD']) : return 'e FINSEC_SD' old.apply(getval, axis=1) This is readable but not efficient answer. Melt functionality can be used to get the same answer in much more efficient manner - old['id'] = old.index new = pd.melt(old, id_vars= 'id', var_name = 'Financial') new = new[new['value'] != 'NaN'].drop('value', axis=1).sort_index(axis=0)
upvote count: 1
answers question: http://stackoverflow.com/q/49404068
type: Answer
has comment: http://stackoverflow.com/comment/85810357
score: 1
downvote count: 0

http://stackoverflow.com/comment/85813825
has text: Newly created ticket in PyCharm bug tracker: https://youtrack.jetbrains.com/issue/PY-29043
score: 0
comment on: http://stackoverflow.com/q/49360709
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49409691
tagged with: python
has comment: http://stackoverflow.com/comment/85833845
has title: Flask-Sqlalchemy Acess different schema?
tagged with: flask
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49414820
downvote count: 0
upvote count: 1
has body: Say I have a Postgres database with two different schema's, one called public and one called development. I know at the class level I can set __table_args__ = {"schema":"schema_name"} for each model, but if I wanted to switch from development to prod. wouldn't I haven't to update all my models? Is there a way to set the schema for the dev and prod schemas in flask? Or should I just create another database as a dev database and just backup the prod database to the development database?
score: 1
answer count: 1
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49414820
linked to: http://stackoverflow.com/q/9298296

http://stackoverflow.com/a/49806006
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49283143
type: Answer
accepted answer of: http://stackoverflow.com/q/49283143
has body: I was able to resolve this issue by installing an archived version of Anaconda rather than the latest one available. Still not sure why the latest version won't install successfully.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49296572
duplicate of: http://stackoverflow.com/q/11858472
has title: Creating new column in pandas from two column data
downvote count: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
favorite count: 0
type: Question
tagged with: pandas
has body: Here's the head from the pandas file In [19]: train.head() Out[19]: Unnamed: 0 id \ 0 1 0a58358a2afd3e4e 1 2 6b2bb500b6a38aa0 2 3 b399f09dee9c3c67 3 4 19ace29d77a5be66 4 5 2c9c54b62f0a6a37 url landmark_id exists \ 0 http://lh6.ggpht.com/-igpT6wu0mIA/ROV8HnUuABI/... 6651 True 1 http://lh6.ggpht.com/-vKr5G5MEusk/SR6r6SJi6mI/... 11284 True 2 https://lh3.googleusercontent.com/-LOW2cjAqubA... 8429 True 3 https://lh5.googleusercontent.com/-tnmSXwQcWL8... 6231 True 4 https://lh5.googleusercontent.com/-mEaSECO7D-4... 10400 True filename 0 training_images/0a58358a2afd3e4e.jpg 1 training_images/6b2bb500b6a38aa0.jpg 2 training_images/b399f09dee9c3c67.jpg 3 training_images/19ace29d77a5be66.jpg 4 training_images/2c9c54b62f0a6a37.jpg what I want to create is a new filename row that has the landmark_id so I can use it to move the files In [23]: train['new_filename'] = 'training_images/' + train['landmark_id'] + '/' + train['id'] + '.jpg' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-23-94fcfab9d25c&gt; in &lt;module&gt;() ----&gt; 1 train['new_filename'] = 'training_images/' + train['landmark_id'] + '/' + train['id'] + '.jpg' /home/muiruri_samuel/.local/lib/python2.7/site-packages/pandas/core/ops.pyc in wrapper(left, right, name, na_op) 737 lvalues = lvalues.values 738 --&gt; 739 result = wrap_results(safe_na_op(lvalues, rvalues)) 740 return construct_result( 741 left, /home/muiruri_samuel/.local/lib/python2.7/site-packages/pandas/core/ops.pyc in safe_na_op(lvalues, rvalues) 698 try: 699 with np.errstate(all='ignore'): --&gt; 700 return na_op(lvalues, rvalues) 701 except Exception: 702 if isinstance(rvalues, ABCSeries): /home/muiruri_samuel/.local/lib/python2.7/site-packages/pandas/core/ops.pyc in na_op(x, y) 684 result = np.empty(len(x), dtype=x.dtype) 685 mask = notna(x) --&gt; 686 result[mask] = op(x[mask], y) 687 else: 688 raise TypeError("{typ} cannot perform the operation " /home/muir…
linked to: http://stackoverflow.com/q/11858472
score: 1
tagged with: python

http://stackoverflow.com/comment/85583643
comment on: http://stackoverflow.com/a/49290255
type: AnswerComment
score: 0
type: Comment
has text: Oh.. I asked the question wrong.. I meant frequency with at least 30. As, always, thanks! :)

http://stackoverflow.com/comment/85787318
score: 2
has text: https://www.python.org/dev/peps/pep-0484/#forward-references
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49392845

http://stackoverflow.com/a/49379157
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49379073
downvote count: 0
type: AcceptedAnswer
score: 4
has body: Google's geocode api supports Hindi, so you don't necessarily have to translate it to English. Here's an example using my googleway package (in R) specifying the language = "hi" argument. You'll need an API key to use the Google API through googleway library(googleway) set_key("your_api_key") res &lt;- google_geocode(address = "village gorthaniya, UP, INDIA", language = "hi") geocode_address(res) # [1] "गोर्थानिया, उत्तर प्रदेश 272181, भारत" geocode_coordinates(res) # lat lng # 1 26.85848 82.50099 geocode_address_components(res) # long_name short_name types # 1 गोर्थानिया गोर्थानिया locality, political # 2 बस्ती बस्ती administrative_area_level_2, political # 3 उत्तर प्रदेश उ॰ प्र॰ administrative_area_level_1, political # 4 भारत IN country, political # 5 272181 272181 postal_code
accepted answer of: http://stackoverflow.com/q/49379073

http://stackoverflow.com/q/49397710
tagged with: python
tagged with: psycopg2
has body: I encountered a problem as title depicted: InternalError: current transaction is aborted, commands ignored until end of transaction block I found 3 solutions: with statement; rollback(); autocommit attribute; (seems too global) I have tried with statement, but not work with my situation. Here, I need cursor for later use, I builded a get() method like Django, so it can't be closed. Well, I think i can catch the certain error to perform rollback(), then to execute(). Due to InternalError is a mixed exceptions, I catch the error based on pgerror attribute. class PostgresqlConnector(object): def __init__(self, config): self.conn = psycopg2.connect(**config) self.cursor = self.conn.cursor() # Add exceptions self.DoesNotExist = DoesNotExist self.MultipleObjectsReturned = MultipleObjectsReturned def __commit__(self): self.conn.commit() def __rollback__(self): self.conn.rollback() def __execute__(self, sql, vals): try: self.cursor.execute(sql, vals) except psycopg2.InternalError as e: if e.pgerror == 'ERROR: current transaction is aborted, commands ignored until end of transaction block\n': self.__rollback__() return self.__execute__(sql, vals) raise e else: self.__commit__() return self.cursor def select(self, tab, query_dict, cols_selected='*', filter_='='): cols, vals = zip(*query_dict.items()) cols_selected = ', '.join(cols_selected) expr_where = ' AND '.join(["{} {} %s".format(x, filter_) for x in cols]) sql = "SELECT {} FROM \"{}\" WHERE {}".format(cols_selected, tab, expr_where) return self.__execute__(sql, vals) # --- omit --- def get(self, tab, query_dict, cols_selected='*', filter_='='): # here i need cursor self.cursor = self.select(tab, query_dict, cols_selected, filter_) if self.cursor.rowcount == 1: return self.cursor.fetchone() elif self.cursor.rowcount == 0: raise self.DoesNotExist("No record found!") else: raise self.MultipleObjectsReturned("Get {} records! only one excepted.".format(self.cursor.rowcount)) def close(self): self.cursor.close() self.conn.clo…
tagged with: postgresql
score: 3
answer count: 0
has comment: http://stackoverflow.com/comment/85797235
downvote count: 1
favorite count: 0
type: Question
upvote count: 4
has title: Handle psycopg2.InternalError 'ERROR: current transaction is aborted, commands ignored until end of transaction block'
type: UnansweredQuestion

http://stackoverflow.com/a/49390967
answers question: http://stackoverflow.com/q/49390746
has body: I build a batch opener for my powershell script. Once open in elevated privileges any other script called is also elevated. I do a similar thing with .vbs to open batch in admin. @ECHO off ECHO Please Wait. powershell.exe -ExecutionPolicy ByPass -file "File.ps1" ECHO. ECHO PRESS ANY KEY ONCE DEBUGGED Pause &gt;nul exit
type: Answer
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/85783860
has comment: http://stackoverflow.com/comment/85783779
downvote count: 1
has comment: http://stackoverflow.com/comment/85783738
has comment: http://stackoverflow.com/comment/85785062

http://stackoverflow.com/a/49433178
has comment: http://stackoverflow.com/comment/85869645
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85869788
downvote count: 0
has comment: http://stackoverflow.com/comment/85869460
has body: Are you using docker to run your rabbitmq? If yes, I suggest you to double check ports binding. For example: -p 5672:5672
answers question: http://stackoverflow.com/q/49394155
type: Answer

http://stackoverflow.com/comment/85565116
comment on: http://stackoverflow.com/q/49281265
score: 1
type: Comment
type: QuestionComment
has text: `break` is useful to exit loops.

http://stackoverflow.com/a/49354523
score: 3
has body: I like @jpp's answer but if you don't want to use a generator this is how I would do it: FileList = glob.glob('*.xlsx') filenames = [] sheets = [] for filename in FileList: for sheet in pd.ExcelFile(filename).sheet_names: filenames.append(filename) sheets.append(sheet) df = pd.DataFrame( {'Filename': filenames, 'Tab': sheets} )
type: Answer
answers question: http://stackoverflow.com/q/49354390
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/85802667
type: QuestionComment
type: Comment
has text: I'm just going to up vote your post 'cause I think it's cute that *'23 sheets with 1000 lines on each sheet'* is *'very big'*.
comment on: http://stackoverflow.com/q/49400498
score: 0

http://stackoverflow.com/a/49373441
upvote count: 1
answers question: http://stackoverflow.com/q/49334697
score: 1
accepted answer of: http://stackoverflow.com/q/49334697
has body: 1. The Right Way You can process the keycodes in the _on_keyboard_down method. class PongGame(Widget): ball = ObjectProperty(None) player1 = ObjectProperty(None) player2 = ObjectProperty(None) PLAYER1_UP = 'w' PLAYER1_DOWN = 's' PLAYER2_UP = 'up' PLAYER2_DOWN = 'down' SENSITIVITY = 10 def __init__(self, **kwargs): super(PongGame, self).__init__(**kwargs) self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_keyboard_down) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == self.PLAYER1_UP: self.move_player(self.player1, self.SENSITIVITY) elif keycode[1] == self.PLAYER1_DOWN: self.move_player(self.player1, -self.SENSITIVITY) if keycode[1] == self.PLAYER2_UP: self.move_player(self.player2, self.SENSITIVITY) elif keycode[1] == self.PLAYER2_DOWN: self.move_player(self.player2, -self.SENSITIVITY) return True def move_player(self, player, displacement): player.center_y += displacement # serve_ball and update methods, ref tutorial # ... Notes To be able to play both sides with just one set of keys, we broke up the if-elif chain. Use _keyboard_closed to unbind the handler, ref the example from the docs. 2. Handler Handling You're right about that cart, you had it backwards. From the Event Dispatcher: If a callback has already been bound to a given event or property, it won’t be added again. Saying that the same handler can't be added to the same event multiple times, with regular bind. What you really want is different methods to be called for the same event. As luck would have it, that's easy... def __init__(self, **kwargs): super(PongGame, self).__init__(**kwargs) self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_keyboard_down1) self._keyboard.bind(on_key_down=self._on_keyboard_down2) def _keyboard_clos…
type: Answer
has comment: http://stackoverflow.com/comment/85772842
has comment: http://stackoverflow.com/comment/85769547
has comment: http://stackoverflow.com/comment/85758940
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85713838
type: Comment
type: QuestionComment
has text: This problem is a _multiclass_ problem, not a _multilabel_ problem. Multilabel is the case which each example might have more than one class related to it.
comment on: http://stackoverflow.com/q/49352416
score: 1

http://stackoverflow.com/q/49389193
answer count: 1
has body: I need to write a program that asks the user for a nucleotide sequence and translates it into amino acids and use a specific genetic table. This is the code I came up with but it is not working. def sequence(code): gencode = { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'} seq = (seq for seq in code.split()) result = [] for x in seq: result.append("".join(seq[char] if x in gencode.keys() else char for char in x)) return "".join(result)`enter code here` if __name__ == "__main__": code = input("Your sequence: ") print (sequence(code))
has title: Translation of genetic code to protein amino acids using python
favorite count: 0
type: Question
tagged with: bioinformatics
type: UnansweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85780074
downvote count: 0
has answer: http://stackoverflow.com/a/49389312
upvote count: 1

http://stackoverflow.com/q/49348396
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85696587
accepted answer: http://stackoverflow.com/a/49348447
tagged with: pandas
score: 2
has answer: http://stackoverflow.com/a/49348447
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85696478
favorite count: 0
type: Question
has title: How to sort tuples in a column of a dataframe
upvote count: 2
has body: I have a dataframe that consists of a column of tuples as shown: pid aid 0000000F (0BDEAC61, 288E046F) 00000017 (7795AF0D, 4A259AFA, 7DA84B6E) 00000019 (8123B8CF, 3A25A1FE) 00000025 (28045D98, 8043B6E5, 81195E5D) 0000003A (7D566708, 7F5583AE) I want to sort the values in each of the tuples so the result would be as follows: pid aid 0000000F (0BDEAC61, 288E046F) 00000017 (4A259AFA, 7795AF0D, 7DA84B6E) 00000019 (3A25A1FE, 8123B8CF) 00000025 (28045D98, 8043B6E5, 81195E5D) 0000003A (7D566708, 7F5583AE) I know that I can loop through them one at a time and sort as follows: z = list(eval(df.aid.iloc[0])) z.sort() But that would take a long time as it's a huge dataframe (over 4 million). Is there a faster method. I also tried: df.aid = df.aid.apply(lambda x: list(eval(x)).sort()) but I got "None" Any help would be appreciated.
downvote count: 0
answer count: 1
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/85696535

http://stackoverflow.com/comment/85631352
type: Comment
score: 0
has text: What is size of DataFrame?
type: QuestionComment
comment on: http://stackoverflow.com/q/49314955

http://stackoverflow.com/q/49364721
type: Question
tagged with: numpy
score: -2
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/49364934
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85730111
has comment: http://stackoverflow.com/comment/85730426
downvote count: 3
upvote count: 1
answer count: 1
has title: manipulate arrays inside numpy ndarrays
has comment: http://stackoverflow.com/comment/85730332
has body: How do i manipulate arrays inside a numpy ndarray in python? For example if i got an array like this a1 = np.array([1,1,1,1],[2,2,2,2],[3,3,3,3]) &gt;&gt; [[1 1 1 1] [2 2 2 2] [3 3 3 3]] and i want to exchange one or multiple rows inside the array. For example i want to insert the array [0,0,0,0] at the first index, so it looks like this: [[0 0 0 0] [2 2 2 2] [3 3 3 3]] or if i got a second array like this a2 = np.array([1,2,3,4],[5,6,7,8]) &gt;&gt; [[1 2 3 4] [5 6 7 8]] and i want it to replace the first two rows of my first array like this: [[1 2 3 4] [5 6 7 8] [3 3 3 3]] How do i do these operations if speed is a big factor?
accepted answer: http://stackoverflow.com/a/49364934
favorite count: 0

http://stackoverflow.com/comment/85577761
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49286854
has text: @ColinRicardo because you iterate over each element once, to re-assign it.

http://stackoverflow.com/a/49393202
has comment: http://stackoverflow.com/comment/86054355
answers question: http://stackoverflow.com/q/49391557
has comment: http://stackoverflow.com/comment/137438158
type: Answer
accepted answer of: http://stackoverflow.com/q/49391557
upvote count: 4
has body: You need an alternate join condition and custom foreign conditions, because there's no actual foreign key relationship to join on: class Event(Base): __tablename__ = 'event' # Attributes eventID = Column(String(length=256), primary_key=True) eventDate = Column(DateTime) userID = Column(String(length=256), ForeignKey('users.userID')) previousEvents = relationship( "Event", primaryjoin=and_(userID == foreign(userID), eventDate &gt; foreign(eventDate)), viewonly=True) Use the foreign() annotation to create a join condition without actual foreign keys. The foreign_keys argument of relationship() could also be used, but you would have to be very careful in how you arrange the comparisons in order to get the columns in the correct order, since the same columns are used on both sides of the join. When you wish to create a query that joins the previous events you need an alias: In [13]: prev_event = aliased(Event) In [14]: print(session.query(Event).join(prev_event, Event.previousEvents)) SELECT event."eventID" AS "event_eventID", event."eventDate" AS "event_eventDate", event."userID" AS "event_userID" FROM event JOIN event AS event_1 ON event_1."userID" = event."userID" AND event_1."eventDate" &lt; event."eventDate" Or if you wish to eager load using a join: In [17]: print(session.query(Event).options(joinedload(Event.previousEvents))) SELECT event."eventID" AS "event_eventID", event."eventDate" AS "event_eventDate", event."userID" AS "event_userID", event_1."eventID" AS "event_1_eventID", event_1."eventDate" AS "event_1_eventDate", event_1."userID" AS "event_1_userID" FROM event LEFT OUTER JOIN event AS event_1 ON event_1."userID" = event."userID" AND event_1."eventDate" &lt; event."eventDate"
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/85664502
score: 0
comment on: http://stackoverflow.com/q/49331185
has text: `for word in trans.split(): first_char_of_word = word[0]`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49331171
favorite count: 0
type: Question
tagged with: character
has comment: http://stackoverflow.com/comment/85664797
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85664345
score: 0
has comment: http://stackoverflow.com/comment/85664400
has comment: http://stackoverflow.com/comment/85664436
upvote count: 3
downvote count: 3
tagged with: python
has title: Python : Remove everything after a specific character (,)
has body: I have millions of lines inside a file (9GB)(can't opened by Notepad++) and i want to remove all the words after a specific characters. (,) Example of line : data1,data2,data3,data4 I want to keep the (data1) and delete everything else. Thanks in advance.
has comment: http://stackoverflow.com/comment/85664439
has comment: http://stackoverflow.com/comment/85664380
has answer: http://stackoverflow.com/a/49331521
has comment: http://stackoverflow.com/comment/85664375

http://stackoverflow.com/q/49428298
has comment: http://stackoverflow.com/comment/85857712
possible better answer: http://stackoverflow.com/a/49432663
tagged with: c++
type: AnsweredQuestion
has body: I am trying to time the houghcircle in python and c++ to see if c++ gives edge over processing time (intuitively it should!) Versions python: 3.6.4 gcc compiler: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609 cmake : 3.5.1 opencv : 3.4.1 I actually installed opencv using anaconda. Surprisingly c++ version also worked The image I am using is given here: Python code import cv2 import time import sys def hough_transform(src,dp,minDist,param1=100,param2=100,minRadius=0,maxRadius=0): gray = cv2.cvtColor(src,cv2.COLOR_RGB2GRAY) start_time = time.time() circles=cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp = dp, minDist = minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius) end_time = time.time() print("Time taken for hough circle transform is : {}".format(end_time-start_time)) # if circles is not None: # circles = circles.reshape(circles.shape[1],circles.shape[2]) # else: # raise ValueError("ERROR!!!!!! circle not detected try tweaking the parameters or the min and max radius") # # a = input("enter 1 to visualize") # if int(a) == 1 : # for circle in circles: # center = (circle[0],circle[1]) # radius = circle[2] # cv2.circle(src, center, radius, (255,0,0), 5) # # cv2.namedWindow("Hough circle",cv2.WINDOW_NORMAL) # cv2.imshow("Hough circle",src) # cv2.waitKey(0) # cv2.destroyAllWindows() # # return if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError("usage: python hough_circle.py &lt;path to image&gt;") image = cv2.imread(sys.argv[1]) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) hough_transform(image,1.7,100,50,30,690,700) C++ code #include &lt;iostream&gt; #include &lt;opencv2/opencv.hpp&gt; #include &lt;ctime&gt; using namespace std; using namespace cv; void hough_transform(Mat src, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0 ) { Mat gray; cvtColor( src, gray, COLOR_RGB2GRAY); vector&lt;Vec3f&gt; circles; int start_time = clock(); HoughCircles( gray, circles, HOUGH_GRADIE…
score: 0
answer count: 2
has title: opencv python is faster than c++?
accepted answer: http://stackoverflow.com/a/49430367
has comment: http://stackoverflow.com/comment/85857741
has answer: http://stackoverflow.com/a/49430367
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85863696
tagged with: opencv
has answer: http://stackoverflow.com/a/49432663
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/85857877

http://stackoverflow.com/a/49363324
accepted answer of: http://stackoverflow.com/q/49363247
score: 2
answers question: http://stackoverflow.com/q/49363247
type: AcceptedAnswer
has body: One solution is to use collections.defaultdict to iterate a list of lists. Then use a list comprehension to transform your dictionary. from collections import defaultdict lst = [[1, 100], [1, 250], [2, 340], [2, 5200]] d = defaultdict(list) for i, j in lst: d[i].append(j) res = [[k]+v for k, v in d.items()] Result: [[1, 100, 250], [2, 340, 5200]]
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/49404438
has comment: http://stackoverflow.com/comment/85810421
type: Answer
has body: You can directly use idxmax followed by reset_index to achieve this. df = old.idxmax(axis=1).reset_index().drop('index', axis=1).rename(columns={0:'Financial'}) print(df) Financial 0 a FINSEC_SA 1 b FINSEC_A 2 c FINSEC_NO 3 d FINSEC_D 4 e FINSEC_SD 5 a FINSEC_SA 6 d FINSEC_D Explanation: 1. idxmax select max. value row wise across columns. 2. drop drops the unwanted column followed by removing duplicate values. 3. Finally, we rename the column as required.
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85813944
answers question: http://stackoverflow.com/q/49404068

http://stackoverflow.com/a/49416294
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49416170
downvote count: 0
has comment: http://stackoverflow.com/comment/85834620
upvote count: 1
type: AcceptedAnswer
has body: Something like this would do what you want: X = ['M', 'W', 'W', 'M', 'M', 'W'] NUM = [1, 2, 3, 4, 5, 6] X_VAL = {'M': 5, 'W': 10 } result = [] for index, val in enumerate(NUM): result.append(val * X_VAL[X[index]]) print(result) Let me know if you need any help understanding the code. EDIT: Like @user2357112 said you can zip both lists like this: X = ['M', 'W', 'W', 'M', 'M', 'W'] NUM = [1, 2, 3, 4, 5, 6] X_VAL = {'M': 5, 'W': 10 } result = [] for val, x in zip(NUM, X): result.append(val * X_VAL[x]) print(result)
has comment: http://stackoverflow.com/comment/85835428
answers question: http://stackoverflow.com/q/49416170
has comment: http://stackoverflow.com/comment/85835380
has comment: http://stackoverflow.com/comment/85835557

http://stackoverflow.com/q/49424086
type: Question
has comment: http://stackoverflow.com/comment/85855212
has body: I'm attempting to process a dataframe one row at a time using iloc. I have a sorted frame read in from a Database: branch animal owner 00177 cat Dave 00177 lion Peter 00177 dog Dave 00200 dog Mary 00200 dog Fred 00300 horse Doug 00400 cat Dave I want to process each group of branch, so I thought if I compared each grpnum with the next one. like this: for R in 0 to 7 while [df.iloc[[R],[0]] == df.iloc[[R+1],[0]] do something R = R + 1 Except I got this error: ValueError: Can only compare identically-labeled DataFrame objects Can I not process a DataFrame this way? How would one process a DataFrame row by row? I'm not tied to using a dataframe object, it was just convenient. This example shows Branch with 4 distinct values. There are actually over a thousand different values, and the same branch can contain up to thirty records and as few as one.
has comment: http://stackoverflow.com/comment/85849417
tagged with: python
has answer: http://stackoverflow.com/a/49425855
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: issues with processing a Pandas Dataframe one row at a time
linked to: http://stackoverflow.com/q/18548370
accepted answer: http://stackoverflow.com/a/49425855

http://stackoverflow.com/a/49375038
has comment: http://stackoverflow.com/comment/85779074
accepted answer of: http://stackoverflow.com/q/49371629
has comment: http://stackoverflow.com/comment/86575867
answers question: http://stackoverflow.com/q/49371629
has comment: http://stackoverflow.com/comment/86575804
has body: Performance It's worth looking at actual performance before beginning any investigation since, contrary to popular opinion, list(map(str, x)) appears to be slower than x.apply(str). import pandas as pd, numpy as np ### Versions: Pandas 0.20.3, Numpy 1.13.1, Python 3.6.2 ### x = pd.Series(np.random.randint(0, 100, 100000)) %timeit x.apply(str) # 42ms (1) %timeit x.map(str) # 42ms (2) %timeit x.astype(str) # 559ms (3) %timeit [str(i) for i in x] # 566ms (4) %timeit list(map(str, x)) # 536ms (5) %timeit x.values.astype(str) # 25ms (6) Points worth noting: (5) is marginally quicker than (3) / (4), which we expect as more work is moved into C [assuming no lambda function is used]. (6) is by far the fastest. (1) / (2) are similar. (3) / (4) are similar. Why is x.map / x.apply fast? This appears to be because it uses fast compiled Cython code: cpdef ndarray[object] astype_str(ndarray arr): cdef: Py_ssize_t i, n = arr.size ndarray[object] result = np.empty(n, dtype=object) for i in range(n): # we can use the unsafe version because we know `result` is mutable # since it was created from `np.empty` util.set_value_at_unsafe(result, i, str(arr[i])) return result Why is x.astype(str) slow? Pandas applies str to each item in the series, not using the above Cython. Hence performance is comparable to [str(i) for i in x] / list(map(str, x)). Why is x.values.astype(str) so fast? Numpy does not apply a function on each element of the array. One description of this I found: If you did s.values.astype(str) what you get back is an object holding int. This is numpy doing the conversion, whereas pandas iterates over each item and calls str(item) on it. So if you do s.astype(str) you have an object holding str. There is a technical reason why the numpy version hasn't been implemented in the case of no-nulls.
type: Answer
has comment: http://stackoverflow.com/comment/85778752
has comment: http://stackoverflow.com/comment/85790791
upvote count: 22
score: 20
has comment: http://stackoverflow.com/comment/85754698
downvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86615879
has comment: http://stackoverflow.com/comment/86596961

http://stackoverflow.com/q/49377576
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85755916
score: -2
has comment: http://stackoverflow.com/comment/85757298
has comment: http://stackoverflow.com/comment/85756977
has comment: http://stackoverflow.com/comment/85757528
answer count: 1
has body: The code I am using is: import numpy as np data=np.loadtxt('C:\\Users\\hp\\Desktop\\data.csv',delimiter=",") why is this not working I copied the data.csv file in the above specified location and it did not work. I copied the csv file in the jupyter folder, but it still did not work What is wrong? I'm using python 3. The error that I am getting is ValueError Traceback (most recent call last) <ipython-input-14-498d125dea5e> in <module>() 1 import numpy as np ----> 2 da=np.loadtxt('C:\\Users\\hp\\Desktop\\data.csv',delimiter=",") ~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin) 1022 1023 # Convert each value according to its column and store -> 1024 items = [conv(val) for (conv, val) in zip(converters, vals)] 1025 # Then pack it according to the dtype's nesting 1026 items = pack_items(items, packing)~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in <listcomp>(.0) 1022 1023 # Convert each value according to its column and store -> 1024 items = [conv(val) for (conv, val) in zip(converters, vals)] 1025 # Then pack it according to the dtype's nesting 1026 items = pack_items(items, packing)~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in floatconv(x) 723 if b'0x' in x: 724 return float.fromhex(asstr(x)) --> 725 return float(x) 726 727 typ = dtype.type ValueError: could not convert string to float: b'"32.502345269453"'
has answer: http://stackoverflow.com/a/49386620
tagged with: python
has comment: http://stackoverflow.com/comment/85756199
upvote count: 0
has comment: http://stackoverflow.com/comment/85755851
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85756056
favorite count: 0
type: Question
tagged with: numpy
has title: Numpy loadtxt function
tagged with: python-3.x
downvote count: 2

http://stackoverflow.com/comment/85865170
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o)
comment on: http://stackoverflow.com/q/49431659

http://stackoverflow.com/comment/85570506
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49283252
type: QuestionComment
has text: As a tip, when you read in the csv file, use the attribute parse_dates like df = pd.read_csv(filename, parse_dates=['start_park_time','end_park_time']) to turn these columns into datetime objects.

http://stackoverflow.com/comment/85849583
type: QuestionComment
has text: Try to change the codes in init function like self.__fltCash = fltCash, instead of self.fltCash, due to you may cause nested attributes error.
type: Comment
comment on: http://stackoverflow.com/q/49424252
score: 0

http://stackoverflow.com/q/49343860
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/49343949
downvote count: 0
accepted answer: http://stackoverflow.com/a/49343949
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has title: How to drop duplicate values based in specific columns using pandas?
has body: Currently, I imported the following data frame from Excel into pandas and I want to delete duplicate values based in the values of two columns. # Python 3.5.2 # Pandas library version 0.22 import pandas as pd # Save the Excel workbook in a variable current_workbook = pd.ExcelFile('C:\\Users\\userX\\Desktop\\cost_values.xlsx') # convert the workbook to a data frame current_worksheet = pd.read_excel(current_workbook, index_col = 'vend_num') # current output print(current_worksheet) | vend_number | vend_name | quantity | source | | ----------- |----------------------- | -------- | -------- | CHARLS Charlie &amp; Associates $5,700.00 Central CHARLS Charlie &amp; Associates $5,700.00 South CHARLS Charlie &amp; Associates $5,700.00 North CHARLS Charlie &amp; Associates $5,700.00 West HUGHES Hughinos $3,800.00 Central HUGHES Hughinos $3,800.00 South FERNAS Fernanda Industries $3,500.00 South FERNAS Fernanda Industries $3,500.00 North FERNAS Fernanda Industries $3,000.00 West .... What I want is to remove those duplicate values based in the columns quantity and source: Review the quantity and source column values: 1.1. If the quantity of a vendor is equal in another row from the same vendor and source is not equal to Central then drop the repeated rows from this vendor except the row Central. 1.2. Else if the quantity of a vendor is equal in another row from the same vendor and there is no source Central then drop the repeated rows. Desired result | vend_number | vend_name | quantity | source | | ----------- |----------------------- | -------- | -------- | CHARLS Charlie &amp; Associates $5,700.00 Central HUGHES Hughinos $3,800.00 Central FERNAS Fernanda Industries $3,500.00 South FERNAS Fernanda Industries $3,000.00 West .... So far, I have tried the following code but pandas is not even detecting any duplicate rows. print(current_worksheet.loc[current_worksheet.duplicated()]) print(current_worksheet.duplicated()) I have tried to figure out the solution but I am struggling…
has comment: http://stackoverflow.com/comment/85688078
has comment: http://stackoverflow.com/comment/85688067
tagged with: python
has answer: http://stackoverflow.com/a/49343892
possible better answer: http://stackoverflow.com/a/49343892

http://stackoverflow.com/comment/85812638
has text: Thanks for your answer but I think this is not the case. I redirect to `index_page` from `logout`, where I defined `session['logged_in']`. Also, if I print out `message` or `render_template('index.html',message=message)` in `index page`, I get expected outputs. Yet when I _return_ the same `render_template`, I get incorrect html rendered.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49405133

http://stackoverflow.com/q/49290456
has comment: http://stackoverflow.com/comment/85584650
has answer: http://stackoverflow.com/a/49294082
tagged with: python
tagged with: plot
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49290628
accepted answer: http://stackoverflow.com/a/49297173
has comment: http://stackoverflow.com/comment/85584785
score: 0
has comment: http://stackoverflow.com/comment/85584603
answer count: 3
possible better answer: http://stackoverflow.com/a/49294082
has answer: http://stackoverflow.com/a/49297173
has title: Pyplot how to reduce xticks *and* xticklabels density?
tagged with: matplotlib
has body: I have to plot several curves with very high xtick density, say 1000 date strings. To prevent these tick labels overlapping each other I manually set them to be 60 dates apart. Code below: import pandas as pd import numpy as np import matplotlib.pyplot as plt ts_index = pd.period_range(start="20060429", periods=1000).strftime("%Y%m%d") fig = plt.figure(1) ax = plt.subplot(1, 1, 1) tick_spacing = 60 for i in range(5): plt.plot(ts_index, 1 + i * 0.01 * np.arange(0, 1000), label="group %d"%i) plt.legend(loc='best') plt.title(r'net value curves') xticks = ax.get_xticks() xlabels = ax.get_xticklabels() ax.set_xticks(xticks[::tick_spacing]) ax.set_xticklabels(xlabels[::tick_spacing]) plt.xticks(rotation="vertical") plt.xlabel(r'date') plt.ylabel('net value') plt.grid(True) plt.show() fig.savefig(r".\net_value_curves.png", ) fig.clf() I'm running this piece of code in PyCharm Community Edition 2017.2.2 with a Python 3.6 kernel. Now comes the funny thing: whenever I ran the code in the normal "run" mode (i.e. just hit the execution button and let the code run "freely" till interruption or termination), then the figure I got would always miss xticklabels: However, if I ran the code in "debug" mode and ran it step by step then I would get an expected figure with complete xticklabels: This is really weird. Anyway, I just hope to find a way that can ensure me getting the desired output (the second figure) in the normal "run" mode. How can I modify my current code to achieve this? Thanks in advance!
type: Question

http://stackoverflow.com/comment/85735196
comment on: http://stackoverflow.com/q/49366491
type: Comment
type: QuestionComment
score: 0
has text: @liliscent, this is a great Meta question. The consensus usually is that it helps (a) catch common pitfalls, (b) suggest the level of explanation required in the answer. For example, if the user is adept at regex, a regex-based answer *may* be appropriate.

http://stackoverflow.com/a/49419451
has comment: http://stackoverflow.com/comment/85840500
upvote count: 1
has comment: http://stackoverflow.com/comment/85840575
has comment: http://stackoverflow.com/comment/85840558
score: 1
answers question: http://stackoverflow.com/q/49417041
type: Answer
accepted answer of: http://stackoverflow.com/q/49417041
has body: Since Python 3.5, interrupted system calls are automatically resumed after invoking the (Python) signal handler. If you don’t want that, raise an exception in your handler.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49346170
score: 2
upvote count: 2
answer count: 2
tagged with: pycharm
downvote count: 0
linked to: http://stackoverflow.com/q/11129731
has comment: http://stackoverflow.com/comment/85692302
tagged with: windows-10
has comment: http://stackoverflow.com/comment/85692330
has answer: http://stackoverflow.com/a/50751142
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85692374
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85692353
has answer: http://stackoverflow.com/a/54133544
has title: Display Images one after other in a loop using a user input prompt
has body: I am writing a code that would display images one by one after the user sends input signal like enter.Following is my code import numpy as np import matplotlib.pyplot as plt from logistic_regression_class.utils_naseer import getData import time X,Y=getData(balances=False) // after getting X data and Y labels # X and Y are retrieved using famous kaggle facial expression dataset label_map=['Anger','Disgust','Fear','Happy','Sad','Surprise','Neutral'] plt.ion() for i in range(len(Y)): x=X[i] plt.figure() plt.imshow(x.reshape(48,48),cmap='gray') plt.title(label_map[Y[i]]) plt.show() _ = input("Press [enter] to continue.") plt.close() Output: I am only getting blank images with no data and each time I presses enter I get a new blank image.But When I removed plt.close() then all the plots showed up in separate window but that will be too many windows popping up. I also used suggestion from stackoverflow this link. What is the correct way to show images in a loop one after another using a use command input? Screen Shots: a) With plt.close() b) Without plt.close()
has comment: http://stackoverflow.com/comment/85948435

http://stackoverflow.com/q/49435781
score: 1
has comment: http://stackoverflow.com/comment/85876538
answer count: 1
has comment: http://stackoverflow.com/comment/85876469
has title: Obfuscated Bytecode when uncompyling python pyc file
has comment: http://stackoverflow.com/comment/85876029
favorite count: 0
type: Question
tagged with: pyc
has comment: http://stackoverflow.com/comment/85873961
has comment: http://stackoverflow.com/comment/85873790
has comment: http://stackoverflow.com/comment/85876775
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/32562163
has body: I'm trying to decompile a pyc file with uncompyle6. The operation gives a Parse error at offset 966 as it says here. Parse error at or near `POP_TOP' instruction at offset 996 Uncompyle prints the result of its decompiling and from that I can see the parse error is thrown after decompiling the last line of my code, which was root.mainloop() since the source code was a tkinter gui. I'd appreciate it if someone could shed some light on how to fix bytecode to an absolute beginner and where I should begin. Since the error is thrown at the end of my code I feel like the error is rectifiable. Here's the error itself: 2295 6290 LOAD_NAME 'root' 6292 LOAD_ATTR 'mainloop' 6296 CALL_FUNCTION_0 0 '' 6298 POP_TOP Parse error at or near `POP_TOP' instruction at offset 996 Here's the bytecode around the error line 966 LOAD_NAME 23 (ttk) 968 LOAD_ATTR 110 (Button) 970 LOAD_NAME 107 (iS1cols) 972 LOAD_NAME 112 (tools_be_xl) 974 LOAD_NAME 43 (tools_browse_xls) 976 LOAD_CONST 126 (('textvariable', 'command')) 978 CALL_FUNCTION_KW 3 980 LOAD_ATTR 108 (grid) 982 LOAD_CONST 0 (0) 984 LOAD_CONST 121 (20) 986 LOAD_CONST 117 (4) 988 LOAD_CONST 127 (2) 990 LOAD_NAME 109 (W) 992 LOAD_CONST 128 (('row', 'padx', 'pady', 'column', 'sticky')) 994 CALL_FUNCTION_KW 5 996 POP_TOP 998 LOAD_NAME 23 (ttk) 1000 LOAD_ATTR 113 (LabelFrame) 1002 LOAD_NAME 91 (tab3Int) 1004 LOAD_CONST 129 (' Bulk Edit ') 1006 LOAD_CONST 107 (('text',)) 1008 CALL_FUNCTION_KW 2 1010 STORE_NAME 114 (imgStep1)
tagged with: decompiling
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85874966
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/85874428
has comment: http://stackoverflow.com/comment/85874553
has comment: http://stackoverflow.com/comment/85875288
has comment: http://stackoverflow.com/comment/85875590
has answer: http://stackoverflow.com/a/49518726
has comment: http://stackoverflow.com/comment/85916912
has comment: http://stackoverflow.com/comment/85874003
has comment: http://stackoverflow.com/comment/85874700
has comment: http://stackoverflow.com/comment/86043002

http://stackoverflow.com/comment/85586544
has text: i've filed a bug report with the emacs mailing list.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49290496
score: 0

http://stackoverflow.com/a/49281717
has body: This code might show you the basic idea. I used your sample line plus one line without the place data. Read the data line by line, splitting on white space. If only the numeric data is present put it out to temporary storage, in this code, StringIO. If there's string data too then format appropriately first. 'Rewind' the temporary storage and read it with pandas. import pandas as pd from io import StringIO for_pd = StringIO() with open('zafar.txt') as zafar: for line in zafar: line = line.strip() items = line.split() if len(items) == 6: print(','.join(items), file=for_pd) elif len(items) == 9: print(','.join(items[:6])+',"{} ({}), {}"'.format(items[7],items[6],items[8]), file=for_pd) for_pd.seek(0) df = pd.read_csv(for_pd, header=None, names=['1','2','3','4','5','6','place']) print(df) Output: 1 2 3 4 5 6 place 0 5440 1988 2018 439 49.0116 10.9308 NaN 1 5440 1988 2018 439 49.0116 10.9308 Emetzheim (Weißenburg), Bayern
score: 0
answers question: http://stackoverflow.com/q/49280161
type: Answer

http://stackoverflow.com/q/49285147
upvote count: 1
favorite count: 0
type: Question
tagged with: http-status-codes
has title: Getting 200 status code instead of 201 or 204
tagged with: python
has body: I'm using Swagger 2.0 to create the framework of a python-flask backend. I declared the POST /image endpoint as following on the Swagger online Editor: /image: post: summary: "Description." operationId: "image_post" consumes: - "multipart/form-data" parameters: - in: "formData" name: "upfile" description: "The file to upload." required: true type: "file" responses: 201: description: "Ok" schema: type: "string" 400: description: "bad image" x-swagger-router-controller: "swagger_server.controllers.default_controller" After downloading the python-flask server, I run it with the command python -m swagger_server. When sending a post request through postman I get that the status code is 200 instead of 201. It also shows 200 on the command line where the server is running. Any clues if this is a bug? or am I doing something wrong?
tagged with: flask
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49285756
score: 1
tagged with: swagger
has answer: http://stackoverflow.com/a/49285756
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85683664
score: 1
comment on: http://stackoverflow.com/q/49341568
type: QuestionComment
has text: You can obviously do that by wrapping up the series with a frozen-series-holder that manually computes a hash when constructed by, e.g., hashing tuples of tuples of the values, and then working with those holders everywhere, but there may be a much simpler way.
type: Comment

http://stackoverflow.com/a/49424954
has body: You can use numpy and a regex-based replacement to cover A1, A2 and more. if we extend your data to include an example with A3: import pandas as pd import numpy as np df = pd.DataFrame({'key': ['A', 'B', 'C', 'A', 'B', 'C', 'A'], 'data1': range(7), 'data2': ['A1', 'B1', 'C1', 'A1', 'B1', 'C1', 'A3']}, columns=['key', 'data1', 'data2']) df['data2'] = np.where((df['key'] == 'A') &amp; (df['data1'] &gt; 1), df['data2'].str.replace(r'A\d+','Bad'), df['data2']) This returns: key data1 data2 0 A 0 A1 1 B 1 B1 2 C 2 C1 3 A 3 Bad 4 B 4 B1 5 C 5 C1 6 A 6 Bad
accepted answer of: http://stackoverflow.com/q/49424733
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49424733
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85633717
comment on: http://stackoverflow.com/a/49315528
type: AnswerComment
has text: @DebasmitaBhoumik great, if my answer helped, please accept it.
score: 1
type: Comment

http://stackoverflow.com/a/49396651
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49396311
has body: How about using the reduce function which is present in 2.7? reduce is often used in conjunction with map to aggregate lists after some number of map transformations. Here's my 3.5 version of it, which should be close, if not identical to 2.7: startVal = 18 myList = [0,0,0,1,0,2] accumulator = reduce((lambda x, y: ( x + [y + (0 if len(x) == 0 else x[-1])])), myList, []) [startVal + v for v in accumulator] &gt;&gt; [18, 18, 18, 19, 19, 21] I'm taking advantage of addition of lists (which concatenates) to append subsequent values to the empty list defined in the initializer. There's a little conditional since you can't get the last entry of an empty list.
type: Answer
accepted answer of: http://stackoverflow.com/q/49396311

http://stackoverflow.com/comment/85781919
score: 0
has text: @AlexEshoo your code looks pretty much like what I THINK mine is doing. Very strange. I will post my actual code (just shortened by really irrelevant stuff) in an edit of the original post.
comment on: http://stackoverflow.com/q/49327987
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49372306
downvote count: 1
has answer: http://stackoverflow.com/a/49372331
possible better answer: http://stackoverflow.com/a/49372331
has body: I want to print the binary numbers 0x00 to 0xFF with their full 8-bit format. The bin() Python function won't return the full 8 bits, so I need to use the format function to format the binary string. This code below is giving me a ValueError, but I'm passing a binary string to the format function and I'm using 08b so why is it giving an error? a = bin(10); a_bin = "{0:08b}".format(a);
favorite count: 0
type: Question
tagged with: integer
answer count: 2
accepted answer: http://stackoverflow.com/a/49372347
has title: ValueError when converting number to 8-bit format
tagged with: python
tagged with: string
upvote count: 2
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49372347

http://stackoverflow.com/a/49433978
has comment: http://stackoverflow.com/comment/85870295
answers question: http://stackoverflow.com/q/49432135
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85870292
has comment: http://stackoverflow.com/comment/85869910
accepted answer of: http://stackoverflow.com/q/49432135
type: Answer
has comment: http://stackoverflow.com/comment/85870131
has body: You have to iterate over all boids in the self._boids list and update their _pos and bird_rect attributes to move them. def move_boids(self): s = Screen() for boid in self._boids: boid._pos += boid._vel * boid.speed boid.bird_rect.center = boid._pos # Bounds check. if boid._pos.x + boid.bird_rect.width &gt;= s.width: boid._pos.x = s.width - boid.bird_rect.width boid._vel.x *= -1 elif boid._pos.x &lt;= 0: boid._pos.x = 0 boid._vel.x *= -1 if boid._pos.y - boid.bird_rect.height &lt;= 0: boid._pos.y = boid.bird_rect.height boid._vel.y *= -1 elif boid._pos.y &gt;= s.height: boid._pos.y = s.height - boid.bird_rect.height boid._vel.y *= -1 You can also simplify the draw method a bit. def draw_boids(self): # Blit all boids at their rects. for boid in self._boids: screen.blit(boid.bird, boid.bird_rect)

http://stackoverflow.com/a/49344598
type: Answer
accepted answer of: http://stackoverflow.com/q/49344301
has comment: http://stackoverflow.com/comment/85701371
has body: Use a generator function! def mygenerator(word): while len(word) &gt; 0: lastletter = word[-1].lower() # get last letter word = word[0:-1] # remove last letter for lv in range(ord(lastletter), ord('z')+1): letter = chr(lv) yield word+letter Here is a test: &gt;&gt;&gt; print(list(mygenerator('jason'))) ['jason', 'jasoo', 'jasop', 'jasoq', 'jasor', 'jasos', 'jasot', 'jasou', 'jasov', 'jasow', 'jasox', 'jasoy', 'jasoz', 'jaso', 'jasp', 'jasq', 'jasr', 'jass', 'jast', 'jasu', 'jasv', 'jasw', 'jasx', 'jasy', 'jasz', 'jas', 'jat', 'jau', 'jav', 'jaw', 'jax', 'jay', 'jaz', 'ja', 'jb', 'jc', 'jd', 'je', 'jf', 'jg', 'jh', 'ji', 'jj', 'jk', 'jl', 'jm', 'jn', 'jo', 'jp', 'jq', 'jr', 'js', 'jt', 'ju', 'jv', 'jw', 'jx', 'jy', 'jz', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] This implements most of the logic you requested. I hope it helps illustrate how flexible and powerful python is.
answers question: http://stackoverflow.com/q/49344301
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/85657422
type: AnswerComment
has text: I see, thank you for that! Do you know why the tick labels for the y margin plot are not being changed to 1,10,100,1000?
comment on: http://stackoverflow.com/a/49327274
score: 0
type: Comment

http://stackoverflow.com/q/49388511
downvote count: 0
possible better answer: http://stackoverflow.com/a/49456776
accepted answer: http://stackoverflow.com/a/49513533
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49456776
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44212250
has answer: http://stackoverflow.com/a/49513533
has title: send file from server to client on bokeh
tagged with: javascript
tagged with: python
has body: I have made a user interface to fetch data from a MySQL table and visualize it. It is running on a bokeh server. My users connect remotely to the server using their browser (firefox). This works perfectly fine: I simply import the table into a pandas dataframe. My users also need to download the table as excel. This means I cannot use the export_csv example which is pure javascript. I have no experience with JavaScript. All I want is to transfer a file from the directory where my main.py is to the client side. The technique I have tried so far is to join a normal on_click callback to a button, export the information I need to 'output.xls', then change a parameter from a dummy glyph which in turn runs a Javascript code. I got the idea from Bokeh widgets call CustomJS and Python callback for single event? . Note I haven't set the alpha to 0, so that I can see if the circle is really growing upon clicking the download button. At the bottom of my message you can find my code. You can see I have tried with both XMLHttpRequest and with Fetch directly. In the former case, nothing happens. In the latter case I obtain a file named "mydata.xlsx" as expected, however it contains only this raw text: 404: Not Found 404: Not Found . Code: p = figure(title='mydata') #download button download_b = Button(label="Download", button_type="success") download_b.on_click(download) #dummy idea from https://stackoverflow.com/questions/44212250/bokeh-widgets-call-customjs-and-python-callback-for-single-event dummy = p.circle([1], [1],name='dummy') JScode_xhr = """ var filename = p.title.text; filename = filename.concat('.xlsx'); alert(filename); var xhr = new XMLHttpRequest(); xhr.open('GET', '/output.xlsx', true); xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { var blob = this.response; alert('seems to work...'); if (navigator.msSaveBlob) { navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); link = document.createElement('a')…
tagged with: bokeh
type: AnsweredQuestion
answer count: 2
score: 2
upvote count: 2

http://stackoverflow.com/comment/85656181
has text: i am not able to get the result i am looking for
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49327192

http://stackoverflow.com/q/49375620
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49376111
score: 1
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Importing Social Media Followers
has comment: http://stackoverflow.com/comment/85752954
duplicate of: http://stackoverflow.com/q/49043857
has comment: http://stackoverflow.com/comment/85753055
has comment: http://stackoverflow.com/comment/85753069
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85752852
tagged with: python
tagged with: jupyter-notebook
has body: I was running this code for a while on Python 2.7 in order to automatically collect the number of followers of certain accounts on Twitter and Instagram. This code is supposed to give me the number of Twitter and Instagram followers of a basketball player in real time. The code has stopped working this week and I cannot find a way to fix it. I would really appreciate if anyone has a solution! import requests from json import loads Username = "nolimittb" r = requests.get('https://www.instagram.com/'+Username) html = r.text.encode("utf-8") text = html[html.index("window._sharedData = ")+21:] text = (text[:text.index("};&lt;/script&gt;")]+"}").replace('\\"', "") dictionary= loads(text) data = dictionary["entry_data"]["ProfilePage"][0][user] print "Thomas Bryant Instagram:" print str(data["followed_by"]["count"]) + ' Followers' from bs4 import BeautifulSoup import requests username='nolimittb31' url = 'https://www.twitter.com/'+username r = requests.get(url) soup = BeautifulSoup(r.content) f = soup.find('li', class_="ProfileNav-item--followers") title = f.find('a')['title'] print 'Thomas Bryant Twitter:' print title num_followers = int(title.split(' ')[0].replace(',',''))
has comment: http://stackoverflow.com/comment/85753035
has comment: http://stackoverflow.com/comment/85752923
has comment: http://stackoverflow.com/comment/85752342
has comment: http://stackoverflow.com/comment/85752952
linked to: http://stackoverflow.com/q/49043857

http://stackoverflow.com/a/49317575
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49317166
has comment: http://stackoverflow.com/comment/85636737
has body: arr=[1,4,10] con=3 [r + i for r in arr for i in range(con)] # [1, 2, 3, 4, 5, 6, 10, 11, 12]
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85636416

http://stackoverflow.com/q/49310776
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49311245
has answer: http://stackoverflow.com/a/49311245
possible better answer: http://stackoverflow.com/a/49311130
has title: XlsxWriter write_formula with date
has answer: http://stackoverflow.com/a/49311130
tagged with: python
type: AnsweredQuestion
score: 3
answer count: 2
upvote count: 3
tagged with: xlsxwriter
downvote count: 0
has body: I am trying to use formula to copy a date value from a cell to another. But trying to add date format to worksheet.write_formula() causes the excel to to show the following alert Here is a sample code I am using: import xlsxwriter from datetime import date workbook = xlsxwriter.Workbook("testFile.xlsx") worksheet = workbook.add_worksheet() dateFmt = workbook.add_format({'num_format': 'mm/dd/yyyy'}) worksheet.write(0, 0, date(2018, 12, 26),dateFmt) worksheet.write_formula('B1','=A1', dateFmt, date(2018, 12, 26)) workbook.close()

http://stackoverflow.com/comment/85805155
score: 0
comment on: http://stackoverflow.com/q/49401730
type: QuestionComment
type: Comment
has text: I tried to do this with the help of pyqtSignal() and it worked fine

http://stackoverflow.com/comment/85811484
type: Comment
type: AnswerComment
has text: I think you have better solution :)
comment on: http://stackoverflow.com/a/49404579
score: 1

http://stackoverflow.com/comment/85741461
comment on: http://stackoverflow.com/q/49328103
has text: can you also explain what do you mean when you say y_i? is it a target value for the i-th sample?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49338910
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49338772
answers question: http://stackoverflow.com/q/49338772
has body: There are hundreds of answer, depending on too many factors. But if in doubt, refer to the Zen of Python: Explicit is better than implicit. and Readability counts. may suggest to go for slot_1 = 'med kit' if slot_1 == 'med kit': print('med kit ready') since it's more readable
downvote count: 0
type: Answer

http://stackoverflow.com/a/49347468
answers question: http://stackoverflow.com/q/49347379
has body: I figured it out! i thought i had tried this solution already, but apparently there was a typo. here is how i solved it: &gt;&gt;&gt; headlines = davarsoup.select('.headline &gt; a') sorry to bother anyone who might have bothered.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49347379
type: Answer

http://stackoverflow.com/q/49351487
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/85703508
type: Question
has comment: http://stackoverflow.com/comment/85706494
linked to: http://stackoverflow.com/q/41624567
has body: Let's say I have a list L=[[a,2],[a,3],[a,4],[b,4],[b,8],[b,9]] Using pyspark I want to be able to remove the third element so that it will look like this: [a,2] [a,3] [b,4] [b,8] I am new to pyspark and not sure what I should do here.
linked to: http://stackoverflow.com/q/627435
tagged with: pyspark
has title: Get the top two elements in a nested list - pyspark
has comment: http://stackoverflow.com/comment/85703543
tagged with: python
has comment: http://stackoverflow.com/comment/85717634
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85703270
tagged with: apache-spark
linked to: http://stackoverflow.com/q/11303225
accepted answer: http://stackoverflow.com/a/49355442
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49355442

http://stackoverflow.com/q/49280675
score: 16
has answer: http://stackoverflow.com/a/49280763
tagged with: scikit-learn
tagged with: python
has body: To be more specific, I want to modify some functions in scikit-learn and import it to python. But I do not know how to work. I tried to modify .py files directly from where the sklearn stores in my local directory, but there are some files I could not open to modify, such as those with .cp36-win_amd64. Any advice would be helpful!
answer count: 2
has answer: http://stackoverflow.com/a/49280742
tagged with: github
downvote count: 1
favorite count: 0
has title: How do I modify a library in python and use it?
upvote count: 17
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/85793737
type: Comment
type: QuestionComment
has text: @sytech edited my ppost. I am not using multiple databases, I'm just letting SQLAlchemy connect to the database and then create the relations. EDIT: disregard. What I recently typed about not being able to see it in psql.
comment on: http://stackoverflow.com/q/49395490
score: 0

http://stackoverflow.com/a/49301385
upvote count: 1
answers question: http://stackoverflow.com/q/49300784
has body: it seems like you want to group by the index and take average of all the columns except lvl i.e. df.groupby(df.index)[[0,1,2,3]].mean() For a dataframe generated using np.random.seed(456) a = [] for i in range(5): tmp_df = pd.DataFrame(np.random.random((10,4))) tmp_df['lvl'] = i a.append(tmp_df) df = pd.concat(a, axis=0) df.groupby(df.index)[[0,1,2,3]].mean() outputs: 0 1 2 3 0 0.411557 0.520560 0.578900 0.541576 1 0.253469 0.655714 0.532784 0.620744 2 0.468099 0.576198 0.400485 0.333533 3 0.620207 0.367649 0.531639 0.475587 4 0.699554 0.548005 0.683745 0.457997 5 0.322487 0.316137 0.489660 0.362146 6 0.430058 0.159712 0.631610 0.641141 7 0.399944 0.511944 0.346402 0.754591 8 0.400190 0.373925 0.340727 0.407988 9 0.502879 0.399614 0.321710 0.715812 which is identical to the output from df.groupby(df.groupby('lvl').cumcount()).mean() without resorting to double groupby. IMO this is cleaner to read and will for large dataframe, will be much faster.
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/49364919
type: Answer
answers question: http://stackoverflow.com/q/49319996
score: 0
has body: I use that script to parse metadata: url = 'http://localhost:8000/radio' request = urllib2.Request(url, headers={'Icy-MetaData': 1}) # request metadata response = urllib2.urlopen(request) #print(response.headers, file=sys.stderr) metaint = int(response.headers['icy-metaint']) # title may be empty initially, try several times response.read(metaint) # skip to metadata metadata_length = struct.unpack('B', response.read(1))[0] * 16 # length byte metadata = response.read(metadata_length).rstrip(b'\0')

http://stackoverflow.com/comment/85801471
comment on: http://stackoverflow.com/q/49400118
score: 0
type: Comment
type: QuestionComment
has text: You might want to use `string.punctuation` (after importing the `string` library first) instead of `'-.,;”“'` EG: `for char in string.punctuation:`

http://stackoverflow.com/a/49402507
type: Answer
score: 5
answers question: http://stackoverflow.com/q/49402486
type: AcceptedAnswer
downvote count: 0
has body: Use boolean indexing with index: a = df.index[df['Score'] &lt; 0] print (a) Int64Index([2], dtype='int64')
accepted answer of: http://stackoverflow.com/q/49402486
upvote count: 5

http://stackoverflow.com/comment/85837091
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49409550
has text: Can you provide the actual Python traceback and error?

http://stackoverflow.com/q/49372057
linked to: http://stackoverflow.com/q/28675121
has body: How can I create a new repository in an organization with PyGithub on Github? In particular I like to know how to use the create_repo method? My question is identical to this question, but I would like the created repository to appear in an organization. The solution to creating a repo without the organization level is: g = Github("username", "password") user = g.get_user() repo = user.create_repo(full_name)
type: AnsweredQuestion
tagged with: github-api
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49374492
tagged with: api
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/57218792
possible better answer: http://stackoverflow.com/a/57218792
tagged with: github
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49374492
tagged with: pygithub
has title: How to create a new repository in an organization with PyGithub
tagged with: python

http://stackoverflow.com/comment/85589747
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49293518
has text: @IljaEverilä with `.encode("utf-8")` I get the same.
score: 0

http://stackoverflow.com/a/49354060
answers question: http://stackoverflow.com/q/49354014
type: Answer
has comment: http://stackoverflow.com/comment/85708736
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49354014
has body: Your logging function groups commands by userid but you seem to want an overall count for all users? If that is the case it makes little sense to add a "usage" column to the log table. You could use a separate table to keep usage counts per command, but it's far easier to do nothing at all. Keep the current log table then get the count using SQL: select count(*) from logs where command = '/start' then you can find the current count for any command. This is more flexible too; if you wanted the count for a single user then you could augment the WHERE clause to filter by userid. Grouping is also possible using GROUP BY. Original answer Can't you just pass the first part of the command string to the log function? if text.startswith('/'): command = text.split()[0] logs(user_id, telegram_nickname, command) if command == '/start': etc...etc.. Here str.split() is used to grab the first part of the command for logging.
has comment: http://stackoverflow.com/comment/85708538

http://stackoverflow.com/comment/85753293
score: 0
type: Comment
has text: Also, if you _did_ change the list, I'm not sure whether that would do what you wanted. For example, if you start with `[1, 1, 1]`, and then change the first `1` to `1 + e.count(1) + 1`, it would become `5`. Then when you get to the second `1`, there are no longer three `1`s, but only `2`, so it would become `4`. Is `[5, 4, 3]` really the output you want there, rather than `[5, 5, 5]`?
type: QuestionComment
comment on: http://stackoverflow.com/q/49376099

http://stackoverflow.com/comment/85721339
type: Comment
has text: https://www.sqlite.org/lang_expr.html#like, SQLite LIKE is case insensitive in the ASCII range by default, it seems. It can be made case sensitive using the [case_sensitive_like pragma](https://www.sqlite.org/pragma.html#pragma_case_sensitive_like). SQLAlchemy [`ColumnElement.contains()`](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement.contains) is simply a shorthand for `col LIKE '%' || expr || '%'`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49360525
score: 0

http://stackoverflow.com/a/49377810
type: Answer
has comment: http://stackoverflow.com/comment/85756665
answers question: http://stackoverflow.com/q/49377703
score: 0
has comment: http://stackoverflow.com/comment/85756749
has body: Do you have this set? export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH Also just to be sure, add the path to the py4j zip (mine is py4j-0.10.1-src.zip) in the spark directory as: export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.10.1-src.zip:$PYTHONPATH

http://stackoverflow.com/a/49336117
accepted answer of: http://stackoverflow.com/q/49335914
has comment: http://stackoverflow.com/comment/85673589
has body: You can use a dict (an Ordered one since you have to maintain the order) to group "heads" by "tails": alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]] from collections import OrderedDict c = OrderedDict() for head, tail in alist: c.setdefault(tuple(tail), []).append(head) res = [[heads, list(tail)] for tail, heads in c.items()] print res prints [[[1, 3, 6], [1, 2]], [[2, 4], [3, 4, 5]], [[5], [5, 6, 7]]] If you want to omit 5 (a group with a single "head"), add a condition to the res= line: res = [[heads, list(tail)] for tail, heads in c.items() if len(heads) &gt; 1]
type: Answer
has comment: http://stackoverflow.com/comment/85673629
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49335914

http://stackoverflow.com/q/49363806
tagged with: python
tagged with: plot
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85810341
has title: Python: Animated plot does not work for me
has body: I am trying to make an animated plot, which plots the content of my "input" matrix. (input[1,t,x,y,0]=z where x is the x coordinate, y the y coordinate, z the color value and t the time value over which I want to animate my plot) But when I run the code I only get a static picture of a certain time value. Does anyone have an idea why this is so? Thanks for any help. Here is the code: def plot_fig(): global M fig = plt.figure(figsize=(5,5)) my_img=plt.imshow(input[1,0,:,:,0],origin='lower',interpolation='nearest',vmin=0.0,vmax=1.0) plt.colorbar() plt.axis('off') # no axes def update(frame_number): global t global input print("update") t += 1 my_img.set_data(input[1,t,:,:,0]) return my_img anim = FuncAnimation(fig, update, interval=10) plt.show() print("end")
type: Question
linked to: http://stackoverflow.com/q/49404585
type: UnansweredQuestion
tagged with: animation
has comment: http://stackoverflow.com/comment/85809675

http://stackoverflow.com/comment/85852444
type: QuestionComment
comment on: http://stackoverflow.com/q/49425737
has text: Aren't you already looking for what you already have in the second file. I don't understand the use case; you can just read the second file instead.
score: 1
type: Comment

http://stackoverflow.com/comment/85879931
score: 0
comment on: http://stackoverflow.com/q/49437216
type: Comment
type: QuestionComment
has text: yes, I noticed NPY_UNIT32 and NPY_UINT64 were not implemented- perhaps there is some good reason why- one of the devs might be able to explain it. In the meantime, you can maybe use tf.int64 or tf.int16 in the from_generator function (both worked for me).

http://stackoverflow.com/a/49385013
answers question: http://stackoverflow.com/q/49384449
has comment: http://stackoverflow.com/comment/85771906
score: 0
type: Answer
has body: Point your %PYSPARK_DRIVER_PYTHON% to a virtual environment with all dependencies including 'Poller' and then check. Else you can try installing 'Poller' in ipython environment( which I frankly dont know how!)
has comment: http://stackoverflow.com/comment/85771681

http://stackoverflow.com/a/49284744
upvote count: 1
type: Answer
downvote count: 1
has body: You can unpack after sorting the contents of the dictionary: import re dictionary = {'key1': ['color1','color2'],'key2':['car1','car2'],'key3':['frut1']} key1, key2, key3 = sorted(dictionary.items(), key=lambda x:int(re.findall('\d+$', x[0])[0]))
has comment: http://stackoverflow.com/comment/85572375
has comment: http://stackoverflow.com/comment/85572407
answers question: http://stackoverflow.com/q/49284640
has comment: http://stackoverflow.com/comment/85573618
score: 0

http://stackoverflow.com/q/49330732
has body: def words(): quote = input("Enter a 1 sentence quote, non-alpha separate words: ") word = "" for ltr in quote: if ltr.isalpha(): word = word + ltr else: if word[0].lower() &gt; "g": print(word.upper()) word = "" else: word = "" Here all the info. Seriously I do not know what to do.
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 2
tagged with: python
has title: I can't deal with "IndexError: string index out of range" in Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85663562
score: 0
has comment: http://stackoverflow.com/comment/85663764
has answer: http://stackoverflow.com/a/49330769
answer count: 1
has comment: http://stackoverflow.com/comment/85663592
accepted answer: http://stackoverflow.com/a/49330769
favorite count: 0

http://stackoverflow.com/q/49294705
downvote count: 0
has title: Plot precomputed charts in several axes
upvote count: 1
score: 1
answer count: 1
favorite count: 0
tagged with: plot
has body: Some matplotlib or seaborn functions need lots of time for computing, e.g. kdeplot. I'd like to create plt.subplots(2, 3), put the same kde plot to all the six axes and then add other stuff to every axis independently. Of course, I wouldn't like to compute kdeplot 6 times. How is it possible to avoid multiple computing?
accepted answer: http://stackoverflow.com/a/49296766
type: Question
tagged with: seaborn
has answer: http://stackoverflow.com/a/49296766
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85821260
comment on: http://stackoverflow.com/q/49408730
type: QuestionComment
has text: @jsanchezs That's one of the things that's missing, but it's more than that. The `action` for the first form is `file2`, so the `add` view will never process a `POST` request, and that's probably not what's intended (as well as the `action` in the second form, which is almost certainly wrong).
score: 0
type: Comment

http://stackoverflow.com/q/49383678
has body: How do you use the db object and its session attribute within a celery task? Should I call db.session.remove at the end of the task? The db object is instantiated as db = SQLAlchemy(app) The file that defines the tasks is structured like that: from project import celery, db, app from project.models import Model @celery.task() def task_1(): model = Model.query.get(0) model.arg = 1 db.session.commit() If the concurrency is set to 1, everything works as expected. If the --maxtaskperchild argument is specified, that task starts throwing: “MySQL server has gone away” errors as soon as the --maxtaskperchild is hit (i.e, a second process is started in place of the first one). However, if I don't specify maxtasksperchild, I don't have errors anymore. What is the best practice to handle session within a celery task?
tagged with: flask
tagged with: celery
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: 2
has title: Celery + Fask-Sqlalchemy
answer count: 0
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85770885
type: AnswerComment
comment on: http://stackoverflow.com/a/49384789
score: 0
type: Comment
has text: Not possible. The models are different, so you will have an error telling you that you cannot load 100 layers in a model with 200 layers. (random numbers)

http://stackoverflow.com/q/49401692
duplicate of: http://stackoverflow.com/q/743806
type: Question
has comment: http://stackoverflow.com/comment/85804683
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85804600
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49401755
downvote count: 4
has body: Hello guys this is my program : GNU nano 2.7.4 File : com.py #!/usr/bin/env python # -*- coding: utf-8 -*- import serial import time import sys ser = serial.Serial('/dev/ttyACM0', 9600) time.sleep(4) while True: mdp = raw_input("Enter Number :") print mdp ser.write(mdp) print(ser.readline()) time.sleep(1) When i execute it i get those number 15.80-14-18.00-14.24 and i want to use each number in different variables like : var1=15.80 var2=14 var3=18.00 var4=14.24 Thank you for taking time to read my question. Edit: thanks for your answer 14.50-14-19.30-3.34 14.50 14 19.30 3.34 Enter Number: 5 5 14.50-14-19.30-3.34 Traceback (most recent call last): File "com.py", line 15, in &lt;module&gt; var1,var2,var3,var4 = var0.split("-") i had a problem with the serial connection i want to test "var0" and know if it has 4 value or not
linked to: http://stackoverflow.com/q/1373164
answer count: 1
linked to: http://stackoverflow.com/q/743806
upvote count: 1
tagged with: variables
has title: how to seperate variables i received?
accepted answer: http://stackoverflow.com/a/49401755
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0

http://stackoverflow.com/comment/86913604
type: QuestionComment
has text: Same problem with `PyYAML<=3.12,>=3.10 (from awscli==1.15.5`, byt I already have python 3.6.4. and couldn't upgrade to Django 2 yet.
score: 0
comment on: http://stackoverflow.com/q/49386295
type: Comment

http://stackoverflow.com/comment/85970552
comment on: http://stackoverflow.com/a/49465622
type: Comment
score: 0
type: AnswerComment
has text: Thanks. I got the code working. But windowing alone didn't do the trick. Adding this line solved the issue `pipeline_options.view_as(StandardOptions).streaming = True`. Any idea what this does?

http://stackoverflow.com/comment/85649528
has text: @S.Pnt glad to help. Let me know if it works out for you. If my answer solves your problem don't forget to select the check box next to the answer so everyone can know your issues has been solved.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49323903
type: Comment

http://stackoverflow.com/comment/85726556
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49360384
type: QuestionComment
has text: I'm afraid I can't reproduce it (Ubuntu 17.10, libfbclient2 3.0.2, python 3.6 and fdb 1.8). I'll try to find the time to install a clean 16.04 VM and see if I can reproduce it that way

http://stackoverflow.com/a/49371005
has comment: http://stackoverflow.com/comment/85744561
score: 0
has comment: http://stackoverflow.com/comment/85744667
type: Answer
has comment: http://stackoverflow.com/comment/85743401
answers question: http://stackoverflow.com/q/49370713
has body: This is the loopy way. It will not be fast, but requires minimal memory. I use .iat for fast integer-based lookup, so care is required if you have other columns in your dataframe. import pandas as pd data = [{'id': 'Jones', 'tf': [(0, 0.5), (1,2.0)]}, {'id': 'Alpha', 'tf': [(1,2.0)]}, {'id': 'Blue', 'tf': [(2,0.1),(1,0.2)]}] df = pd.DataFrame(data) df = df.join(pd.DataFrame(columns=[0, 1, 2])) for idx, lst in enumerate(df['tf']): for tup in lst: df.iat[idx, tup[0]+2] = tup[1] df = df.drop('tf', 1).melt('id').dropna(subset=['value']) # id variable value # 0 Jones 0 0.5 # 3 Jones 1 2 # 4 Alpha 1 2 # 5 Blue 1 0.2 # 8 Blue 2 0.1

http://stackoverflow.com/q/49327371
tagged with: python
has comment: http://stackoverflow.com/comment/85656600
score: 0
has comment: http://stackoverflow.com/comment/85656673
has comment: http://stackoverflow.com/comment/85657453
has comment: http://stackoverflow.com/comment/85656486
tagged with: email
type: Question
answer count: 2
has title: Unable to send email __Connection Refused Error
type: UnansweredQuestion
has body: import smtplib sender = 'user@gmail.com' receivers = ['user_2@gmail.com'] message = """From: User &lt;user@gmail.com&gt; To: To user_2 &lt;user_2@gmail.com&gt; Subject: message this is a test megssage. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print ("Successfully sent email") except smtplib.SMTPException: print ("Error: unable to send email") When I try to run this program, it shows an error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Moreover what do I have to put in localhost?
has answer: http://stackoverflow.com/a/49327481
has answer: http://stackoverflow.com/a/49327604

http://stackoverflow.com/q/49283143
accepted answer: http://stackoverflow.com/a/49806006
has answer: http://stackoverflow.com/a/54325517
tagged with: anaconda
downvote count: 0
possible better answer: http://stackoverflow.com/a/54325517
answer count: 3
has body: I am trying to reinstall anaconda 64 bit on Windows 7 to use Python 3.6 and the installations works right till the end but it fails executing the post install script with following error. However, if I check the Lib folder in the Anaconda3 folder, I see the files _nsis.py and subprocess.py which the installer says are missing. Ignoring the error results in no Anaconda navigator in the start menu but the Anaconda prompt is available for some reason. I tried installing Miniconda too but am facing the same issue. Below is the error snapshot
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/56627583
has title: Anaconda installation fails due to post install scripts Win 2 Error
favorite count: 0
type: Question
tagged with: python
tagged with: failed-installation
has answer: http://stackoverflow.com/a/49806006
type: AnsweredQuestion

http://stackoverflow.com/comment/85737641
type: Comment
score: 0
type: AnswerComment
has text: Ah, I've overlooked that, my bad. Edited the answer.
comment on: http://stackoverflow.com/a/49357945

http://stackoverflow.com/a/49367945
upvote count: 14
accepted answer of: http://stackoverflow.com/q/49367144
type: Answer
has comment: http://stackoverflow.com/comment/85783055
answers question: http://stackoverflow.com/q/49367144
has comment: http://stackoverflow.com/comment/85739381
has comment: http://stackoverflow.com/comment/85782432
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85779385
score: 13
downvote count: 1
has body: The answer to get the result smooth lies in constructing your own colormap. To do this one has to create an RGBA-matrix: a matrix with on each row the amount (between 0 and 1) of Red, Green, Blue, and Alpha (transparency; 0 means that the pixel does not have any coverage information and is transparent). As an example the distance to some point is plotted in two dimensions. Then: For any distance higher than some critical value, the colors will be taken from a standard colormap. For any distance lower than some critical value, the colors will linearly go from white to the first color of the previously mentioned map. The choices depend fully on what you want to show. The colormaps and their sizes depend on your problem. For example, you can choose different types of interpolation: linear, exponential, ...; single- or multi-color colormaps; etc.. The code: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable # create colormap # --------------- # create a colormap that consists of # - 1/5 : custom colormap, ranging from white to the first color of the colormap # - 4/5 : existing colormap # set upper part: 4 * 256/4 entries upper = mpl.cm.jet(np.arange(256)) # set lower part: 1 * 256/4 entries # - initialize all entries to 1 to make sure that the alpha channel (4th column) is 1 lower = np.ones((int(256/4),4)) # - modify the first three columns (RGB): # range linearly between white (1,1,1) and the first color of the upper colormap for i in range(3): lower[:,i] = np.linspace(1, upper[0,i], lower.shape[0]) # combine parts of colormap cmap = np.vstack(( lower, upper )) # convert to matplotlib colormap cmap = mpl.colors.ListedColormap(cmap, name='myColorMap', N=cmap.shape[0]) # show some example # ----------------- # open a new figure fig, ax = plt.subplots() # some data to plot: distance to point at (50,50) x,y = np.meshgrid(np.linspace(0,99,100),np.linspace(0,99,100)) z = (x-50)**2. + (y-50)**2. …
has comment: http://stackoverflow.com/comment/85747530

http://stackoverflow.com/a/49289060
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85608126
answers question: http://stackoverflow.com/q/49288674
has body: A possible solution is to use indexAt() since the position of the QComboBox is relative to the viewport(), but to obtain the QComboBox that was selected we use sender(). for n,item in enumerate(wbs_details): qitem = QtGui.QTableWidgetItem(item[0]) self.projectlist.setItem(n, 0, qitem) qitem = QtGui.QTableWidgetItem(item[1]) self.projectlist.setItem(n, 1, qitem) milestone_options = ["Award","Mobilization","Survey"] milestonecombo = QtGui.QComboBox() milestonecombo.addItems(milestone_options) milestonecombo.setFixedWidth(150) milestonecombo.currentIndexChanged[str].connect(self.onCurrentIndexChanged) self.projectlist.setCellWidget(n, 2, milestonecombo) def onCurrentIndexChanged(self, text): combobox = self.sender() ix = self.projectlist.indexAt(combobox.pos()) print(ix.row(), ix.column(), text) Another possible solution is to use the property: for n,item in enumerate(wbs_details): qitem = QtGui.QTableWidgetItem(item[0]) self.projectlist.setItem(n, 0, qitem) qitem = QtGui.QTableWidgetItem(item[1]) self.projectlist.setItem(n, 1, qitem) milestone_options = ["Award","Mobilization","Survey"] milestonecombo = QtGui.QComboBox() milestonecombo.addItems(milestone_options) milestonecombo.setFixedWidth(150) milestonecombo.setProperty("row", n) milestonecombo.setProperty("column", 1) milestonecombo.currentIndexChanged[str].connect(self.onCurrentIndexChanged) self.projectlist.setCellWidget(n, 2, milestonecombo) def onCurrentIndexChanged(self, text): combobox = self.sender() r = combobox.property("row").toPyObject() c = combobox.property("column").toPyObject() print(r, c, text)
has comment: http://stackoverflow.com/comment/85607984
score: 1
has comment: http://stackoverflow.com/comment/85608302

http://stackoverflow.com/q/49286903
accepted answer: http://stackoverflow.com/a/49287160
answer count: 1
has body: I've got a sparse matrix with a few elements. Now I would like to row normalize it. However, when I do this, it gets converted to a numpy array, which is not acceptable from a performance standpoint. To make things more concrete, consider the following example: x = csr_matrix([[0, 1, 1], [2, 3, 0]]) # sparse normalization = x.sum(axis=1) # dense, this is OK x / normalization # this is dense, not OK, can be huge Is there an elegant way to do this without having to resort to for loops? EDIT Yes, this can be done using sklearn.preprocessing.normalize using 'l1' normalization, however, I have no wish to depend on sklearn.
linked to: http://stackoverflow.com/q/49254111
has comment: http://stackoverflow.com/comment/85576929
has comment: http://stackoverflow.com/comment/85577249
has comment: http://stackoverflow.com/comment/85577284
has comment: http://stackoverflow.com/comment/85576959
tagged with: scipy
tagged with: sparse-matrix
has title: Normalize sparse row probability matrix
type: Question
duplicate of: http://stackoverflow.com/q/49254111
has comment: http://stackoverflow.com/comment/85577198
has comment: http://stackoverflow.com/comment/85577325
has answer: http://stackoverflow.com/a/49287160
tagged with: python
linked to: http://stackoverflow.com/q/12305021
linked to: http://stackoverflow.com/q/30260642
has comment: http://stackoverflow.com/comment/85577129
tagged with: numpy
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/55677768
type: Answer
score: 11
has body: You will be able to find the lr_utils.py and all the other .py files (and thus the code inside them) required by the assignments: Go to the first assignment (ie. Python Basics with numpy) - which you can always access whether you are a paid user or not And then click on 'Open' button in the Menu bar above. (see the image below) . Then you can include the code of the modules directly in your code.
answers question: http://stackoverflow.com/q/49311929
has comment: http://stackoverflow.com/comment/127311647
downvote count: 0
upvote count: 11

http://stackoverflow.com/comment/85875317
score: 0
type: Comment
type: QuestionComment
has text: @Joe: I know that...which why I asked whether getting the objects in a `list` (aka JSON array) would be acceptable to them in my comment.
comment on: http://stackoverflow.com/q/49435728

http://stackoverflow.com/a/52625012
has body: try installing the xlrd version '0.9.4' Worked for me
type: Answer
answers question: http://stackoverflow.com/q/49325837
score: 0

http://stackoverflow.com/a/49293352
has body: It might well be the relative path you're using in the source command. Cron will run your script from a different directory, so source ./project/bin/activate will likely not be a valid path. Try source /home/abc/project/bin/activate ... guessed path based on the full path in your python3 ... line.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49293287
has comment: http://stackoverflow.com/comment/85589852
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85639927
has text: I don't know a command-line tool for that. `pip show` doesn't show `long_description`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49308861
score: 0

http://stackoverflow.com/q/49330030
tagged with: python
accepted answer: http://stackoverflow.com/a/49336043
type: AnsweredQuestion
tagged with: shapely
tagged with: geospatial
linked to: http://stackoverflow.com/q/12198468
has body: To remove duplicate lists from a list, there are several nice ways in Python - for example: a = [[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [ 9.1514622, 47.1166004 ] ] print len(a) # 5 b_set = set(map(tuple,a)) b = map(list,b_set) print len(b) # 4 But unfortunately, I had to convert my list to a Shapely Polygon object, in which I need to simplify the geometry and do some other geo functions. from shapely.geometry import Polygon a = [[[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [ 9.1514622, 47.1166004 ] ] ] polys = [Polygon(item) for item in a] # convert list to polygon print len(polys) # prints 5 This answer shows how to remove a duplicate Polygon from a list of Polygons, but how can I remove a duplicate point from a list of points, as a Shapely polygon? I guess it's possible to convert it back to a list, remove duplicates, and then re-convert to Polygon. But that seems overly complicated. Any ideas on how to do this?
linked to: http://stackoverflow.com/q/31622618
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49336043
has title: Remove a duplicate point from polygon in Shapely
tagged with: polygon
downvote count: 0
answer count: 1
score: 6
upvote count: 6

http://stackoverflow.com/q/49401344
favorite count: 0
type: Question
has title: How to store a varying size arraylist in a numpy array (for clustering purposes)?
tagged with: numpy
has body: a=[] for (x,y,w,h) in faces: for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) a.append(eyes) i+=1 print(a) eyes is the detection output from detectMultiScale using eye_cascade (detecting inside a face, but ommitted). Let's say (ex, ey, ew, eh) are 4 coordinates that need to be stored in an array for each iteration of this loop. The output for each iteration looks like this: [54, 46, 90, 103] But sometimes, it also looks like this: [[20 34 56 41], [34 56 78 89]] Sometimes the value of (ex, ey, ew, eh) can be upto 4 array values of in one array. How can we store these multidimensional outputs in a numpy array? It does not have a fixed size, sometimes, it is an array of 4 coordinates; sometimes it is an array of an array of many sets of 4 coordinates.
tagged with: multidimensional-array
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49417332
tagged with: opencv
has comment: http://stackoverflow.com/comment/85807576
score: 1
answer count: 1
upvote count: 1

http://stackoverflow.com/q/49438360
possible better answer: http://stackoverflow.com/a/49438628
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/49438628
has answer: http://stackoverflow.com/a/49438694
type: Question
has body: I feel like this should be really simple but I'm having a hard time with it. Suppose I have this: df1: ticker hhmm &lt;--- The hhmm value corresponds to the column in df2 ====== ==== AAPL 0931 IBM 0930 XRX 1559 df2: ticker 0930 0931 0932 ... 1559 &lt;&lt;---- 390 columns ====== ==== ==== ==== ... ==== AAPL 4.56 4.57 ... ... IBM 7.98 ... ... ... XRX 3.33 ... ... 3.78 The goal is to create a new column in df1 whose value is df2[df1['hhmm']]. For example: df1: ticker hhmm df2val ====== ==== ====== AAPL 0931 4.57 IBM 0930 7.98 XRX 1559 3.78 Both df's have 'ticker' as their index, so I could simply join them BUT assume that this uses too much memory (the dataframes I'm using are much larger than the examples shown here). I've tried apply and it's slooooow (15 minutes to run). What's the Pandas Way to do this? Thanks!
tagged with: dataframe
tagged with: python
has title: In Pandas how can I use the values in one table as an index to extract data from another table?
accepted answer: http://stackoverflow.com/a/49438694
has answer: http://stackoverflow.com/a/49438738
tagged with: pandas
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 3
downvote count: 0

http://stackoverflow.com/q/49283825
has comment: http://stackoverflow.com/comment/85576505
has body: I have exported a cookies.txt file from firefox using a cookie export addon. Im trying to use the cookie file with python requests but getting this... ValueError: Invalid header value My code: import requests cj = cookielib.MozillaCookieJar() cj.load('cookies.txt', ignore_discard=True) r = requests.get('blah.com', cookies=cj) What can I do?
tagged with: cookies
score: 1
has comment: http://stackoverflow.com/comment/85573845
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/49285901
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85574260
has title: Python requests invalid header value
tagged with: cookiejar
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85699655
type: AnswerComment
has text: this is for a txt file, i don't know much about csv, but i think you can use similar methods
comment on: http://stackoverflow.com/a/49349969
type: Comment
score: 0

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49396155
tags question: http://stackoverflow.com/q/49320747
tags question: http://stackoverflow.com/q/49314588
tags question: http://stackoverflow.com/q/49367546
tags question: http://stackoverflow.com/q/49438255
tag name: kivy-language
tags question: http://stackoverflow.com/q/49414737
tags question: http://stackoverflow.com/q/49421627
tags question: http://stackoverflow.com/q/49334295
tags question: http://stackoverflow.com/q/49403918
tags question: http://stackoverflow.com/q/49399678

http://stackoverflow.com/comment/85743924
type: AnswerComment
has text: Its very bad practice, especially in production.
comment on: http://stackoverflow.com/a/49371304
type: Comment
score: 0

http://stackoverflow.com/q/49307866
has comment: http://stackoverflow.com/comment/85621164
answer count: 1
downvote count: 0
tagged with: image-processing
has title: How to define a Gaussian voting for generalized hough transform within a range of displacement of a coordinate in accumulator?
has body: I am not professional programmer and taking baby steps in that. I have defined a Gaussian kernel which shows the weights for scoring with a window size of 5 and sigma=3 (i.e., 3 displacements) in python. [[0.00364954 0.01483356 0.02344521 0.01483356 0.00364954] [0.01483356 0.06029105 0.09529314 0.06029105 0.01483356] [0.02344521 0.09529314 0.15061577 0.09529314 0.02344521] [0.01483356 0.06029105 0.09529314 0.06029105 0.01483356] [0.00364954 0.01483356 0.02344521 0.01483356 0.00364954]] This is the plot of Gaussian: If c_i is the center cell of Gaussian window, the weights should be like the following: where delta_p show the displacement from the c_i, How can I find the neighbors and then add the Gaussian weights to those neighbors, in which their indices are ranging from -2 to 2 from left to right and from top to bottom? Indeed, I do not understand how to include this in accumulator increment?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85665895
tagged with: hough-transform
tagged with: python
tagged with: computer-vision
accepted answer: http://stackoverflow.com/a/49314607
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49314607
tagged with: python-2.7
score: 3
upvote count: 3

http://stackoverflow.com/a/49410899
has comment: http://stackoverflow.com/comment/85847873
type: Answer
has comment: http://stackoverflow.com/comment/86149341
has body: Check that app.yaml, cron.yaml and other app configs are valid and correctly formatted. Strip them to the bare minimum needed to test your application. 500 A server error has occurred on deployment is usually related to malformed configs. Also note that appcfg.py is being deprecated 'soon' and you should switch to gcloud app deploy.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49403669

http://stackoverflow.com/q/49373333
has comment: http://stackoverflow.com/comment/85747864
downvote count: 1
favorite count: 0
type: Question
has title: Python: Create an element inside an element
tagged with: indexing
accepted answer: http://stackoverflow.com/a/49373623
has comment: http://stackoverflow.com/comment/85748005
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/49373423
has answer: http://stackoverflow.com/a/49373623
has body: So for a school project I have to create some playing field and afterwards it has to be checked. My thought was to add a grid in python, just a simple list grid = ([[' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ']]) As you can see it's 6 elements, each containing 6 spaces. the grid.insert only works for adding elements but not for these 'element elements'. the idea is that when, if x == 25 and y == 25: then grid becomes: ([['1',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ']]) Is this even possible in python? Or should I look for a different way of solving this? I hope this is enough information, else I will glady supply you with more!
has comment: http://stackoverflow.com/comment/85747874
has answer: http://stackoverflow.com/a/49373423
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85747860
answer count: 3
has comment: http://stackoverflow.com/comment/85747979
upvote count: 0
has answer: http://stackoverflow.com/a/49373416

http://stackoverflow.com/comment/85882923
type: AnswerComment
has text: Thanks for the answers and comments. I accept this as answer because this is approximately 8 times faster than Wen's crosstab and 4 times faster than piRSquared's method.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49434077

http://stackoverflow.com/q/49355939
has title: Predict real value of new data points
has comment: http://stackoverflow.com/comment/85712184
has comment: http://stackoverflow.com/comment/85712769
has comment: http://stackoverflow.com/comment/85713430
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/49357670
has comment: http://stackoverflow.com/comment/85713122
tagged with: machine-learning
upvote count: 1
tagged with: python
has body: Suppose I have data points: x = [(1, 2), (1, 5), (1, 6), (2, 4), (2, 5), (2, 7), (3, 1), (3, 5), (3, 6)] y = [2.3,5.6,9.0,8.6,4.2,13.5,11.0,1.3,5.0] Now I want to predict the value of y for some new pairs, say (2,3),(3,4) Suggest me a python code for the same. I have tried with interpolation but couldn't get the result, I think some machine learning would do it, but I am really new in machine learning. Suggest me a python code for the same. Actual data I am working on is similar to these dummy data.Want to predict values of missing point in the given image
downvote count: 3
has answer: http://stackoverflow.com/a/49357945
favorite count: 0
type: Question
tagged with: interpolation
answer count: 2

http://stackoverflow.com/q/49373453
possible better answer: http://stackoverflow.com/a/49373796
has title: How do I map one column to multiple columns in pyspark?
linked to: http://stackoverflow.com/q/46835882
accepted answer: http://stackoverflow.com/a/49373575
has answer: http://stackoverflow.com/a/49373796
has answer: http://stackoverflow.com/a/49373575
tagged with: apache-spark
type: AnsweredQuestion
upvote count: 3
duplicate of: http://stackoverflow.com/q/46835882
has comment: http://stackoverflow.com/comment/85748829
downvote count: 1
favorite count: 0
tagged with: apache-spark-sql
type: Question
score: 2
answer count: 2
tagged with: pyspark
has body: I have a pyspark data frame that looks like this: df.show() +---+ |dim| +---+ |1x1| |0x0| |1x0| +---+ The data type in dim is str. Now I want to separate dim into 2 column, and have something like this: df.show() +---+----+----+ |dim|dim1|dim2| +---+----+----+ |1x1| 1| 1| |0x0| 0| 0| |1x0| 1| 0| +---+----+----+ I know that if I were to operate on a single string I'd just use the split() method in python: "1x1".split("x"), but how do I simultaneously create multiple columns as a result of one column mapped through a split function?
tagged with: python
has comment: http://stackoverflow.com/comment/85748434

http://stackoverflow.com/a/51837897
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49340468
has body: just some hints to attempt: Ensure that your "Image01.jpg" file is open and use the full path. image_path = "/full/path/to/Image01.jpg" image_file = Image.open( open(image_path, 'rb')) # side-note: generally it is better to use the open with syntax, see link below # https://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement To ensure that you are actually on the pdf page that you expect to be, try this. This code will insert the image only on the first page for page in doc: page.InsertImage(rect, filename=image_path) break # Without this, the image will appear on each page of your pdf
upvote count: 2

http://stackoverflow.com/comment/85704303
comment on: http://stackoverflow.com/a/49351961
score: 0
type: AnswerComment
has text: The first one looks nice. I'm not sure if `'C'` and `'M'` are always present in `L`.
type: Comment

http://stackoverflow.com/q/49378303
has body: I am trying to run a .py file from another python code using the following sequence. from tkinter import * import os import sys def open_SS(): print('processing') os.system('cd /home/pi/Desktop/Backup') os.system('python p.py') def close_window(): master.destroy() master = Tk() master.minsize(width=500, height=300) Button(master, text='Exit', command=close_window).grid(row=12, column=6, sticky=W, pady=4) Button(master, text='SS', command=open_SS).grid(row=12, column=8, sticky=W, pady=4) mainloop( ) The Exit button does the command, but the 'SS' button does not, the word 'processing' does get printed, just the running of the p.py file. I tried running those two os.system commands on a command terminal and it works fine. p.py is supposed to input GPIO signals to a Raspberry Pi.
tagged with: tkinter
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85757890
has comment: http://stackoverflow.com/comment/85807951
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85758428
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/18884782
tagged with: python
has title: tkinter button unable to open different python code
has answer: http://stackoverflow.com/a/49407485

http://stackoverflow.com/a/49392924
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49392838
has body: You are missing a trailing ')' on this line: lineColor = (random.radint (0, 255), random.radint (0, 255), random.radint (0, 255)
answers question: http://stackoverflow.com/q/49392838
type: AcceptedAnswer

http://stackoverflow.com/a/49289628
upvote count: 1
answers question: http://stackoverflow.com/q/49286236
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
has body: Is this what you need -- a method parameterized for the given input? def testPoint(x, y, move_x, move_y): p = Point(x, y) # create a point instance p.move(move_x, move_y) # Use method move, move the point object by x=2 and y=2 assert p.x == x + move_x and \ p.y == y + move_y You can then execute this for a variety of starting points and movement vectors.
accepted answer of: http://stackoverflow.com/q/49286236

http://stackoverflow.com/comment/85701334
type: AnswerComment
score: 0
has text: Apart from hard coding, you could use `.metrics(linespace)` on the Font object to get the height in pixel of each row of text then do the necessary arithmetic against the screen height to approximate the number of rows you may need for `self.internal_windows`. See this [link](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/fonts.html) for explanation of Font object. I suspect you will then also have to factor in borderwidth, horizontal scrollbar width, the window title bar....
comment on: http://stackoverflow.com/a/49338802
type: Comment

http://stackoverflow.com/a/49288457
has body: While waiting for some help showing how to do this in a 'Pythonic way', I came up with an easy brute force method: With the string s set to the 2nd option, with the given &lt;thead&gt; and &lt;tbody&gt; labels, apply the following code: s = ''.join(s.split('&lt;tbody&gt;')) s = ''.join(s.split('&lt;/tbody&gt;')) s = ''.join(s.split('&lt;thead&gt;')) s = ''.join(s.split('&lt;/thead&gt;'))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49286753

performance
tags question: http://stackoverflow.com/q/49284383
tags question: http://stackoverflow.com/q/49403521
tags question: http://stackoverflow.com/q/49377878
tags question: http://stackoverflow.com/q/49367525
tags question: http://stackoverflow.com/q/49335507
tags question: http://stackoverflow.com/q/49344116
tags question: http://stackoverflow.com/q/49371629
tags question: http://stackoverflow.com/q/49311922
tags question: http://stackoverflow.com/q/49379847
tags question: http://stackoverflow.com/q/49314543
tags question: http://stackoverflow.com/q/49306324
tags question: http://stackoverflow.com/q/49410023
tags question: http://stackoverflow.com/q/49420272
tag name: performance
tags question: http://stackoverflow.com/q/49396293
tags question: http://stackoverflow.com/q/49297938
tags question: http://stackoverflow.com/q/49380594
tags question: http://stackoverflow.com/q/49425997
tags question: http://stackoverflow.com/q/49289457
tags question: http://stackoverflow.com/q/49394773
type: Tag
tags question: http://stackoverflow.com/q/49302884
tags question: http://stackoverflow.com/q/49282205
tags question: http://stackoverflow.com/q/49418144
tags question: http://stackoverflow.com/q/49280574
tags question: http://stackoverflow.com/q/49290059
tags question: http://stackoverflow.com/q/49350385

http://stackoverflow.com/q/49331717
has title: Classes and self in python: instance and class variables
has comment: http://stackoverflow.com/comment/85665502
has body: I'm a novice Python programmer utterly confused by OOP and the need for self in classes. I've read the many SO posts, blogs* etc that attempt to demystify it, but could use some help on this particular scenario. I am basing the below scenarios off the Python2 tutorial on Class and Instance Variables. I'll lead with my examples, followed by explicit questions beneath. First, I'll directly set tricks, and then use the add_trick method: class Dog: tricks = [] def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) def print_self_tricks(self): print(self.tricks) a = Dog('spencer') b = Dog('rex') a.tricks = ['foo'] # How is this even possible? Where did I define self.tricks? a.print_self_tricks() ['foo'] # Ok, the below results make sense b.print_self_tricks() [] a.tricks ['foo'] b.tricks [] a.add_trick('jump') a.print_self_tricks() ['foo', 'jump'] b.print_self_tricks() [] # Great, as expected a.tricks ['foo', 'jump'] b.tricks [] # Great, as expected Now, the exact same setup, but executed in a different order: add_trick before direct setting of trick. class Dog: tricks = [] def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) def print_self_tricks(self): print(self.tricks) a = Dog('spencer') b = Dog('rex') a.add_trick('jump') a.print_self_tricks() ['jump'] b.print_self_tricks() ['jump'] # Welp, that's not expected. a.tricks ['jump'] b.tricks ['jump'] # Welp, that's not expected. a.tricks = ['foo'] a.print_self_tricks() ['foo'] b.print_self_tricks() ['jump'] # Great, but inconsistent with the behavior above resulting from a.add_trick a.tricks ['foo'] b.tricks ['jump'] # Great, but inconsistent with the behavior above resulting from a.add_trick Why does self.tricks exist? It was never defined in __init__ (e.g. self.tricks = tricks). I wouldn't expect it to be possible to set self.tricks since it wasn't previously defined. Why does my approach not result in a different answer? That is, why…
linked to: http://stackoverflow.com/q/2709821
tagged with: python
accepted answer: http://stackoverflow.com/a/49331783
tagged with: class
has answer: http://stackoverflow.com/a/49331783
type: AnsweredQuestion
score: 0
tagged with: oop
tagged with: instance
answer count: 1
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85665493
has comment: http://stackoverflow.com/comment/85665512

http://stackoverflow.com/comment/85680477
has text: i get a 404, will add my full file now
comment on: http://stackoverflow.com/a/49338594
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49371365
type: AnsweredQuestion
has title: Combining multiple TraitsUi Views containing matplotlib figures
tagged with: traitsui
downvote count: 0
score: 1
upvote count: 1
tagged with: matplotlib
answer count: 1
linked to: http://stackoverflow.com/q/24071067
favorite count: 0
type: Question
has body: I am trying to build an interactive image viewer using TraitsUI. This can be done using the implementation shared by Pierre Haessig. Next, I want to present many of these Views simultaneously. A similar approach was outlined here. However, I cannot get this approach to work for my problem at hand. building such a container throws an AttributeError: 'Test' object has no attribute 'dpi'. I suppose I am misunderstanding how editors work in this context, but I cannot figure out how to make it work. Runnable example code: # By Pierre Haessig, https://gist.github.com/pierre-haessig/9838326 from pyface.qt import QtGui, QtCore import matplotlib # We want matplotlib to use a QT backend matplotlib.use('Qt4Agg') from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from traits.api import Any, Instance from traitsui.qt4.editor import Editor from traitsui.qt4.basic_editor_factory import BasicEditorFactory class _MPLFigureEditor(Editor): scrollable = True def init(self, parent): self.control = self._create_canvas(parent) self.set_tooltip() def update_editor(self): pass def _create_canvas(self, parent): """ Create the MPL canvas. """ # matplotlib commands to create a canvas mpl_canvas = FigureCanvas(self.value) return mpl_canvas class MPLFigureEditor(BasicEditorFactory): klass = _MPLFigureEditor if __name__ == "__main__": # Create a window to demo the editor from traits.api import HasTraits, Int, Float, on_trait_change from traitsui.api import View, Item from numpy import sin, cos, linspace, pi class Test(HasTraits): figure = Instance(Figure, ()) n = Int(11) a = Float(0.5) view = View(Item('figure', editor=MPLFigureEditor(), show_label=False), Item('n'), Item('a'), width=400, height=300, resizable=True) def __init__(self): super(Test, self).__init__() axes = self.figure.add_subplot(111) self._t = linspace(0, 2*pi, 200) self.plot() @on_trait_change('n,a') def plot(self): t = self._t a = self.a n = self.n axes = self.fi…
tagged with: python
has answer: http://stackoverflow.com/a/51645174
accepted answer: http://stackoverflow.com/a/51645174

http://stackoverflow.com/comment/85744432
has text: Possible duplicate of [How could I use Batch Normalization in TensorFlow?](https://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49371671
score: 2

http://stackoverflow.com/comment/87371329
score: 0
comment on: http://stackoverflow.com/a/49466811
type: Comment
type: AnswerComment
has text: voglster is correct, this also fixed it for me. Just as an FYI the current latest version that works is 2.1.4

http://stackoverflow.com/q/49393518
tagged with: python
has body: I am using a jupyter lab notebook and trying to modify code, reload it within the jupyter notebook and use the modified code without reloading the kernel. I am using python 3.5.5 and am running code like this: (in file test.py) def myTest(): print('hello') (in jupyter) from test import myTest import importlib importlib.reload(test) myTest() When I run the code in my jupyter lab notebook I get a NameError that name 'test' is not defined. From searching on stackoverflow the only references I find to this error is problems using older version of python. But the way I am using importlib.reload() seems to be correct.
accepted answer: http://stackoverflow.com/a/49393667
has answer: http://stackoverflow.com/a/49393667
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85788850
has comment: http://stackoverflow.com/comment/85788747
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85788723
tagged with: jupyter-notebook
favorite count: 0
type: Question
tagged with: jupyter-lab
answer count: 1
has title: Reloading python function

http://stackoverflow.com/comment/85811589
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49400385
score: 0
has text: @mootmoot, How to access another region?

http://stackoverflow.com/comment/85664169
comment on: http://stackoverflow.com/a/49331077
score: 0
type: AnswerComment
has text: This is a JSON string. Regex is not the appropriate tool.
type: Comment

http://stackoverflow.com/comment/111821978
has text: I had this error with this: `pd.DatetimeIndex(['1462352019029395103', '1462352019029395104'])`. It turned out that I had to use int64 instead of strings as timestamps. This is obvious, it just gave me the idea that you might also get this error simply because int64 is expected and you fail to to convert your input from string to int64 for whatever reason.
comment on: http://stackoverflow.com/q/49328235
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/85707849
comment on: http://stackoverflow.com/q/49353773
has text: You could try calling it from console in pycharm (like `python[3] project.py [-args]`)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49319900
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49793877
accepted answer: http://stackoverflow.com/a/49793877
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: I have a problem for getting all events for all tenants/projects in Ceilometer. When I get the event list I always get only the list of events related to project that my user assigned. The user is admin in openstack. Explaining in more detail: Here is my sample code: def sync_resources(): logger.info("Executing sync_resources") sync_tenants() tenants = Tenant.objects.all() managers = Manager.objects.filter(is_active=True) for manager in managers: services = manager.services.all() regions = manager.region_set.all() for region in regions: ceilometer_driver = CeilometerDriver(region_name=region.name, **manager.ceilometer_params) if ceilometer_driver.is_authenticated: for tenant in tenants: queries = [ceilometer_driver.make_query("project_id", ceilometer_driver.EQUAL, tenant.tenant_id)] resource_list = ceilometer_driver.get_event_list(query=queries) The sample function uses a driver that I have written. And the driver first authenticates with username,password and project_id. After that it should get the list of events based on prjojects. The problem here is that even the user is admin I can only get the events that the admin is assigned as user. For example instead of getting the events when I try to get the resource list I get all. However when I try events I get only events of projects for the user. # returns all the resources for all tenants/projects resource_list = ceilometer_driver.get_resource_list() # returns only the events for user projects resource_list = ceilometer_driver.get_event_list() When I try it with REST API: This gets again all resources for all projects: http://192.168.101.11:8777/v2/resources This one gets only projects events relevant to user http://192.168.101.11:8777/v2/events This one returns empty if the admin user is not assigned to project: http://192.168.101.11:8777/v2/events?q.field=project_id&amp;q.value=d81584b38e56444cad4823b2bd2aab34 From terminal: This gets again all resources for all projects: $ ceilometer resource-list This one get…
tagged with: django
tagged with: python
tagged with: openstack
has title: Django Ceilometer get events for all projects
tagged with: ceilometer

http://stackoverflow.com/q/49398198
has body: As I understand, one cannot use pip to install/upgrade pywin32, though pip install -U pypiwin32 is a workaround. pywin32 is now hosted on GitHub. I know very little of git but know that it works with binary files. Is there a way to programmatically upgrade the pywin32 binary? That is, say pywin32 v221 is installed with Python v.3.6 (64bit), the program should check against the latest (v223) on GitHub and download the pywin32-223.win-amd64-py3.6.exe and install it. So far, I can only think of a web-scraping-like script that compares the installed version with the latest version on the web and act accordingly. I wonder whether there's a simple solution.
linked to: http://stackoverflow.com/q/49248769
tagged with: pywin32
tagged with: python
has title: How to update pywin32 automatically?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23864234
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/49499867
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/57882963
tagged with: pip
tagged with: github
linked to: http://stackoverflow.com/q/20101834
has answer: http://stackoverflow.com/a/49398957
possible better answer: http://stackoverflow.com/a/49398957
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49499867

http://stackoverflow.com/comment/85715142
has text: sorry about that，I type all these by my phone..
comment on: http://stackoverflow.com/q/49357229
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85645342
type: Comment
type: QuestionComment
score: 0
has text: adb is not what im looking for. I'm looking for programming wise advise
comment on: http://stackoverflow.com/q/49313291

http://stackoverflow.com/a/49388913
answers question: http://stackoverflow.com/q/49385148
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49385148
has body: Problem You are not able to reach screen0 because it is not in your screenList. The variable, testScreen defined in method screenSelector is a local variable, which is not the same class variable, testScreen defined in class selectionScreen. Undefined variable, return testscreen due to typo error. At Screen0, the code, on_release: root.manager.current = str(root.testScreen) will cause an AttributeError: 'Screen0' object has no attribute 'testScreen' Solution In order to reach Screen0, you have to do the following: Python Script Add Screen0 into the variable, screenList Replace random.randint(0, 1) with random.randint(0, 2) Replace testScreen with self.testScreen in method screenSelector kv file Define an id, e.g. id: selection_screen Reference it, e.g. root.manager.ids.selection_screen.testScreen Add on_press call to screenSelector in the other screens, e.g. on_press: root.manager.ids.selection_screen.screenSelector() Example main.py from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager from kivy.properties import StringProperty import random class ScreenManager(ScreenManager): pass class SelectionScreen(Screen): testScreen = StringProperty('Screen1') def screenSelector(self): screenList = ['Screen0', 'Screen1', 'Screen2'] testNumber = random.randint(0, 2) self.testScreen = screenList[testNumber] return self.testScreen class Screen0(Screen): pass class Screen1(Screen): pass class Screen2(Screen): pass class Test(App): def build(self): return ScreenManager() if __name__ == "__main__": Test().run() test.kv #:kivy 1.10.0 &lt;ScreenManager&gt;: SelectionScreen: id: selection_screen name: 'SelectionScreen' Screen0: name: 'Screen0' Screen1: name: 'Screen1' Screen2: name: 'Screen2' &lt;SelectionScreen&gt;: BoxLayout: Button: text: "Click when ready" size_hint: .6, .5 font_size: 10 on_press: root.screenSelector() on_release: root.manager.current = str(root.manager.ids.selection_screen.testScreen) &lt;Screen0&gt;: BoxLayout: orientation: 'vertical…
type: AcceptedAnswer

http://stackoverflow.com/comment/85842261
type: QuestionComment
comment on: http://stackoverflow.com/q/49420039
has text: There are various ways you can do it. One way is ,You can store number as a text (so 1000 places long number = 1000 char size word) and then convert back to int when needed.
score: 1
type: Comment

http://stackoverflow.com/comment/85758708
type: QuestionComment
comment on: http://stackoverflow.com/q/49379088
has text: Why don't you use pandas?
score: 0
type: Comment

http://stackoverflow.com/a/49328354
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/85658670
has body: Python has a built in zip library mydir = 'mydir' myzipfile = 'fancy.zip' from zipfile import ZipFile import os with ZipFile(myzipfile, 'w') as zipout: for dirpath, dirnames, filenames in os.walk(mydir): for filename in filenames: with open(os.path.join(dirpath[len(mydir)+1:], filename), 'r') as fin: with zipout.open(os.path.join(dirpath, filename), 'w') as fout: fout.write(fin.read()) This will take all the files from mydir and copy them into fancy.zip It will also recurse into subdirectories of mydir and copy those files as well.
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/85658592
answers question: http://stackoverflow.com/q/49328037

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/49416636
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/49328051

http://stackoverflow.com/comment/85803416
comment on: http://stackoverflow.com/a/49370013
has text: The type is unicode according to my CloudWatch logs. The log also displays the error `Not a JPEG file: starts with 0xef 0xbf` which I assume comes from this: `image_jpg = tf.image.decode_jpeg(image)`
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/106612384
comment on: http://stackoverflow.com/q/49371712
score: 1
type: Comment
type: QuestionComment
has text: Does this answer your question? [How do I compare the contents of two Google Protocol Buffer messages for equality?](https://stackoverflow.com/questions/24296221/how-do-i-compare-the-contents-of-two-google-protocol-buffer-messages-for-equalit)

http://stackoverflow.com/q/49309668
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/25328818
has comment: http://stackoverflow.com/comment/85622670
upvote count: 0
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/49313038
has body: I'm new to the site and the website wouldn't let me upload my question because i didnt "indent my code" which I have. I spent 1.5h trying to type my question, so i decided to use screen shot. I need help with Selenium Explicit Waits. [EDIT]:I realised I was using python idle 3.6 instead of idle 2.7. SMH sorry for wasting everyone's time. this is why it wouldn't run. Links to websites: https://www.hongkiat.com/blog/automate-create-login-bot-python-selenium/ http://selenium-python.readthedocs.io/waits.html Please check out the question. Thank you.
has comment: http://stackoverflow.com/comment/85625412
has answer: http://stackoverflow.com/a/49313038
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: Selenium explicit waits (importing folder)
has comment: http://stackoverflow.com/comment/85623755
linked to: http://stackoverflow.com/q/48267633
tagged with: python-module
has comment: http://stackoverflow.com/comment/85621412
answer count: 1
tagged with: selenium
downvote count: 3

http://stackoverflow.com/q/49327987
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading
tagged with: serial-port
has title: Serial Communication breaks down when threading
has body: I am using a USB microwave source, which communicates via a virtual COM port. Communication is done via python. Everything works fine, as long as I am executing the code blockingly. However, as soon as any communication is done in a thread I get a SerialException: Attempting to use a port that is not open. Is there an obvious reason, why this is happening? Nothing else, at least originating from my software, is trying to communicate with the port during that time. The highest level script: from serial import SerialException import deer import windfreak_usb try: deer.mw_targets = windfreak_usb.WindfreakSynthesizer() except SerialException: deer.mw_targets.port.close() deer.mw_targets = windfreak_usb.WindfreakSynthesizer() deer_mes = deer.DeerMeasurement(f_start=0.9e9, f_end=1.2e9, df=3e6, f_nv=1.704e9, seq=["[(['mw'],28),([],tau),(['mw', 'mwy'],56),([],tau),(['mw'],28),([],100)]", "[(['mw'],28),([],tau),(['mw', 'mwy'],56),([],tau),(['mw'],84),([],100)]"], power_nv=10, power_targets=3, tau=700 ) deer_mes.run(10e6) # &lt;- this works perfectly, as it is the blocking version # deer_mes.start(10e6) # &lt;- raises the SerialException at the line indicated below deer.mw_targets.port.close() A reduced form of the microwave source (windfreak_usb.py): import serial import synthesizer class WindfreakSynthesizer(synthesizer.Synthesizer): def __init__(self): synthesizer.Synthesizer.__init__(self) self.port = serial.Serial( port='COM14', baudrate=9600, timeout=10 ) self.off() def __del__(self): self.port.close() def off(self): self.port.write('o0') def power(self, p): p = int(p) self.port.write('a{}'.format(p)) A reduced form of the measurement class (deer.py): import threading import time import numpy import os from PyQt4 import QtCore from PyQt4.QtCore import QObject import matplotlib.pyplot as plt import hardware import matpickle import pulsed import pulser import savepath import synthesizer if 'pg' not in globals(): pg = pulser.Pulser() if 'mw_targets' not in globals(): mw_ta…
tagged with: python
has comment: http://stackoverflow.com/comment/85659177
score: 0
has comment: http://stackoverflow.com/comment/85781864
has comment: http://stackoverflow.com/comment/85781919
has comment: http://stackoverflow.com/comment/85658285
type: Question
tagged with: virtual-serial-port
answer count: 0

http://stackoverflow.com/comment/85708214
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49353831
type: Comment
has text: You're welcome. You may not need to adjust anything. If `RegisterForm` is indeed a `ModelForm` with model `coach`, this code should just work. If it's not, you need to get the right object to pass as the instance to the form.

http://stackoverflow.com/comment/85644754
score: 0
type: Comment
type: QuestionComment
has text: If I should apply different techniques to save a plot of delaunay triangles, I'm all ears!! I'm just very confused right now. Thank you!
comment on: http://stackoverflow.com/q/49321813

http://stackoverflow.com/comment/85825784
comment on: http://stackoverflow.com/q/49411783
score: 0
has text: with ascending order, then the timeseries will not be ordered...?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/132499593
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/68581302
has text: I also have a question about y and y-test that you mentioned in the post. If I understand correctly, you mean for calculating r-squre we should just use y_test. But for calculating the Adj_r2, we should use the whole y and X for len(y), X.shape[1], I mean before split the data. Is that right? or you mean: Adj_r2 = 1 - (1-r2_score(y_test, y_pred)) * (len(y_train)-1)/(len(y_train)-X_train.shape[1]-1)

http://stackoverflow.com/comment/85603703
type: QuestionComment
type: Comment
has text: where do you need the csrf_token for?
comment on: http://stackoverflow.com/q/49298250
score: 1

http://stackoverflow.com/q/49408627
has comment: http://stackoverflow.com/comment/85818615
has comment: http://stackoverflow.com/comment/85818728
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85818568
has comment: http://stackoverflow.com/comment/85818656
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85818541
has comment: http://stackoverflow.com/comment/85818796
has answer: http://stackoverflow.com/a/49408793
accepted answer: http://stackoverflow.com/a/49408793
answer count: 1
downvote count: 1
has title: How to calculate the average from a text file for every year in python?
score: -1
has body: So this is my text file and i want to calculate the average for every year: 1969 324.000 1970 330.190 1970 326.720 1970 327.130 1971 326.970 1971 331.200 1971 329.430 1971 335.770 1971 337.600 And this is my Code that i got from another question but it keeps erroring: In[2]: result = {} with open('filename.txt', 'r') as f: for line in f: year, num = line.split() year = int(year) num = float(num) try: result[year].append(num) except KeyError: result[year] = [num] In[3]: for k, v in sorted(result.items()): print('Year: {}\tAverage: {:.2f}'.format(k, sum(v) / len(v))) My error: Traceback (most recent call last): File "C:\Users\fra02.sek\Desktop\average.py", line 4, in &lt;module&gt; year, num = line.split() ValueError: too many values to unpack (expected 2)
has comment: http://stackoverflow.com/comment/85818491
type: Question
upvote count: 0

http://stackoverflow.com/comment/85686045
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49342892
type: QuestionComment
has text: Do you have errors? What do you get?

http://stackoverflow.com/q/49355749
has body: The following code raises TypeError: input expected at most 1 arguments but got 3. I am unsure how to fix this. def leg_count(w): x = input("How many legs does a", w, "have? ") print("A", w, "has", x, "legs") leg_count("crocodile")
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49355959
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49355768
has answer: http://stackoverflow.com/a/49355959
tagged with: python
linked to: http://stackoverflow.com/q/14856953
accepted answer: http://stackoverflow.com/a/49355768
score: -1
answer count: 2
has title: How to fix TypeError: input expected at most 1 arguments but got 3
upvote count: 0
duplicate of: http://stackoverflow.com/q/14856953
has comment: http://stackoverflow.com/comment/85711712

http://stackoverflow.com/q/49306075
tagged with: machine-learning
upvote count: 1
answer count: 1
downvote count: 1
has body: I have implemented a pretty simple Deep Neural Network to perform multi-label classification. The overview of the model is (bias omitted for the sake of simple visualization): That is, a 3-layer deep neural network with ReLU units and Sigmoid as output unit. The loss function is Sigmoid Cross Entropy and the used optimizer is Adam. When I train this NN without Dropout I get the following results: #Placeholders x = tf.placeholder(tf.float32,[None,num_features],name='x') y = tf.placeholder(tf.float32,[None,num_classes],name='y') keep_prob = tf.placeholder(tf.float32,name='keep_prob') #Layer1 WRelu1 = tf.Variable(tf.truncated_normal([num_features,num_features],stddev=1.0),dtype=tf.float32,name='wrelu1') bRelu1 = tf.Variable(tf.zeros([num_features]),dtype=tf.float32,name='brelu1') layer1 = tf.add(tf.matmul(x,WRelu1),bRelu1,name='layer1') relu1 = tf.nn.relu(layer1,name='relu1') #Layer2 WRelu2 = tf.Variable(tf.truncated_normal([num_features,num_features],stddev=1.0),dtype=tf.float32,name='wrelu2') bRelu2 = tf.Variable(tf.zeros([num_features]),dtype=tf.float32,name='brelu2') layer2 = tf.add(tf.matmul(relu1,WRelu2),bRelu2,name='layer2') relu2 = tf.nn.relu(layer2,name='relu2') #Layer3 WRelu3 = tf.Variable(tf.truncated_normal([num_features,num_features],stddev=1.0),dtype=tf.float32,name='wrelu3') bRelu3 = tf.Variable(tf.zeros([num_features]),dtype=tf.float32,name='brelu3') layer3 = tf.add(tf.matmul(relu2,WRelu3),bRelu3,name='layer3') relu3 = tf.nn.relu(tf.matmul(relu2,WRelu3) + bRelu3,name='relu3') #Out layer Wout = tf.Variable(tf.truncated_normal([num_features,num_classes],stddev=1.0),dtype=tf.float32,name='wout') bout = tf.Variable(tf.zeros([num_classes]),dtype=tf.float32,name='bout') logits = tf.add(tf.matmul(relu3,Wout),bout,name='logits') #Predictions logits_sigmoid = tf.nn.sigmoid(logits,name='logits_sigmoid') #Cost &amp; Optimizer cost = tf.losses.sigmoid_cross_entropy(y,logits) optimizer = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cost) Evaluation results on test…
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/85616205
type: Question
has comment: http://stackoverflow.com/comment/85616408
tagged with: python
has comment: http://stackoverflow.com/comment/85686885
accepted answer: http://stackoverflow.com/a/49465302
tagged with: deep-learning
type: AnsweredQuestion
score: 0
has title: Why DNN with Dropout always predict one?
has answer: http://stackoverflow.com/a/49465302
tagged with: neural-network

http://stackoverflow.com/q/49301983
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85711698
has comment: http://stackoverflow.com/comment/85689378
type: Question
has body: I was wondering how I can slice this plot up into smaller strips. Plot of galaxies positions I need to make it into slices of a height of 10 and the width needs to remain the same. This is the code for the plot: from matplotlib import pyplot as plt import numpy as np plt.figure(figsize=(13,13)) #Don't forget to start from 0 not 1 x=[] y=[] z=[] filename=(r"C:\Users\Melis\OneDrive\Documents\minnimill6.txt") f1=open(filename) while 1: rawline = f1.readline() lines = rawline.strip() if lines == '': break if lines[0] != '#' and lines[0] != 'g': line = np.array(list(map(float, lines.split(',')))) #print (line) x.append(line[14]) y.append(line[15]) z.append(line[16]) f1.close() plt.scatter([x],[y]) plt.draw()
type: UnansweredQuestion
tagged with: arrays
tagged with: matplotlib
has title: how to slice a 2D plot
has comment: http://stackoverflow.com/comment/85711830
tagged with: python
has comment: http://stackoverflow.com/comment/85711732

http://stackoverflow.com/a/49320811
has body: Unfortunately "S" is predefined in sympy and is therefore interpreted by sympify as sympy.core.singleton.SingletonRegistry, see the documentation: The registry for the singleton classes (accessible as S). This is a bit more obvious when you try sympify on a simple expression, e.g. &gt;&gt; sp.sympify('S + A') TypeError: unsupported operand type(s) for +: 'SingletonRegistry' and 'Symbol' You can avoid this problem by replacing "S" with any other letter, e.g a lowercase "s". If you want to keep the letter "S", you can also add it to your locals using the symbol you defined previously: X = sp.sympify("(funcmux(S) - D) * X", locals={"funcmux": funcmux, "S": S})
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49320273
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49320273
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85689578
score: 0
comment on: http://stackoverflow.com/q/49344715
type: QuestionComment
has text: I think you would have written the method in the same time you posted the question. If you can not find it, write it. Simple as that.
type: Comment

http://stackoverflow.com/comment/85881085
type: AnswerComment
has text: @TheWhiteWolf Got it. Thank you for clearing that up for me.
type: Comment
comment on: http://stackoverflow.com/a/49405676
score: 0

http://stackoverflow.com/comment/85867627
has text: Think of compression as just an *encoding* that happens to be smaller than the original. The encoding includes the encoded data as well as some metadata needed to reconstruct the original (good compression schemes are adaptive; they are not independent of the original data). If the metadata is larger than the difference in size between the original and the encoded data, there is no net *compression*. That metadata has a fixed size (or at least, a fixed minimum size), so you won't see any benefit until you start compressing larger pieces of data.
comment on: http://stackoverflow.com/q/49432661
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85615055
type: AnswerComment
score: 0
has text: It couldn't see anything wrong with it. You assign to a set correctly. When I select option 8, it correctly shows the list without duplicates.
type: Comment
comment on: http://stackoverflow.com/a/49306116

http://stackoverflow.com/comment/85881270
has text: thing is also request.GET is empty so the data is not even in GET
comment on: http://stackoverflow.com/q/49439451
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85848581
has text: Then what you should be using is either a clustering algorithm or Fisher's LDA (Linear Discriminant Analysis) instead of neural networks.
comment on: http://stackoverflow.com/q/49416912
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49375502
has comment: http://stackoverflow.com/comment/85763101
accepted answer: http://stackoverflow.com/a/49385249
has comment: http://stackoverflow.com/comment/85764023
tagged with: aplpy
has answer: http://stackoverflow.com/a/49385249
downvote count: 0
has comment: http://stackoverflow.com/comment/85763998
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I am trying to open a full-color image from a '.fits' file. But, when comparing it to the corresponding '.gif' image, there appears to be an error regarding its color and size. How can I view the real-color image in its proper dimensions? As an example, one can select the '.fits' file and corresponding '.gif' file located at the top of this webpage. My example code, which uses the APLPY module, is below. def from_fits_to_image(color_scheme, rloc, rname='synop_Ml_0.2104', rext='.fits', cmap=None): """ color_scheme : 'rgb', 'grayscale', or 'false color'; color scheme of image to be shown rloc : type &lt;str&gt;; location of file to be read rname : type &lt;str&gt;; name of file to be read rext : type &lt;str&gt;; extension of file to be read cmap : None or type &lt;str&gt;; colormap """ rpath = rloc + rname + rext if color_scheme == 'rgb': pic = aplpy.FITSFigure(rpath) # pic.show_rgb(alt_filename) # what filename is supposed to go here? else: pic = aplpy.FITSFigure(rpath) if color_scheme == 'grayscale': pic.show_grayscale() elif color_scheme == 'false color': if cmap is None: pic.show_colorscale() else: pic.show_colorscale(cmap=cmap) # plt.savefig(...) plt.show() So long as one provides the proper rloc (the location of the downloaded '.fits' file) and color_scheme, the above code will run. Calling the function below will show an empty plot of the proper dimensions. To make it non-empty, I must supply another existing filename, though I am unclear on what exactly that should be. from_fits_to_image(color_scheme='rgb', rloc=rloc) Each of the function calls below reveal a plot that has been resized to small. While color_scheme='grayscale' seems to colorize the plot properly, the other methods do not properly colorize the image. from_fits_to_image('grayscale', rloc=rloc) from_fits_to_image('false color', rloc=rloc) from_fits_to_image('false color', rloc=rloc, cmap='plasma') For comparison, the '.gif' image is below. Ideally, the output will look exactly like the image belo…
tagged with: fits
has title: How to view this .fits image without resizing and without modifying colors?
tagged with: python-imaging-library
score: 1
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85762886
tagged with: python-3.x

http://stackoverflow.com/comment/115757105
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49356428
type: Comment
has text: @Raghuveer. Better word should be "expected" instead of "desired". I am sorry but I dont have any resources. Maybe you can look into the linked documentation for PCA above and go through the research papers linked there to get details.

http://stackoverflow.com/a/52106361
has comment: http://stackoverflow.com/comment/129072237
has body: Another option is to use TensorFlow which comes with the ability to do a streaming read from Google Cloud Storage: from tensorflow.python.lib.io import file_io with file_io.FileIO('gs://bucket/file.csv', 'r') as f: df = pd.read_csv(f) Using tensorflow also gives you a convenient way to handle wildcards in the filename. For example: Reading wildcard CSV into Pandas Here is code that will read all CSVs that match a specific pattern (e.g: gs://bucket/some/dir/train-*) into a Pandas dataframe: import tensorflow as tf from tensorflow.python.lib.io import file_io import pandas as pd def read_csv_file(filename): with file_io.FileIO(filename, 'r') as f: df = pd.read_csv(f, header=None, names=['col1', 'col2']) return df def read_csv_files(filename_pattern): filenames = tf.io.gfile.Glob(filename_pattern) dataframes = [read_csv_file(filename) for filename in filenames] return pd.concat(dataframes) usage DATADIR='gs://my-bucket/some/dir' traindf = read_csv_files(os.path.join(DATADIR, 'train-*')) evaldf = read_csv_files(os.path.join(DATADIR, 'eval-*'))
type: Answer
upvote count: 26
answers question: http://stackoverflow.com/q/49357352
score: 26
downvote count: 0
has comment: http://stackoverflow.com/comment/129863524

http://stackoverflow.com/a/49328950
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49291739
has body: I finally figured out what was wrong and why I wasn't getting any event pings from the API server. It turns out that my localhost needed to be publicly accessible in order to receive event changes from the server. My solution was to us ngrok to create a secure tunnel from my localhost out to the public endpoint. Once that was achieved, I added the callback url, which in turn allowed the server to ping me with event changes.
type: Answer
answers question: http://stackoverflow.com/q/49291739
upvote count: 2
score: 2

http://stackoverflow.com/comment/85588845
type: Comment
has text: @nj2337 thank you for a great explanation of code. As I run this I get the value 0 for any text strings I pass as all my strings are equal. Say, "data science" and "Data scient"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49292601

pythonista
tags question: http://stackoverflow.com/q/49349033
tag name: pythonista
type: Tag

http://stackoverflow.com/comment/85607301
type: QuestionComment
has text: Just run the code and you will see what I mean
comment on: http://stackoverflow.com/q/49302626
type: Comment
score: 0

http://stackoverflow.com/a/49361242
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85723580
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49360545
has comment: http://stackoverflow.com/comment/85722618
has body: I searched the item text in treeview to check duplication. def search(treeview, comparevalue): children = treeview.get_children('') for child in children: values = treeview.item(child, 'values') if comparevalue[0]==values[0] and str(comparevalue[1])==str(values[1]): return True return False def append_select(): cur_id = tree.focus() selvalue = tree.item(cur_id)['values'] print('append_select:', cur_id, selvalue) if search(tree2, selvalue)==True: print("item exist") elif cur_id: tree2.insert("", tk.END, values=selvalue) But more simply can worked by using item iid. def append_select(): cur_id = tree.focus() selvalue = tree.item(cur_id)['values'] if tree2.exists(cur_id)==True: print("item exist") elif cur_id: tree2.insert("", tk.END, cur_id, values=selvalue)
type: Answer
accepted answer of: http://stackoverflow.com/q/49360545

http://stackoverflow.com/q/49321748
has comment: http://stackoverflow.com/comment/85646114
upvote count: 1
answer count: 1
tagged with: selenium
linked to: http://stackoverflow.com/q/45635190
downvote count: 1
has comment: http://stackoverflow.com/comment/85644795
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49322010
has body: Program: Python + Selenium Situation: I am trying to run a script to automate Facebook login and open my Facebook home page Problem: I am a beginner and i am not sure if there is a problem in my python configuration or i am just doing a code mistake. the code is stopping at the last line. How did I retrieve the element class? i went to Facebook page and i inspected the profile button element and i copied it but it is not working (_1vp5 f_click) Resolution: could you please direct me on the best way to find the home page element Below is my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(executable_path=r"chromedriver.exe") driver.get("http://www.facebook.com") usr = "xxxxx" pwd = "yyyy" assert "Facebook" in driver.title elem = driver.find_element_by_id("email") elem.send_keys(usr) elem = driver.find_element_by_id("pass") elem.send_keys(pwd) elem.send_keys(Keys.RETURN) driver.find_element_by_class("_1vp5 f_click").click() Code output: Traceback (most recent call last): File "C:/Users/shouks/MyPythonScripts/test1.py", line 23, in &lt;module&gt; driver.find_element_by_class("_1vp5 f_click").click() AttributeError: 'WebDriver' object has no attribute 'find_element_by_class'
has comment: http://stackoverflow.com/comment/85646456
tagged with: facebook
tagged with: python
has comment: http://stackoverflow.com/comment/85644856
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/85647769
has answer: http://stackoverflow.com/a/49322010
type: AnsweredQuestion
has title: Python Selenium : How to click an element
has comment: http://stackoverflow.com/comment/85645246
score: 0

http://stackoverflow.com/comment/85707206
has text: If you go to http://127.0.0.1 in your browser, do you see another application running there such as Windows IIS?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49353418
type: QuestionComment

http://stackoverflow.com/comment/85578687
type: AnswerComment
has text: I guess that kind of answers my question. I was wondering if there was a way to create a single direct assertion to do this test. It seems I have to wrap the assertion in some logic/loop to determine it it is true.
comment on: http://stackoverflow.com/a/49287517
score: 0
type: Comment

http://stackoverflow.com/a/49286598
answers question: http://stackoverflow.com/q/49286456
type: Answer
has body: You can try this: df_out = df.groupby(['gender','occupation'])['gender'].count() (df_out / df_out.sum(level=0)).loc['M'].sort_values(ascending=False) Output: occupation technician 0.250 administrator 0.250 writer 0.125 student 0.125 lawyer 0.125 executive 0.125 Name: gender, dtype: float64
score: 2
upvote count: 2
downvote count: 0

scons
tag name: scons
tags question: http://stackoverflow.com/q/49295646
tags question: http://stackoverflow.com/q/49383508
type: Tag

pyspark
tags question: http://stackoverflow.com/q/49286282
tags question: http://stackoverflow.com/q/49303286
tags question: http://stackoverflow.com/q/49353078
tags question: http://stackoverflow.com/q/49389950
tags question: http://stackoverflow.com/q/49348130
tags question: http://stackoverflow.com/q/49332239
tags question: http://stackoverflow.com/q/49289539
tags question: http://stackoverflow.com/q/49384880
tags question: http://stackoverflow.com/q/49429709
tags question: http://stackoverflow.com/q/49303835
tags question: http://stackoverflow.com/q/49352674
tags question: http://stackoverflow.com/q/49396558
tags question: http://stackoverflow.com/q/49290029
tags question: http://stackoverflow.com/q/49408272
tags question: http://stackoverflow.com/q/49419678
tags question: http://stackoverflow.com/q/49399245
tags question: http://stackoverflow.com/q/49382957
tags question: http://stackoverflow.com/q/49321165
tags question: http://stackoverflow.com/q/49290553
tags question: http://stackoverflow.com/q/49318402
tags question: http://stackoverflow.com/q/49286434
tags question: http://stackoverflow.com/q/49374608
tags question: http://stackoverflow.com/q/49432950
tags question: http://stackoverflow.com/q/49305978
tags question: http://stackoverflow.com/q/49373453
tags question: http://stackoverflow.com/q/49404445
tags question: http://stackoverflow.com/q/49368475
tags question: http://stackoverflow.com/q/49421150
tags question: http://stackoverflow.com/q/49307581
tags question: http://stackoverflow.com/q/49376887
tags question: http://stackoverflow.com/q/49384449
tags question: http://stackoverflow.com/q/49291876
tags question: http://stackoverflow.com/q/49420660
tags question: http://stackoverflow.com/q/49404275
tags question: http://stackoverflow.com/q/49353752
tags question: http://stackoverflow.com/q/49378466
tags question: http://stackoverflow.com/q/49361286
tags question: http://stackoverflow.com/q/49394396
tags question: http://stackoverflow.com/q/49322578
type: Tag
tags question: http://stackoverflow.com/q/49403291
tags question: http://stackoverflow.com/q/49357302
tags question: http://stackoverflow.com/q/49406922
tags question: http://stackoverflow.com/q/49321731
tags question: http://stackoverflow.com/q/49366762
tags question: http://stackoverflow.com/q/49311592
tags question: http://stackoverflow.com/q/49356541
tags question: http://stackoverflow.com/q/49428524
tag name: pyspark
tags question: http://stackoverflow.com/q/49377085
tags question: http://stackoverflow.com/q/49390292
tags question: http://stackoverflow.com/q/49351487
tags question: http://stackoverflow.com/q/49377703
tags question: http://stackoverflow.com/q/49283986
tags question: http://stackoverflow.com/q/49365911
tags question: http://stackoverflow.com/q/49299079
tags question: http://stackoverflow.com/q/49341281
tags question: http://stackoverflow.com/q/49389575
tags question: http://stackoverflow.com/q/49428928
tags question: http://stackoverflow.com/q/49411495

http://stackoverflow.com/q/49309449
tagged with: python
has title: Searching Nested Document
has body: I am having trouble searching nested documents using the elasticsearch_dsl and elasticsearch libraries in Python. I can successfully perform searches on top-level (i.e. non-nested) parts of the documents, but all of my attempts to search the nested portions fail for one reason or another. I have scoured StackOverflow &amp; the web for a definitive guide to searching nested documents using Python, but keep coming up short. Here is a sample document that I am using: {"username": "nancy", "codeData": [ {"code": "B1", "order": "2"}, {"code": "L4", "order": "1"} ] } I have 7 documents in an index, which I have mapped like this: request_body = { "settings" : { "number_of_shards": 5, "number_of_replicas": 1 }, 'mappings': { 'testNesting': { 'properties': { 'username': {'type': 'text'}, 'codeData': {'type': 'nested', 'properties' :{ "code" : {"type":"text"}, "order" :{"type":"text"} } } } } } } es.indices.create(index = "nest-test6", body = request_body) Performing the following search works correctly: s = Search(using = es).query("match", username = "nancy") response = s.execute() print(response.to_dict()) Now, I want to try searching for documents that have code = "B1" within "codeData". I have listed the sources that I've tried to use at the bottom of this question. My hope is that this can become a definitive guide that people can reference when trying to query nested documents using Python. Here is what I have tried so far: q = Q("match", code = "L4") s = Search(using = es, index = "nest-test6").query("nested", path = "codeData", query = q) Above results in a Transport Error (400, failed to create query), and then lists the query itself with a bunch of \n after each item. q = Q("match", **{"codeData.code"" : "L4"}) s = Search(using = es, index = "nest-test6").query("nested", path = "codeData", query = q) Above results in a syntax error on line 1. s = Search(using = es, index = "nest-test6").query("nested", path = "lithologyData", query = **Q{"match":{ "lithology":"L4"}…
favorite count: 0
score: 3
answer count: 1
tagged with: elasticsearch
tagged with: elasticsearch-dsl
type: Question
has answer: http://stackoverflow.com/a/49323825
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49354641
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85710239
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85709748
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85709996
has comment: http://stackoverflow.com/comment/85710168
tagged with: python
tagged with: python-cryptography
has comment: http://stackoverflow.com/comment/104459924
has body: I have an RSA modulus and exponent in binary format. I don't have access to the key in PEM format. How can I load it using cryptography library? I am not sure how to approach this but I have: from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization key_file = open("key", "rb") private_key = serialization.load_pem_private_key( base64.b64encode(key_file.read()), password=None, backend=default_backend() ) ValueError: Could not deserialize key data. As a note, I don't have to use the cryptography library and if there is a better way to do this using a different library, that's okay.
answer count: 0
score: 1
has title: How to read binary key in Python Cryptography?
has comment: http://stackoverflow.com/comment/85710113

http://stackoverflow.com/comment/85834179
comment on: http://stackoverflow.com/q/49414693
type: Comment
type: QuestionComment
has text: Related: **[Why “the best choice” or “possible options” questions are always downvoted](https://meta.stackexchange.com/q/214215/370758)**
score: 0

music21
type: Tag
tags question: http://stackoverflow.com/q/49339622
tag name: music21

http://stackoverflow.com/comment/85607461
comment on: http://stackoverflow.com/q/49302626
has text: Consider searching for the specific tag you are interested in: `prod_price = driver.find_element_by_xpath('//span[@id='priceblock_ourprice']').text`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49340824
score: 0
has comment: http://stackoverflow.com/comment/85689397
has body: I haven't actually figured out why specifying the string (or text for older versions of BeautifulSoup) parameter of find_all(...) doesn't give me what I want but, the following does give me a generalized solution. pattern = re.compile('color', flags=re.UNICODE+re.IGNORECASE) desired_tags = [tag for tag in soup.find_all('p') if pattern.search(tag.text) is not None]
type: Answer
answers question: http://stackoverflow.com/q/49338402

http://stackoverflow.com/q/49342275
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/85724110
tagged with: python
has title: Part (or instance) rotation in abaqus with Euler angle
type: AnsweredQuestion
score: 0
has body: I tried to model composite with many inclusions (cylinder). I need to rotate the cylinders to the proper position with given Euler angles. But I found from abaqus documentation that instance in abaqus can only be rotated by certain axis. So I was wondering is there a way in abaqus (or abaqus-python) to rotate instance by Euler angles?
has comment: http://stackoverflow.com/comment/85704913
has comment: http://stackoverflow.com/comment/85684817
tagged with: abaqus
has answer: http://stackoverflow.com/a/49364985
accepted answer: http://stackoverflow.com/a/49364985

http://stackoverflow.com/comment/85666344
score: 0
type: Comment
type: AnswerComment
has text: The source is going to be two fairly high-end SSDs; the destination is going to be two heterogenous, non-RAID mechanical drives, each needing the contents of both source drives. The plan now is to first copy "over" (A->a & B->b) then copy "across" (A->b & B->a). Unless adding two writes to the `copyfileobj` clone (read-once write-twice) would speed anything up?
comment on: http://stackoverflow.com/a/49332057

http://stackoverflow.com/comment/85686067
type: QuestionComment
has text: This is a highly wasteful way to do this. You make a call to the API for every seperate piece of information, including the timestamp, so it's not really valid anyway, although it may not matter for your purposes..
comment on: http://stackoverflow.com/q/49342838
score: 1
type: Comment

http://stackoverflow.com/q/49328525
possible better answer: http://stackoverflow.com/a/76470200
tagged with: shell
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49328725
has answer: http://stackoverflow.com/a/49328725
has answer: http://stackoverflow.com/a/78077465
score: 67
tagged with: python
tagged with: virtualenv
has body: I am in a virtualenv and trying to run through pip installs. I know the code works because outside the virtualenv this code has worked. I am running on a Windows 10 machine. Using the Git Bash terminal or the regular command prompt (have tried as admin and regular user). I am trying to run pip install dotenv or python -m pip install dotenv and neither of the two work. I get the error saying AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' During handling of the above exception, another exception occurred:Command "python setup.py egg_info" failed with error code 1 in C:\Users\USER~1\AppData\Local\Temp\pip-build-7bbdcnx2\dotenv\ I have also tried to do things such as python -m pip install setuptools --upgrade un-install setuptools and install it again. restart my computer. and many other things. I'm not too sure what else to try (i've installed flask before this and it worked, I also can install other things like mitmproxy as an example) Any ideas? Again, this is a Windows 10 machine and I just want to install dotenv for Python (version 3.6.4 if it matters). Thank you.
has answer: http://stackoverflow.com/a/76470200
upvote count: 67
type: AnsweredQuestion
answer count: 3
tagged with: windows
has title: pip install dotenv error code 1 Windows 10
downvote count: 0

http://stackoverflow.com/q/49331641
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85665375
score: 0
has body: I am trying to build a responsive interface using p5.js. It uses user responses to update pyo4 object variables. QUESTION Can I use Python inside p5.js? QUESTION If I can't use Python can I use PHP inside p5.js and evoke Python within PHP? I tried this simple example without luck: var htmlString="&lt;?php echo $htmlString;?&gt;"
answer count: 1
accepted answer: http://stackoverflow.com/a/49331905
has title: Use php code bloks inside p5.js to invoke python script
type: Question
linked to: http://stackoverflow.com/q/22808517
tagged with: p5.js
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/85665322
has answer: http://stackoverflow.com/a/49331905

http://stackoverflow.com/a/49384850
score: 2
downvote count: 0
has body: is your script generating any HTML reports, if yes, you can publish the HTML in the email body. Display HTML page inside mail body with Email-ext plugin in Jenkins
type: Answer
answers question: http://stackoverflow.com/q/49380688
upvote count: 2

oracle-database
tags question: http://stackoverflow.com/q/49332719
tags question: http://stackoverflow.com/q/49315383
tags question: http://stackoverflow.com/q/49288724
tags question: http://stackoverflow.com/q/49326271
tags question: http://stackoverflow.com/q/49310178
tag name: oracle-database
tags question: http://stackoverflow.com/q/49398152
tags question: http://stackoverflow.com/q/49322210
type: Tag
tags question: http://stackoverflow.com/q/49422671

http://stackoverflow.com/comment/85783281
has text: great thanks did the trick, how does this work even with the path "C:\Program Files\py3.5" not being the actual path to my directory holding the python.exe?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49390850
type: AnswerComment

http://stackoverflow.com/q/49429368
tagged with: python
has comment: http://stackoverflow.com/comment/85963204
has comment: http://stackoverflow.com/comment/85885921
downvote count: 1
has comment: http://stackoverflow.com/comment/85886282
answer count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/49502189
has comment: http://stackoverflow.com/comment/86099840
accepted answer: http://stackoverflow.com/a/49677125
has comment: http://stackoverflow.com/comment/85877532
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86101749
has comment: http://stackoverflow.com/comment/85885994
upvote count: 46
has answer: http://stackoverflow.com/a/49502189
has answer: http://stackoverflow.com/a/49677125
has title: How to solve memory issues while multiprocessing using Pool.map()?
score: 45
linked to: http://stackoverflow.com/q/25962114
tagged with: pandas
linked to: http://stackoverflow.com/q/49475489
linked to: http://stackoverflow.com/q/23853553
has comment: http://stackoverflow.com/comment/85869795
has comment: http://stackoverflow.com/comment/86165246
tagged with: memory
has answer: http://stackoverflow.com/a/49506903
linked to: http://stackoverflow.com/q/45943160
has comment: http://stackoverflow.com/comment/85885498
has comment: http://stackoverflow.com/comment/85963093
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/85886326
has answer: http://stackoverflow.com/a/49470953
has comment: http://stackoverflow.com/comment/85963003
has comment: http://stackoverflow.com/comment/85962930
linked to: http://stackoverflow.com/q/34143397
has comment: http://stackoverflow.com/comment/85885626
has body: I have written the program (below) to: read a huge text file as pandas dataframe then groupby using a specific column value to split the data and store as list of dataframes. then pipe the data to multiprocess Pool.map() to process each dataframe in parallel. Everything is fine, the program works well on my small test dataset. But, when I pipe in my large data (about 14 GB), the memory consumption exponentially increases and then freezes the computer or gets killed (in HPC cluster). I have added codes to clear the memory as soon as the data/variable isn't useful. I am also closing the pool as soon as it is done. Still with 14 GB input I was only expecting 2*14 GB memory burden, but it seems like lot is going on. I also tried to tweak using chunkSize and maxTaskPerChild, etc but I am not seeing any difference in optimization in both test vs. large file. I think improvements to this code is/are required at this code position, when I start multiprocessing. p = Pool(3) # number of pool to run at once; default at 1 result = p.map(matrix_to_vcf, list(gen_matrix_df_list.values())) but, I am posting the whole code. Test example: I created a test file ("genome_matrix_final-chr1234-1mb.txt") of upto 250 mb and ran the program. When I check the system monitor I can see that memory consumption increased by about 6 GB. I am not so clear why so much memory space is taken by 250 mb file plus some outputs. I have shared that file via drop box if it helps in seeing the real problem. https://www.dropbox.com/sh/coihujii38t5prd/AABDXv8ACGIYczeMtzKBo0eea?dl=0 Can someone suggest, How I can get rid of the problem? My python script: #!/home/bin/python3 import pandas as pd import collections from multiprocessing import Pool import io import time import resource print() print('Checking required modules') print() ''' change this input file name and/or path as need be ''' genome_matrix_file = "genome_matrix_final-chr1n2-2mb.txt" # test file 01 genome_matrix_file = "genome_matrix_final-chr1234…

http://stackoverflow.com/a/49295809
accepted answer of: http://stackoverflow.com/q/49295451
has body: Use reshape() : w2 = G.w - alpha *temp.reshape(-1,1) print(w2.shape) (784,1) Or transpose() (which is slighlty slower, see examples): w2 = G.w - alpha *temp.transpose() print(w2.shape) (784,1) Examples A = np.random.rand(100,1) B = np.random.rand(1,100) print(A.shape) (100, 1) print(B.shape) (1, 100) print((A - 0.1*B).shape) (100, 100) print((A - 0.1*B.reshape(-1,1)).shape) #3.86 µs per loop (100, 1) print((A - 0.1*B.transpose()).shape) #5.27 µs per loop (100, 1)
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/49295451
type: Answer

http://stackoverflow.com/comment/85660736
type: AnswerComment
score: 0
type: Comment
has text: Ohh yeah.. for that very purpose I printed the URL as a log everytime. Can you please try running the snippet on your machine? Thanks in advance!
comment on: http://stackoverflow.com/a/49329207

http://stackoverflow.com/comment/85690265
has text: Also, what is this code supposed to _do_? For example, is there a reason you're writing `d1 = {"x": 9}` and then `d.update(d1)`? Do you expect that to do something different than just `d["x"] = 9`? If so, without knowing _what_ you expect it to do, it's impossible to tell you how to fix it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49345084

http://stackoverflow.com/q/49354330
downvote count: 0
has title: Lemmatization of slang words in Python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85709083
tagged with: sentiment-analysis
tagged with: nltk
has body: I'm trying to train an SVM for Twitter text classification. Obviously, tweets tend to contain a lot of words that are slang or misspelled relative to formal documents that are more common to NLP. Here's an example of a tweet I'm trying to classify: Word I'm bout to holla at her via twitter RT @iamJay_Fresh : #trushit - im tryna fucc nicki minaj lol I want to know if it's possible to stem/lemmatize this text so the slang words are corrected and it looks something like this: Word I'm about to holler at her via Twitter RT @iamJay_Fresh : #trushit - I'm trying to fuck Nicki Minaj lol Note: I'm not too concerned about expanding common acronyms like "lol" to "laughing out loud". The reason I want to lemmatize is to reduce data sparsity: if the SVM has seen "holler" many times in a negative context but "holla" only a few times because people use it less, it would benefit from using the connotation of "holler" to classify a tweet with "holla". OTOH "lol" is commonly used in positive tweets so if the SVM sees another "lol" it'll know about its polarity even though it's not formal English.
tagged with: python
tagged with: nlp
score: 2
tagged with: lemmatization
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/85934084
type: AnswerComment
comment on: http://stackoverflow.com/a/49426735
has text: Perfect, this does exactly what I needed to do. Would not have thought of this on my own.
type: Comment
score: 0

http://stackoverflow.com/q/49436895
has title: Arguments for LogLocator
type: Question
has body: In MatPlotLib, I want to plot a graph with a linear x-axis and a logarithmic y-axis. For the x-axis, there should be labels at multiples of 4, and minor ticks at multiples of 1. I have been able to do this using the MultipleLocator class. However, I am having difficulty doing a similar thing for the logarithmic y-axis. I want there to be labels at 0.1, 0.2, 0.3 etc., and minor ticks at 0.11, 0.12, 0.13 etc. I have tried doing this with the LogLocator class, but I'm not sure what the right parameters are. Here is what I have tried to far: x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10] fig = plt.figure() ax1 = fig.add_subplot(111) x_major = MultipleLocator(4) x_minor = MultipleLocator(1) ax1.xaxis.set_major_locator(x_major) ax1.xaxis.set_minor_locator(x_minor) ax1.set_yscale("log") y_major = LogLocator(base=10) y_minor = LogLocator(base=10) ax1.yaxis.set_major_locator(y_major) ax1.yaxis.set_minor_locator(y_minor) ax1.plot(x, y) plt.show() This shows the following plot: The x-axis is as I want it, but not the y-axis. There is a label on the y-axis at 0.1, but no labels at 0.2 and 0.3. Also, there are no ticks at 0.11, 0.12, 0.13 etc. I have tried some different values for the LogLocator constructor, such as subs, numdecs, and numticks, but I cannot get the right plot. The documentation at https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.LogLocator doesn't really explain these parameters very well. What parameter values should I be using?
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
tagged with: yticks
upvote count: 5
has answer: http://stackoverflow.com/a/49442932
score: 5
tagged with: matplotlib
tagged with: xticks
tagged with: python

http://stackoverflow.com/comment/85884718
has text: @JonDeaton Redis would be pretty painless, I don't think you'd have to re-write anything. You could probably wrap the Redis client in some class that implements `__getitem__` and `__setitem__` and it would be a drop-in replacement for your `dict`. I'm just saying, Redis *solves this problem already*. Almost certainly, it would require less effort than implementing a hash-map over `multiprocessing.Array`
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49438954
type: QuestionComment

http://stackoverflow.com/a/49298578
upvote count: 2
has comment: http://stackoverflow.com/comment/85599715
has body: From prefetch_related documentation Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups. As you can see from following explanation prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. prefetch_related will do queries for each of tables and merge them in python Additionally if you are having Foreign keys and not Many to Many you could use select_related instead
score: 2
has comment: http://stackoverflow.com/comment/85599302
downvote count: 0
has comment: http://stackoverflow.com/comment/85598968
type: Answer
answers question: http://stackoverflow.com/q/49298480

http://stackoverflow.com/a/49327793
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49327240
type: Answer
has body: Using numpy's argsort method. df = pd.DataFrame({'col_a':[0,0,0,1,1,1], 'col_b':[5,2,8,3,7,4]}) df["rank"] = np.argsort( df.values.copy().view(dtype=[('x', int), ('y', int)]).flatten(), order=("x","y") ) + 1 col_a col_b rank 0 0 5 2 1 0 2 1 2 0 8 3 3 1 3 4 4 1 7 6 5 1 4 5

http://stackoverflow.com/comment/85732175
type: Comment
comment on: http://stackoverflow.com/q/49365432
score: 0
type: QuestionComment
has text: @chepner I see. Is there a way I am able to half them, and then add the halves together so that they contain the best values from both populations?

http://stackoverflow.com/a/49438375
has body: In this example the dataframe has multiindex (i.e. indexed over several columns). So, row keys are iterables instead of a single value. So, in the df.loc['g1','v1'] example pandas interprets ('g1','v1') as a row index instead of firsrt column of multiindex and a column. If you want to index only on the first column of the index, use an iterable type (possible incomplete) as a row index: df.loc[['g1'],'a']
upvote count: 1
answers question: http://stackoverflow.com/q/49438163
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/85671807
has text: So it is suggesting to put in a separate view? How would I display data and the image together? Doesn't one view = one page or can I get multiple views on a page?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49334579

http://stackoverflow.com/comment/85694890
type: Comment
comment on: http://stackoverflow.com/q/49347609
has text: If your code requires horizontal scroll, you're doing it wrong. Keep them short and sweet.
type: QuestionComment
score: 2

http://stackoverflow.com/a/49580678
has body: I used DictVectorizer instead and it fixed the problem: X, y = df.iloc[:,:-1], df.iloc[:,-1] # Import DictVectorizer from sklearn.feature_extraction import DictVectorizer # Convert df into a dictionary using .to_dict(): df_dict df_dict = X.to_dict("records") # Create the DictVectorizer object: dv dv = DictVectorizer(sparse=False) # Apply dv on df_dict: df_encoded X_encoded = dv.fit_transform(df_dict) X_encoded = pd.DataFrame(X_encoded) X_train, X_test, y_train, y_test= train_test_split(X_encoded, y, test_size=0.2, random_state=123) Now fit the model and plot the feature importances: Finally, you have to look up the names: # Use pprint to make the vocabulary easier to read import pprint pprint.pprint(dv.vocabulary_) If anyone knows how to get the plot to use the dictionary vocabulary to look up the feature names and put them on the plot, I would greatly appreciate your input.
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49288515
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49288515
score: 1

http://stackoverflow.com/comment/85762752
comment on: http://stackoverflow.com/a/49380398
has text: It can work.Thx May I ask antoher question? How can i show the whole div class to html
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49429971
has answer: http://stackoverflow.com/a/49468226
tagged with: word-embedding
has comment: http://stackoverflow.com/comment/85862278
tagged with: word2vec
tagged with: python
tagged with: gensim
has comment: http://stackoverflow.com/comment/85869589
has answer: http://stackoverflow.com/a/63893888
has body: I am new to Gensim, and I am trying to load my given (pre-trained) Word2vec model. I have 2 files: xxxx.model.wv and a bigger one xxxx.model.wv.syn0.npy. When I call the following line: gensim.models.Word2Vec.load('xxxx.model.wv') I get the following error: AttributeError: 'EuclideanKeyedVectors' object has no attribute 'negative' How can I solve this error?
accepted answer: http://stackoverflow.com/a/49468226
score: 2
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/63893888
downvote count: 0
favorite count: 0
type: Question
has title: How can I load Word2vec with Gensim without getting an AttributeError?
type: AnsweredQuestion

http://stackoverflow.com/q/49288597
linked to: http://stackoverflow.com/q/2953746
has answer: http://stackoverflow.com/a/49288743
answer count: 2
has title: How to read a comma-separated value from a CSV file as an integer?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49288668
has body: I am having a bit of trouble reading data from a CSV file as an integer. Here is an example of my CSV file: Col1 Col2 Col3 Header Header Header Header 1 1,000,000 BLANK 2 500,000 BLANK 3 200,000 What I am wanting to do is read in the data from 'Col3' (not including the header) as integers into a tuple. Here is my code: import csv prizePoints = [] with open("csvfile.csv") as prizes: next(prizes) for row in prizes: prizePoints.append(row) When I try this, I get an error that says: ValueError: invalid literal for int() with base 10: '"1' Example of printed row: ['', '1', '1,000,000'] I think it is due to the values in 'Col3' having commas. However, I am unsure of how to fix this so any help would be greatly appreciated! P.S. I can't change the format of the values for 'Col3' so that they do not have commas.
has comment: http://stackoverflow.com/comment/85580809
type: Question
has comment: http://stackoverflow.com/comment/85580416
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85580841
tagged with: python

http://stackoverflow.com/comment/85721253
comment on: http://stackoverflow.com/a/49360080
has text: Not sure what you need, if you are hoping to append your results each time you run the script then you can use `'a'` instead. If you are hoping to write more data per row, take a look at the [`csv`](https://docs.python.org/3.6/library/csv.html#module-csv) library in Python. This helps you write a list to a file automatically adding delimiters between each value.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/85690603
type: QuestionComment
type: Comment
has text: Anyway, that code isn't going to work if you don't have a writable current working directory. And it's also not going to do anything useful. First, `write` just returns how many bytes it wrote, which you don't care about. Second, whatever you were planning to do with that file (e.g., if you're using Pillow, `Image.open` it) you can almost certainly do with `binary`, or with `io.BytesIO(binary)`, just as easily (but without knowing what you're planning to do with it, nobody can show you exactly how).
score: 0
comment on: http://stackoverflow.com/q/49345303

http://stackoverflow.com/comment/106985217
comment on: http://stackoverflow.com/a/49345499
type: AnswerComment
has text: @OlivierMoindrot how does this even work? How is the data actually put in if you only use placeholders?
score: 0
type: Comment

http://stackoverflow.com/q/49365911
favorite count: 0
has answer: http://stackoverflow.com/a/49366013
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49367105
type: UnansweredQuestion
tagged with: pyspark
downvote count: 0
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/6582171
score: 3
has body: I have a pyspark dataframe with a column FullPath. How can I use the function os.path.splitext(FullPath) to extract the extension of each entry in the FullPath column and put them in a new column? Thanks.
upvote count: 3
has title: Extract file extension from Pyspark Dataframe column

http://stackoverflow.com/q/49416548
answer count: 1
type: Question
has body: thanks in advance for any input.... I'm trying to group some temperature readings together so I can compare two sets of readings. Below I'm trying to do it for a minute, but it doesn't matter if it's an hour. The data seems to come through OK, just won't group properly. It just lists out all the temperature readings (many per minute). The data is here : https://github.com/uilfut/pi_code/blob/master/tinydb_environment.json 'date_time' is the datetime column 'tempC' is the temperature column from pandas.io.json import json_normalize import datetime as dt import numpy as np with open('/home/data.json') as f: data = json.load(f) df = pd.DataFrame.from_dict({(i, j): data[i][j] for i in data.keys() for j in data[i].keys()}, orient='index') df['data_source'] = df.index.droplevel(level=1) df.index = df.index.droplevel(level=0) df['date_time'] = pd.to_datetime(df['date_time']) # this next line doesn't work - df.set_index('date_time').groupby(pd.Grouper(freq='T, min')['tempC'].mean() print(df.head(10)) I also tried # df['time'] = df['date_time'].dt.time # df.groupby(pd.TimeGrouper('5Min'))['tempC'].mean().dropna() # df.set_index('date_time').groupby(pd.TimeGrouper('1hour')) ['tempC'].mean().dropna() # df.set_index('date_time').groupby(pd.Grouper(freq='T, min')) ['tempC'].mean() # df.set_index('time').resample("H").mean() # df.set_index('date_time').resample('5min', how=np.mean) Hope it's something easy for someone! Many thanks
tagged with: datetime
tagged with: python
score: 0
tagged with: pandas-groupby
tagged with: pandas
has title: Can't make pandas group by timeframe
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49418844

http://stackoverflow.com/q/49351190
has body: I have the following dataframe imported from a csv file: ts employee_id gps_lat gps_lng event_id event_params speed status serial_number 9/22/2016 13:53 1 34.97 -81.98 Down {"type":"Down","maximumangle":0,"duration":0} 0 1100110 211 9/22/2016 13:53 1 34.97 -81.98 Left {"type":"Left","maximumangle":-38.57,"duration":203} 0 1102110 212 9/22/2016 13:53 1 34.97 -81.98 Right {"type":"Right","maximumangle":52.975,"duration":17} 0 1102130 250 9/22/2016 13:53 1 34.97 -81.98 Down {"type":"Down","maximumangle":0,"duration":0} 0 1102130 249 9/22/2016 13:54 1 34.97 -81.98 Down {"type":"Down","maximumangle":0,"duration":0} 0 1102140 280 9/22/2016 13:54 1 34.97 -81.98 Left {"type":"Left","maximumangle":-10.866,"duration":40} 0 1102140 279 I need to split the event_params column into separate columns with headers- Type, Maximum Angle and Duration, and I need to get rid of curly braces. In short I need the following output. ts employee_id gps_lat gps_lng event_id Type maximumangle duration speed status serial_number 9/22/2016 13:53 1 34.97 -81.98 Down Down 0 0 0 1100110 211 9/22/2016 13:53 1 34.97 -81.98 Left Left -38.57 203 0 1102110 212 9/22/2016 13:53 1 34.97 -81.98 Right Right 52.975 17 0 1102130 250 9/22/2016 13:53 1 34.97 -81.98 Down Down 0 0 0 1102130 249 9/22/2016 13:54 1 34.97 -81.98 Down Down 0 0 0 1102140 280 #Code I am trying to use: import re parts = re.split('\df3|(?&lt;!\d)[:.](?!\d)', df3) parts I am trying to approach the problem by spliting it first about : delimiter, then splitting the last column by } and then deleting the columns with contents maximum angle and duration. I have been trying to use the re.split function in the following way but it returns error --expected string or bytes-like object
downvote count: 4
has title: Spliting a column with strings in a dataframe
type: UnansweredQuestion
tagged with: python
tagged with: regex
tagged with: delimiter
score: -3
tagged with: pandas
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49351598
favorite count: 0
type: Question

http://stackoverflow.com/q/49353463
has comment: http://stackoverflow.com/comment/85707339
has comment: http://stackoverflow.com/comment/85707358
has answer: http://stackoverflow.com/a/49353557
tagged with: clang
accepted answer: http://stackoverflow.com/a/49353557
tagged with: c++11
type: Question
has comment: http://stackoverflow.com/comment/85707638
has title: Cython compiled ok, but Symbol not found: __ZNSs4_Rep20_S_empty_rep_storageE when running on Mac OS
tagged with: python
has comment: http://stackoverflow.com/comment/85707541
has comment: http://stackoverflow.com/comment/85707237
tagged with: c++
type: AnsweredQuestion
score: 0
has body: System: Mac OS 10.12.6. Python: Python 3.5.2 from Anoconda3. Cython==0.28. I set up and compiled Cython with # the .pyx file from libc.stdint cimport * cimport CLexActivator def SetProductFile(filePath): cdef bytes py_bytes = filePath.encode() cdef const char* c_string = py_bytes cdef int32_t status = CLexActivator.SetProductFile(c_string) print(status) return status and # the setup file from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize ext_modules=[ Extension("PyLexActivator", sources=["PyLexActivator.pyx"], language='c', extra_objects=["libLexActivator.a"], ) ] setup( name = "PyLexActivator", ext_modules = cythonize(ext_modules) ) I used python setup.py build_ext --inplace to compile. Compiling PyLexActivator.pyx because it changed. [1/1] Cythonizing PyLexActivator.pyx running build_ext building 'PyLexActivator' extension creating build creating build/temp.macosx-10.6-x86_64-3.5 /usr/bin/clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/o/anaconda/include -arch x86_64 -I. -I/Users/o/anaconda/include/python3.5m -c PyLexActivator.c -o build/temp.macosx-10.6-x86_64-3.5/PyLexActivator.o /usr/bin/clang -bundle -undefined dynamic_lookup -L/Users/o/anaconda/lib -arch x86_64 build/temp.macosx-10.6-x86_64-3.5/PyLexActivator.o libLexActivator.a -L/Users/o/anaconda/lib -o /path to/PyLexActivator.cpython-35m-darwin.so Error occurs when running import PyLexActivator dlopen(/path to/PyLexActivator.cpython-35m-darwin.so, 2): Symbol not found: __ZNSs4_Rep20_S_empty_rep_storageE Referenced from: /path to/PyLexActivator.cpython-35m-darwin.so Expected in: flat namespace in /path to/PyLexActivator.cpython-35m-darwin.so I do not know what __ZNSs4_Rep20_S_empty_rep_storageE represents. Since the .pyx compiled with a static lib libLexActivator.a, I guess this error might come from unknown references. But I do not know how to solve it. I also use otool -L to sho…
answer count: 1
tagged with: cython

http://stackoverflow.com/comment/85721844
has text: @Sabrina You are right. And this is because both are evaluated if not put in one line (Where left is first and right second).
type: Comment
comment on: http://stackoverflow.com/a/49351316
type: AnswerComment
score: 0

http://stackoverflow.com/a/49279969
downvote count: 0
upvote count: 1
has body: This probably? def remove_words(s): return s.apply(lambda x: ["".join([x for x in x if x not in ["name", "is"]])])
score: 1
answers question: http://stackoverflow.com/q/49279901
type: Answer

http://stackoverflow.com/comment/85786195
type: AnswerComment
has text: This works great, but as Vamsi mentioned, I need to be able to use it in a groupby
score: 0
comment on: http://stackoverflow.com/a/49391972
type: Comment

http://stackoverflow.com/q/49307927
has comment: http://stackoverflow.com/comment/85617905
has comment: http://stackoverflow.com/comment/85619270
has comment: http://stackoverflow.com/comment/131056966
has title: Python ModuleNotFoundError: No module named 'paramiko'
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85618504
tagged with: windows
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/85618616
has body: I am using Spyder in Windows machine to execute below Python program. But the program fails with error message "ModuleNotFoundError: No module named 'paramiko'" I installed paramiko by going to command line . So I know paramiko is installed. But it is showing error from Spyder. Can you please help me to fix this issue ? import os import paramiko server="xxx" username="xxx" password="xxx" localpath="C:\Temp\MyLog.txt" remotepath="C:\Temp" ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) ssh.connect(server, username=username, password=password) sftp = ssh.open_sftp() sftp.put(localpath, remotepath) sftp.close() ssh.close()

http://stackoverflow.com/a/49339613
has comment: http://stackoverflow.com/comment/85679879
upvote count: 2
has body: You can use a dictionary to store the list names and each associated list: d = {'l_2': ['e', 'f', 'g'], 'l_3': ['g', 'h', 'i'], 'l_1': ['a', 'b', 'c']} l_all = ['l_1','l_2','l_3'] final_results = [d[i] for i in l_all] Output: [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] However, to actually access the lists via variable name, you would have to use globals: l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] l_all = ['l_1','l_2','l_3'] new_l = [globals()[i] for i in l_all] Output: [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']]
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85679544
has comment: http://stackoverflow.com/comment/85679735
score: 2
has comment: http://stackoverflow.com/comment/85679714
has comment: http://stackoverflow.com/comment/85679599
answers question: http://stackoverflow.com/q/49339589
has comment: http://stackoverflow.com/comment/85679946

http://stackoverflow.com/comment/85821255
has text: `command=self.sendinfo`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49409827
score: 3

http://stackoverflow.com/q/49438954
upvote count: 23
has comment: http://stackoverflow.com/comment/85883210
has comment: http://stackoverflow.com/comment/85879879
has comment: http://stackoverflow.com/comment/85977389
has answer: http://stackoverflow.com/a/50067306
has comment: http://stackoverflow.com/comment/85884758
has comment: http://stackoverflow.com/comment/85879999
has title: Python Shared Memory Dictionary for Mapping Big Data
has comment: http://stackoverflow.com/comment/85879970
has answer: http://stackoverflow.com/a/49591717
has comment: http://stackoverflow.com/comment/85880086
has answer: http://stackoverflow.com/a/49535259
has comment: http://stackoverflow.com/comment/85879907
has body: I've been having a hard time using a large dictionary (~86GB, 1.75 billion keys) to process a big dataset (2TB) using multiprocessing in Python. Context: a dictionary mapping strings to strings is loaded from pickled files into memory. Once loaded, worker processes (ideally >32) are created that must lookup values in the dictionary but not modify it's contents, in order to process the ~2TB dataset. The data set needs to be processed in parallel otherwise the task would take over a month. Here are the two three four five six seven eight nine approaches (all failing) that I have tried: Store the dictionary as a global variable in the Python program and then fork the ~32 worker processes. Theoretically this method might work since the dictionary is not being modified and therefore the COW mechanism of fork on Linux would mean that the data structure would be shared and not copied among processes. However, when I attempt this, my program crashes on os.fork() inside of multiprocessing.Pool.map from OSError: [Errno 12] Cannot allocate memory. I'm convinced that this is because the kernel is configured to never overcommit memory (/proc/sys/vm/overcommit_memory is set to 2, and I can't configure this setting on the machine since I don't have root access). Load the dictionary into a shared-memory dictionary with multiprocessing.Manager.dict. With this approach I was able to fork the 32 worker process without crashing but the subsequent data processing is orders of magnitude slower than another version of the task that required no dictionary (only difference is no dictionary lookup). I theorize that this is because of the inter-process communication between the manager process containing the dictionary and each worker process, that is required for every single dictionary lookup. Although the dictionary is not being modified, it is being accessed many many times, often simultaneously by many processes. Copy the dictionary into a C++ std::map and rely on Linux's COW mechanism t…
has comment: http://stackoverflow.com/comment/85883119
has answer: http://stackoverflow.com/a/49472025
has comment: http://stackoverflow.com/comment/86014611
answer count: 10
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49555198
has comment: http://stackoverflow.com/comment/85884718
has comment: http://stackoverflow.com/comment/85880304
has comment: http://stackoverflow.com/comment/85879922
has comment: http://stackoverflow.com/comment/85882539
has comment: http://stackoverflow.com/comment/85883882
has comment: http://stackoverflow.com/comment/85879963
has comment: http://stackoverflow.com/comment/85880059
has comment: http://stackoverflow.com/comment/85883454
favorite count: 0
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/85883929
has comment: http://stackoverflow.com/comment/86378445
has comment: http://stackoverflow.com/comment/85879954
has comment: http://stackoverflow.com/comment/85880062
has answer: http://stackoverflow.com/a/49525170
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85880106
has comment: http://stackoverflow.com/comment/85961361
tagged with: bigdata
has answer: http://stackoverflow.com/a/49593862
has answer: http://stackoverflow.com/a/49439082
has comment: http://stackoverflow.com/comment/85883165
has answer: http://stackoverflow.com/a/49473779
downvote count: 1
has answer: http://stackoverflow.com/a/49472227
score: 22

http://stackoverflow.com/comment/85822806
type: Comment
has text: Aww.. schucks. I feel the "+1" love and it is returned.
comment on: http://stackoverflow.com/a/49410526
score: 0
type: AnswerComment

http://stackoverflow.com/a/49437904
has comment: http://stackoverflow.com/comment/85878090
has body: If you want a customized version of str(a), the answer is array_str: &gt;&gt;&gt; print(a) [ 1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896] &gt;&gt;&gt; str(a) '[1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715\n 1.04486896]' &gt;&gt;&gt; np.array_str(a, max_line_width=np.inf) '[1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896]' &gt;&gt;&gt; print(np.array_str(a, max_line_width=np.inf) [1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896] If you want to change the printout of every array, not just here, see set_printoptions.
downvote count: 0
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/119847424
upvote count: 11
answers question: http://stackoverflow.com/q/49437807

http://stackoverflow.com/q/49287325
has comment: http://stackoverflow.com/comment/85581558
has comment: http://stackoverflow.com/comment/85578650
has comment: http://stackoverflow.com/comment/85579030
has comment: http://stackoverflow.com/comment/85581249
tagged with: pycurl
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85580915
has comment: http://stackoverflow.com/comment/85581443
linked to: http://stackoverflow.com/q/15461995
has title: how would I speed up my python pycurl looping requests
tagged with: python
has body: I am attempting to just generate traffic on the network by having a large list of sites that I am opening from a text file. I then would like to get the site and all the href links. Go to those links and then the site, then proceed onto the next site in the text document. My problem (that I have been noticing) is that it taking a while to execute these statements, Upwards of 5 seconds per curl. Is this because of my excessive use of try except loops? I'm just trying to understand where the problem may be. 2018-03-14 16:30:32.590135 http://www.ipostparcels.com/parcel-delivery/amazon-parcel-delivery 2018-03-14 16:30:37.653522 http://www.ipostparcels.com/parcel-delivery/abot-ipostparcels 2018-03-14 16:30:42.716842 http://www.ipostparcels.com/parcel-delivery/parcel-delivery-rates 2018-03-14 16:30:47.762127 http://www.ipostparcels.com/parcel-delivery/parcel-collection-and-delivery 2018-03-14 16:30:52.809792 http://www.ipostparcels.com/parcel-delivery/post-for-a-post 2018-03-14 16:30:57.876936 http://www.ipostparcels.com/parcel-delivery/discont-codes-and-offers 2018-03-14 16:31:02.947123 http://www.ipostparcels.com/corier/ebay-corier-service #!/usr/bin/python from bs4 import BeautifulSoup import urllib2 import pycurl from io import BytesIO import os import re import sys import random from datetime import datetime links = [] while True: with open("topdomains3.txt", "r") as f: domains = list(f) joker=random.randint(1, len(domains)) for i in domains[joker:len(domains)]: i=i.replace("\\n", "") i=i.replace("None", "") i=i.rstrip() print i try: c = pycurl.Curl() c.setopt(c.URL, i) c.setopt(pycurl.TIMEOUT, 3) c.setopt(c.FOLLOWLOCATION, True) c.setopt(c.MAXREDIRS , 5) try: i='http://' + i html_page = urllib2.urlopen(i) soup = BeautifulSoup(html_page, 'html5lib') except Exception,e: print e continue for link in soup.findAll('a', attrs={'href': re.compile("^http")}): links.append(link.get('href').replace("u", "")) for a in links: try: print "----------------------------------------…
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85581417
answer count: 0
has comment: http://stackoverflow.com/comment/85581272
type: UnansweredQuestion

http://stackoverflow.com/comment/85578550
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49286784
score: 0
has text: One more thing: It may be easier to work out the complexity in terms of the length of the final list (i.e., the total number of elements) rather than the length of the initial list and the depth. (But I'm pretty sure you do still need the depth, to handle the complexity of the `[[[[[[[[[[0]]]]]]]]]]` case, which obviously isn't any function of either the initial length 1 or the final length 1.)

http://stackoverflow.com/q/49344582
has title: Python: How do I lock an object until all threads have done a thing
has comment: http://stackoverflow.com/comment/85689536
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85689497
accepted answer: http://stackoverflow.com/a/49344765
score: 1
has answer: http://stackoverflow.com/a/49344765
has body: I am writing a simple threaded server that will send a message to all clients. I have an object that is reset after posting the change message, however I am having a hard time figuring out how to reset that object only after all threads have posted the change message. To add some context to the problem. I am building a multi user Tkinter python app which connects to a remote database to retrieve information and the application needs to know when data changes so that when a user updates data, all other running instances of the app will get the update. From what I understand, MySQL does not support asynchronous application updates. Instead of running a query every 5 seconds on the database to see if there is a change, I am putting this code server side so that it will send a message to a socket on the client that a change has occurred on the database. The main loop is just a dummy that will simulate a change Here is my code: import socket, threading, time, select, os class dbMonitor: isDBAltered = False def postChange(self): self.isDBAltered = True def __str__(self): return str(self.isDBAltered) class ThreadedServer(object): def __init__(self, port,dbMon): self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.setblocking(0) self.sock.bind((socket.gethostname(), self.port)) self.dbMon = dbMon def listen(self): self.sock.listen(100) read_list = [self.sock] while True: read,write,error = select.select(read_list,[],[],1) for s in read: if s is self.sock: client, address = self.sock.accept() client.settimeout(60) threading.Thread(target = self.listenToClient, args = (client,address)).start() def listenToClient(self, client, address): read_list = [client] size = 1024 while True: response = b'Ack' if self.dbMon.isDBAltered: response = b'CHANGE' try: client.send(response) except: client.close() return False self.dbMon.isDBAltered = False read,write,error = select.select(read_lis…
favorite count: 0
type: Question
tagged with: sockets
tagged with: multithreading
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/comment/85707427
type: QuestionComment
comment on: http://stackoverflow.com/q/49352067
has text: I think images that are similar to the bad result are nearly impossible to work on. 6222 image can be still possible to extract something from, but the other 2 are very very hard.
score: 0
type: Comment

http://stackoverflow.com/q/49407037
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85815186
tagged with: list
has comment: http://stackoverflow.com/comment/85837015
score: 0
tagged with: permutation
has body: I have a recursive code to compute unique permutations. However, this gives me a segmentation fault (due to an exceeded stack limit). How do I convert it into an iterative code. I have followed online tutorials on converting recursive code to iterative, but my iterative code doesn't work. class unique_element: def __init__(self,value,occurrences): self.value = value self.occurrences = occurrences def perm_unique(elements): eset=set(elements) listunique = [unique_element(i,elements.count(i)) for i in eset] u=len(elements) return perm_unique_helper(listunique,[0]*u,u-1) def perm_unique_helper(listunique,result_list,d): if d &lt; 0: yield list(result_list) else: for i in listunique: if i.occurrences &gt; 0: result_list[d]=i.value i.occurrences-=1 for g in perm_unique_helper(listunique,result_list,d-1): print g yield g i.occurrences += 1
linked to: http://stackoverflow.com/q/6284396
type: Question
has title: Efficient iterative unique permutation generator of a list with many repetitions
answer count: 0

http://stackoverflow.com/q/49352249
has comment: http://stackoverflow.com/comment/85706230
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49353887
tagged with: time
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/49353887
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85707732
has title: tkinter clock function error: NameError
has comment: http://stackoverflow.com/comment/85704535
type: AnsweredQuestion
has body: I have this function for a clock label in tkinter: def update_clock(): global clock now = time.strftime("%H:%M:%S") clock.configure(text=now) clock.after(1000, update_clock) I am getting this error: NameError: name 'update_clock' is not defined In all of the clock tutorials I have read they have the name of the function after the 1000 in that last line. How can I fix this error?
downvote count: 3
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85669088
has text: Oh yes, you're absolutely right. Moviepy has proven to be a library with full of surprising difficulties, and I've often settled to the first solution that has worked, even if isn't very elegant. I made the change to my script, the same colour distortion/whitening problem still exists (unsurprisingly).
comment on: http://stackoverflow.com/q/49323977
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49376930
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: argparse
answer count: 1
type: Question
tagged with: cx-freeze
has title: argparse causing error in cx_Freeze app
has body: I made two python programs A and B where both are packaged by cx_Freeze into different exe files. Program A is the main program and B sits inside the "Main Program folder/dummy_dist" A launches B using subprocess.run() like the following subprocess.run(["dummy_dist/dummy.exe", "--mode 1", "--pid " + str(os.getpid()), "--sid " + sid], cwd="dummy_dist") when I run this, the following error shows up The only part of the error which is my code is the "line 45" which is args = parser.parse_args() and just for reference the code where I use argparse is this parser = argparse.ArgumentParser(description="-") parser.add_argument('--mode', dest="mode", metavar='Program Mode', type=str, help="") parser.add_argument('--pid', dest="pid", metavar='PID', type=str, required=False) parser.add_argument('--sid', dest="sid", metavar='SESSION_ID', type=str, help="Active SESSION_ID", required=False) The program runs fine when I run it as a .py file. Can you guys please tell me what is wrong?
has answer: http://stackoverflow.com/a/49407809

http://stackoverflow.com/comment/85582260
type: Comment
comment on: http://stackoverflow.com/q/49289429
type: QuestionComment
score: 0
has text: @blueberryfields I am relatively new to this but thought that having both installed would allow me to write for both x32 and x64 systems?

http://stackoverflow.com/comment/85812354
type: Comment
type: QuestionComment
score: 0
has text: Given that `TypeError: vars() argument must have __dict__ attribute`, which is not the case of `a.someval` here, I would still be interested to see how exactly it would work in such case...? Thanks for the ideas!
comment on: http://stackoverflow.com/q/49405240

http://stackoverflow.com/a/49399638
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85800609
has body: Just use collections.defaultdict that you already imported: In [21]: from collections import defaultdict ...: result = defaultdict(lambda: defaultdict(list)) ...: for d in players: ...: for k,v in d.items(): ...: result[d['school']][k].append(v) ...: In [22]: result Out[22]: defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'ASU': defaultdict(list, {'homestate': ['AL'], 'name': ['jack'], 'position': ['QB'], 'school': ['ASU']}), 'WSU': defaultdict(list, {'homestate': ['CT', 'MD'], 'name': ['matt', 'john'], 'position': ['RB', 'LB'], 'school': ['WSU', 'WSU']})})
type: Answer
has comment: http://stackoverflow.com/comment/85800533
answers question: http://stackoverflow.com/q/49399471
score: 3
has comment: http://stackoverflow.com/comment/85800548

http://stackoverflow.com/q/49429336
has comment: http://stackoverflow.com/comment/85860187
has title: TemplateSyntaxError at Could not parse the remainder
has answer: http://stackoverflow.com/a/49429951
accepted answer: http://stackoverflow.com/a/49429951
tagged with: django
tagged with: javascript
has body: In my django app I am trying to get the name of image to be loaded from JSON variable.In its HTML key there is name of the image to be displayed. I am reading that key and appending in the static path.But I get this error TemplateSyntaxError at Could not parse the remainder JSON var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; My loop used for extracting image name and other required parameters for(var index=0;index&lt;json.length;index++) { gridster.add_widget('&lt;li class="new" &gt;&lt;button class="delete-widget-button" style="float: right;"&gt;-&lt;/button&gt;&lt;img src="{% static \'images/'+json[index].html+'\' %}"&gt;&lt;/li&gt;',json[index].size_x,json[index].size_y,json[index].col,json[index].row); }; Check in this loop the variable I get var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for(var index=0;index&lt;json.length;index++) { console.log('&lt;li class="new" &gt;&lt;button class="delete-widget-button" style="float: right;"&gt;-&lt;/button&gt;&lt;img src="{% static \'images/'+json[index].html+'\' %}"&gt;&lt;/li&gt;',json[index].size_x,json[index].size_y,json[index].col,json[index].row); };
tagged with: python
has comment: http://stackoverflow.com/comment/85860491
type: AnsweredQuestion
score: 0
tagged with: django-templates
has comment: http://stackoverflow.com/comment/85860493
has comment: http://stackoverflow.com/comment/85860120
answer count: 1
has comment: http://stackoverflow.com/comment/85860323
tagged with: jinja2
has comment: http://stackoverflow.com/comment/85860596
type: Question
has comment: http://stackoverflow.com/comment/85860416

http://stackoverflow.com/comment/85799708
type: AnswerComment
score: 1
has text: See the modified answer.
comment on: http://stackoverflow.com/a/49398915
type: Comment

http://stackoverflow.com/comment/85920062
has text: thx, I tried your suggestion with "rolling(3)" apply_by_multiprocessing(df_total_2, square, axis=0, workers=4) Out[76]: a b 0 NaN NaN 1 NaN NaN 2 1.0 1.0 3 NaN NaN 4 NaN NaN 5 4.0 4.0 6 NaN NaN 7 NaN NaN 8 NaN NaN 9 NaN NaN Any idea, thank you?
score: 0
comment on: http://stackoverflow.com/a/49416355
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49342847
has title: how to install spacy for python 3.4, windows 7?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85686596
tagged with: python
has answer: http://stackoverflow.com/a/49343576
tagged with: installation
tagged with: spacy
score: 0
answer count: 1
has body: I am trying to install the spacy python library for python 3.4 on windows 7. i keep getting install errors (the important-looking error messages are below). I installed it for 2.7, but I can't seem to install it for 3.4. I tried doing: pip3.4 install -U spacy But it does not seem to work. Does anybody have any ideas? I'm trying to avoid crazy system surgery. There must be some simple way to do this. Warning: The nvcc binary could not be located in your $PATH. For GPU capability, either add it to your path, or set $CUDA_HOME warning: no files found matching '*.cpp' under directory 'include' warning: no files found matching 'buildbot.json' *********************************************************** WARNING: One of the following dependencies is unresolved: ctypes &gt;=1.0.1 readline &gt;=1.7.1 *********************************************************** error: Unable to find vcvarsall.bat Cleaning up... Command C:\Python34\python.exe -c "import setuptools, tokenize;file='C:\Users\joe\AppData\Local\Temp\pip_build_joe\spacy\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\joe\AppData\Local\Temp\pip-sxqy1vof-record\install-record.txt --single-version-externally-managed --compile failed with error code 1 in C:\Users\joe\AppData\Local\Temp\pip_build_joe\spacy Storing debug log for failure in C:\Users\joe\pip\pip.log
type: Question

http://stackoverflow.com/q/49366585
has answer: http://stackoverflow.com/a/49366675
favorite count: 0
has answer: http://stackoverflow.com/a/49367209
has body: I have a dataframe: d = {'col1':['2q','48', '48-49']} test = pd.DataFrame(d) col1 0 2q 1 48 2 48-49 And a dictionary for mapping: mupcs_to_pc_mapping = {'24': ['48-49', '48', '49'], #M2 '23': ['50-51', '50', '51'], #M3 '22': ['52-53', '52', '53'], #M4 '21': ['54-55', '54', '55'], #M5 } I would like to test each value of the test dataframe to see if it exists in the mupcs_to_pc_mapping dict values. So the final result is something like: 0 False 1 True 2 True I tried a variation of: test['col1'].isin(mupcs_to_pc_mapping.values()) and test['col1'].any(value for value in mupcs_to_pc_mapping.values()) but both of them result in an error. Does anyone know what is wrong with my code?
type: AnsweredQuestion
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/49366700
accepted answer: http://stackoverflow.com/a/49366642
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/49366642
type: Question
has title: Compare dataframe to list of dictionary values
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49366700

http://stackoverflow.com/comment/85708594
comment on: http://stackoverflow.com/a/49353831
type: Comment
has text: Yes sure ! So I try to open Register.html and i get the error. This is the full trace http://dpaste.com/29NKN68
type: AnswerComment
score: 0

http://stackoverflow.com/q/49289081
has title: Killing/Creating new session everytime a request is sent?
tagged with: python
score: 0
has body: I am fairly new with python and have been playing with sending and getting requests with the requests module. However, I cannot figure out how to either kill or create a new session everytime a POST request is made. Here is the function I am using: def sendRequestTest(): try: session.headers.update({'x-csrftoken': req.cookies['csrftoken']}) login_data = {'email': EMAIL, 'password': PASSWD, 'username': USERNAME, 'first_name': NAME} login = session.post(SIGNUP_URL, data=login_data, allow_redirects=True) session.headers.update({'x-csrftoken': login.cookies['csrftoken']}) cookies = login.cookies login_text = json.loads(login.text) print(login_text) except: print("An connection error has occured.") I have tried adding session.close() to the end of the function, but got an indentation error. Any help is greatly appreciated.
answer count: 1
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85582362
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49291000

http://stackoverflow.com/a/49379939
score: 2
accepted answer of: http://stackoverflow.com/q/49379778
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85761881
has comment: http://stackoverflow.com/comment/85760947
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85764509
answers question: http://stackoverflow.com/q/49379778
has body: Shared Folder via SFTP Do you mean that you don´t have XMLRPC available? You can share a local server folder (by sftp for instance) and the third party application can leave the files there temporary. When you process the file you can already delete it. Alternative to XMLRPC >> JSONRPC and Controllers You can use controllers as well, but you need to use JSONRPC here. Maybe you can include the plain xml file into one JSON field. But I think controllers were built only for OpenERP internal purposes. Check the problems I had about this: question1, question2 Note: Take into account that with this solution you will need to use only one database in the OpenERP instance. Process XML File If you want to read the XML file you can use the lxml library. Check this other answer: After building an Element instance e from the XML, e.g. with the XML function, or by parsing a file with something like import xml.etree.ElementTree e = xml.etree.ElementTree.parse('thefile.xml').getroot() or any of the many other ways shown at ElementTree, you just do something like: for atype in e.findall('type'): print(atype.get('foobar'))

http://stackoverflow.com/q/49394329
type: UnansweredQuestion
has title: Error with curdir (ntpath) python
tagged with: python
has body: I have been working with the ntpath, curdir feature of python but it is not working! Note that if I have a direct path to the data files, no error occurs. I need to be using relative paths with the project and cannot be hard coding my files in the project. Here's my error: Parent suite setup failed: File not found error :.\DataSetFiles\uOpen Data Extract updated - CID94746.xlsx doesnot exist At script start up, here's what happens: __init__.robot *** Settings *** Resource ../Generic_Configurations/Import_File.robot Import_File.robot *** Settings *** Variables ../Generic_Configurations/ConfigurationsFile.py ConfigurationsFile.py from ntpath import curdir DataExtractFile = curdir + '\\DataSetFiles\\uOpen Data Extract updated - CID94746.xlsx' DataSheetFile = curdir + '\\DataSetFiles\\DataSheet.xlsx' I'm scripting robot framework with the Eclipse IDE. Any comments/suggestions appreciated!
has comment: http://stackoverflow.com/comment/85798852
has comment: http://stackoverflow.com/comment/85792901
score: 0
has answer: http://stackoverflow.com/a/49413690
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85790371
type: Question
has comment: http://stackoverflow.com/comment/85791567
tagged with: robotframework

http://stackoverflow.com/a/49408182
answers question: http://stackoverflow.com/q/49408112
score: 1
upvote count: 1
has body: Try this: Use of *args and **kwargs **kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. def manyArgs(*arg): print("Was called with ", len(arg), " arguments: ", arg) def main(): manyArgs() if __name__ == "__main__": main() if i run this without any arguments it prints the following line: Was called with 0 arguments: ()
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85659974
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49328934
type: AnswerComment
has text: Your answer is incomplete without a solution.

http://stackoverflow.com/q/49397732
linked to: http://stackoverflow.com/q/2435256
upvote count: 1
favorite count: 0
tagged with: fuzzywuzzy
type: Question
has body: I'm doing a similar project to this: Data matching algorithm Where, I have one data frame (dataset1) with customer details, without a special unique ID, which is then matched against data frame 2 (dataset2) which has the same fields along with a special unique ID. Example: Dataset1 columns include: Title, Last name, First name, Middle/other name, address, DOB, sex, health care number dataset2 columns include: Unique ID, Title, Last name, First name, Middle/other name, address, DOB, sex, health care number My plan: My data set 1 is ~500,000 rows w/ 11 or so columns - the row count can be split if required. Data set 2 is ~2,000,000 Based on matching criteria from the business eg. >5 columns must match, and potentially a fuzzy component eg names that are hyphenated (inc. other special characters) in one data set but not in the other. Based on the approximate match, this ID, and the fields from data set 2 is copied into data set 1 in adjacent columns, along with an overall match %. Then overall match % ranges can be extracted and inspected by the business. I plan on using Panda with Fuzzywuzzy. I'm having trouble planning my technical approach on the logic of my code. SHould I look through the first field for matches, then filter down on the next column, and so on? I think so, but how does the loop operate moving across the columns in the two comparative data sets? do I need to write each operation of comparison back into the data set for storage or can it be kept else where? the alternative that might work, is that I concatenate all the columns into a single column, and those are matched, and returned with the matched ID, other fields and the matching %. I'm looking for the best direction to head into, along with general logic on the best way to do it.
has answer: http://stackoverflow.com/a/49415357
type: UnansweredQuestion
tagged with: python
has title: data matching multiple columns with fuzzy matching criteria
tagged with: pandas
score: 1
answer count: 1
tagged with: dataset
downvote count: 0

http://stackoverflow.com/comment/85732416
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49365194
has text: Thank you so much, it works! Just a quick question, it seems after assigning tPrice to the function call I have lost the looping functionality. I run the code once, complete Order#1, then I say yes to repeat and complete Order#2. However after that, the program just ends, I do not quite get the option to choose an Order#3. How would I go about fixing that?

http://stackoverflow.com/q/49319181
tagged with: iteration
type: Question
has comment: http://stackoverflow.com/comment/85639439
tagged with: qgis
has comment: http://stackoverflow.com/comment/85640930
tagged with: python
has body: I have two polygon shapefiles with several objects. Each object in both shapefiles has a given ID number. Now I want to clip the object with ID=1 in Shapefile A with the object with ID=1 in Shapefile B. However each shapefile has about 5000 objects, so I would like to create a Python script via the QGIS graphical modeler. I know how to use the graphical modeler to clip objects and stuff, but I cannot find any iteration option within the modeler. Is there an option to do so or how can I implement an iteration directly into the script to get the wanted clip results? Thanks in advance!
tagged with: qpython
has comment: http://stackoverflow.com/comment/85639411
score: 0
answer count: 0
type: UnansweredQuestion
has title: Clip Shapefiles via Iteration in QGIS Python Script

http://stackoverflow.com/q/49313324
has body: I have a python script which captures repo command. import subprocess processing(commandforrepo) def processing(repocmd): process = None process = subprocess.Popen(repocmd, stdout=subprocess.PIPE, stderr=None, shell=True) process.communicate() In the particular command, I am trying to parse a list of repocmd to compare two branches and print out the differences "repo forall $(repo forall -c 'echo $REPO_PROJECT')\ -c 'git log --abbrev-commit --pretty=oneline --no-merges \ --cherry-pick --left-only HEAD...$REPO_RREV'" Attempted to run the script on the terminal but the command did not get executed. However, when this command is issued on the terminal, it produces a list of differences between the two branches. Any clue as to what is missing?
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/37561240
tagged with: git
score: 2
has comment: http://stackoverflow.com/comment/85628320
answer count: 1
has answer: http://stackoverflow.com/a/49313863
has title: Python repo popen could not work in python script but works on the terminal
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/85924478
comment on: http://stackoverflow.com/a/49458736
type: Comment
has text: Awesome! it worked great. Would you mind adding your comment to your answer and I will accept it. Would be also great if you can explain what does the "1" represent in both the "reshape" and the "input_shape". Is this the dimension of the input? [num_vals x 1 ]?
type: AnswerComment
score: 0

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/49383479
tag name: google-oauth
tags question: http://stackoverflow.com/q/49351659
tags question: http://stackoverflow.com/q/49331054
tags question: http://stackoverflow.com/q/49374112

http://stackoverflow.com/comment/85610183
comment on: http://stackoverflow.com/q/49302170
type: Comment
has text: I've edited my question to load the cogs outside the ready events. Note how `client2` loads the cog second, meaning `client2` is the bot that will respond to !add and ~add.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85721304
has text: Structured arrays - https://docs.scipy.org/doc/numpy-1.14.0/user/basics.rec.html address this.
comment on: http://stackoverflow.com/a/49360139
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85812511
type: QuestionComment
comment on: http://stackoverflow.com/q/49405599
score: 1
type: Comment
has text: `key` iterates over the values in `('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')`. The 2nd answer in that question has some nice links to the documentation that are worth checking out.

http://stackoverflow.com/comment/101019990
type: AnswerComment
comment on: http://stackoverflow.com/a/49357670
has text: Does the model "remember" what was fit, so model.predict(x) works afterwards? Is the .predict(x) function the only thing needed after applying model training to get predictions?
score: 0
type: Comment

http://stackoverflow.com/comment/85742144
score: 0
type: AnswerComment
has text: @JijiAR what I read in your comment is `''` where it should be `' '`. I changed the code in the answer, try with that please.
comment on: http://stackoverflow.com/a/49363716
type: Comment

http://stackoverflow.com/comment/85806609
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49397920
type: QuestionComment
has text: I fear that this is just a very nice example of pandas going crazy with date formatting. Yet, would you be able to use a [mcve] in the question, such that this can be reproduced? ([How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples))

http://stackoverflow.com/a/49288150
type: AcceptedAnswer
has body: Here are the changes I made which solves my problem. It allows me to edit the string when called from the 'narrow' method. def otherImages(self): return["&lt;div id='menu_button'&gt;&lt;a href='/narrow'&gt;&lt;img src='../images/menu_button.png'&gt;&lt;/a&gt;&lt;/div&gt;"] def narrow(self): try: self.reply() self.contentList('onlineSection') # removed onlineSectionv for words in self.otherImages(): words = words.replace("/narrow", "/") self.wfile.write(bytes(words, "utf8")) return
score: 0
has comment: http://stackoverflow.com/comment/85581432
accepted answer of: http://stackoverflow.com/q/49287434
has comment: http://stackoverflow.com/comment/85580939
type: Answer
answers question: http://stackoverflow.com/q/49287434

http://stackoverflow.com/a/49418111
answers question: http://stackoverflow.com/q/49417311
has body: As suggested by @abarnert, the first port of call is find out why your data is coming across as strings and try and rectify that problem. However, if this is beyond your control, you can use ast.literal_eval as below. import pandas as pd from ast import literal_eval df = pd.DataFrame({'helpful': ['[2, 4]', '[0, 0]', '[0, 1]', '[7, 13]', '[4, 6]']}) res = pd.DataFrame(df['helpful'].map(literal_eval).tolist(), columns=['helpful', 'not_helpful']) # helpful not_helpful # 0 2 4 # 1 0 0 # 2 0 1 # 3 7 13 # 4 4 6 Explanation From the documentation, ast.literal_eval performs the following function: Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49417311
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85771180
score: 0
type: Comment
type: AnswerComment
has text: got it, my answer won't handle such case. Need to update it. Thanks.
comment on: http://stackoverflow.com/a/49384063

http://stackoverflow.com/q/49295311
score: 51
answer count: 5
has title: what is the difference between Flatten() and GlobalAveragePooling2D() in keras
upvote count: 51
possible better answer: http://stackoverflow.com/a/65860888
tagged with: python
has answer: http://stackoverflow.com/a/63502664
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75123681
tagged with: keras-layer
tagged with: deep-learning
has body: I want to pass the output of ConvLSTM and Conv2D to a Dense Layer in Keras, what is the difference between using global average pooling and flatten Both is working in my case. model.add(ConvLSTM2D(filters=256,kernel_size=(3,3))) model.add(Flatten()) # or model.add(GlobalAveragePooling2D()) model.add(Dense(256,activation='relu'))
has answer: http://stackoverflow.com/a/56749019
downvote count: 0
accepted answer: http://stackoverflow.com/a/49299921
tagged with: keras
has answer: http://stackoverflow.com/a/65860888
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49299921

http://stackoverflow.com/comment/85751393
type: QuestionComment
score: 1
has text: @MohamedElzarei I am trying to avoid that because I don't want to change the optimizer parameters such as the learning rate (which is different from the initial learning rate due to decay).
type: Comment
comment on: http://stackoverflow.com/q/49374511

http://stackoverflow.com/a/49297090
accepted answer of: http://stackoverflow.com/q/49296665
has comment: http://stackoverflow.com/comment/85595989
answers question: http://stackoverflow.com/q/49296665
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85596015
score: 1
has body: EDIT Here is a better solution. It basically partitions the number of steps into the amount of variables to generate all the valid combinations: def partitions(n, k): if n &lt; 0: return -partitions(-n, k) if k &lt;= 0: raise ValueError('Number of partitions must be positive') if k == 1: return np.array(n) ranges = np.array([np.arange(i + 1) for i in range(n + 1)]) parts = ranges[-1].reshape((-1, 1)) s = ranges[-1] for _ in range(1, k - 1): d = n - s new_col = np.concatenate(ranges[d]) parts = np.repeat(parts, d + 1, axis=0) s = np.repeat(s, d + 1) + new_col parts = np.append(parts, new_col.reshape((-1, 1)), axis=1) return np.append(parts, (n - s).reshape((-1, 1)), axis=1) def make_grid_part(n, step): num_steps = round(1.0 / step) return partitions(num_steps, n) / float(num_steps) print(make_grid_part(3, 0.33333)) Output: array([[ 0. , 0. , 1. ], [ 0. , 0.33333333, 0.66666667], [ 0. , 0.66666667, 0.33333333], [ 0. , 1. , 0. ], [ 0.33333333, 0. , 0.66666667], [ 0.33333333, 0.33333333, 0.33333333], [ 0.33333333, 0.66666667, 0. ], [ 0.66666667, 0. , 0.33333333], [ 0.66666667, 0.33333333, 0. ], [ 1. , 0. , 0. ]]) For comparison: %timeit make_grid_part(5, .1) &gt;&gt;&gt; 338 µs ± 2.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit make_grid_simple(5, .1) &gt;&gt;&gt; 26.4 ms ± 806 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) make_grid_simple actually runs out of memory if you push it just a bit further. Here is one simple way: def make_grid_simple(n, step): num_steps = round(1.0 / step) vs = np.meshgrid(*([np.linspace(0, 1, num_steps + 1)] * n)) all_combs = np.stack([v.flatten() for v in vs], axis=1) return all_combs[np.isclose(all_combs.sum(axis=1), 1)] print(make_grid_simple(3, 0.33333)) Output: [[ 0. 0. 1. ] [ 0.33333333 0. 0.66666667] [ 0.66666667 0. 0.33333333] [ 1. 0. 0. ] [ 0. 0.33333333 0.66666667] [ 0.33333333 0.33333333 0.33333333] [ 0.66666667 0.33333333 0. ] [ 0. 0.66666667 0.33333333] [ 0.33333333 0.66666667 0. ] [ 0. 1. 0.…
type: Answer
has comment: http://stackoverflow.com/comment/85599860

chemistry
type: Tag
tag name: chemistry
tags question: http://stackoverflow.com/q/49374685

http://stackoverflow.com/a/49328156
has comment: http://stackoverflow.com/comment/85700016
has body: There are a number of problems here, but your first big issue is that you're using non-unique ids. Make your Ids unique and you can properly reference the value of your hidden input, fix your jQuery listener to look like $('#actually_uniqe_id').on('change', function (){...} instead of the mess it is currently, you can get your value correctly with var rating = document.getElementById("#actually_unique_id").value; and modify your posted data to convey both the id and rating like data: {'id': {{result.id}}, 'rating': rating}. Never use non-unique IDs. Because of confusion surrounding this point, your current jQuery event listener is meaningless, and your rate_id variable is undefined because document.getElementById("{{result.id}}") fetches the first reference of that id, which is a div that has no attribute 'value'. Edit: Also, since you have a loop generating potentially lots of rating inputs, drop the event listener for something like: &lt;input id="value_{{result.id}}" type="hidden" onchange="updateStars('{{result.id}}')" /&gt; and &lt;script type="text/javascript"&gt; function updateStars(id) { var rating = document.getElementById("value_" + id).value; $.ajax({ url : '/dashboard', type : 'POST', data : {'id': '{{result.id}}', 'rating': rating} }); &lt;/script&gt;
has comment: http://stackoverflow.com/comment/85659158
has comment: http://stackoverflow.com/comment/85659918
has comment: http://stackoverflow.com/comment/85682511
has comment: http://stackoverflow.com/comment/85674500
has comment: http://stackoverflow.com/comment/85701427
has comment: http://stackoverflow.com/comment/85706772
has comment: http://stackoverflow.com/comment/85665294
has comment: http://stackoverflow.com/comment/85701261
has comment: http://stackoverflow.com/comment/85680929
has comment: http://stackoverflow.com/comment/85676190
type: Answer
has comment: http://stackoverflow.com/comment/85700921
has comment: http://stackoverflow.com/comment/85659464
has comment: http://stackoverflow.com/comment/85661938
answers question: http://stackoverflow.com/q/49311103
has comment: http://stackoverflow.com/comment/85666518
has comment: http://stackoverflow.com/comment/85677962
score: 0
has comment: http://stackoverflow.com/comment/85679475
has comment: http://stackoverflow.com/comment/85698688
accepted answer of: http://stackoverflow.com/q/49311103
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85699096

http://stackoverflow.com/a/49354311
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49343335
accepted answer of: http://stackoverflow.com/q/49343335
type: Answer
has body: It looks like some other package that I had previously installed broke my system-wide Python. Here's how I fixed in order to install package xyz: Browsed /usr/local/lib/python2.7/dist-packages in search for occurences of "gitignore" Deleted folders of all matching occurences (including setuptools_git itself that matches "gitignore") pip install setuptools_git In package xyz, rm -rf dist/ build/ *.egg-info/ Reinstall package xyz, which now succeeds to install Use virtual envs as a lesson
downvote count: 0

http://stackoverflow.com/a/49294722
downvote count: 0
has body: In python when we take input through input() function, by default it's a string. You can check it's type by- print(type(VARIABLE)) that's why your program doesn't work right, because of the condition on line 7. You are comparing string variable to int. Here is the modified program. print("Hello World") myName = input("Whats your name?") myVar = int(input("Enter a number: ")) print(myName) print(myVar) if(myName == "Ben" and myVar == 5): print("You are cool") elif(myName == "Max"): print("You are not cool") else: print("Nice to meet you") Also, since you're new to python try to learn more about data-types in python. Few links link1, link2, link3 that'll help in understanding data-types in python.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49292811

http://stackoverflow.com/q/49366282
duplicate of: http://stackoverflow.com/q/31460267
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 1
tagged with: opencv
duplicate of: http://stackoverflow.com/q/31590499
has body: I am currently trying a code which I saw in a youtube tutorial(I specified it in my Github link from above). I see that there are two masks applied but I tried several RGB values and I still can`t get the lighr green pixels(which are exposed to more light). I would like to know what masks should I apply in my code and how can I tell which one is good in any given color extraction. image_blur = cv2.GaussianBlur(image, (7, 7), 0) #t unlike RGB, HSV separates luma, or the image intensity, from # chroma or the color information. #just want to focus on color, segmentation image_blur_hsv = cv2.cvtColor(image_blur, cv2.COLOR_RGB2HSV) # Filter by colour # 0-10 hue #minimum red amount, max red amount min_green = np.array([36, 0, 0]) max_green = np.array([70, 255,255]) #layer mask1 = cv2.inRange(image_blur_hsv, min_green, max_green) #birghtness of a color is hue # 170-180 hue min_green2 = np.array([188,0,0]) max_green2 = np.array([208,243,139]) mask2 = cv2.inRange(image_blur_hsv, min_green2, max_green2) #looking for what is in both ranges # Combine masks mask = mask1 + mask2 Here is my link to Github where you can find the pictures and the entire code: https://github.com/andreyy03/PlantsRecognition Thank you!
has answer: http://stackoverflow.com/a/49368762
favorite count: 0
score: -1
has title: What mask should I apply to get all green pixels?
type: Question
downvote count: 2
linked to: http://stackoverflow.com/q/31590499

http://stackoverflow.com/comment/85824895
type: Comment
has text: The fields and column names can be used in any order in the command. Just make sure parameters are listed in the same order as in the command.
comment on: http://stackoverflow.com/a/49405676
type: AnswerComment
score: 0

http://stackoverflow.com/a/49433341
has comment: http://stackoverflow.com/comment/85873958
has comment: http://stackoverflow.com/comment/85873674
score: 1
has body: Since item is in a text file, it is a string, you should convert it to an int before comparing: for item in l1: if item.isdigit(): # if it is a number item = int(item) # convert it to int if item&gt;=9000: l2.append(item) else: item = item+9000 l2.append(item) else: # not a number # do something
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/85875703
accepted answer of: http://stackoverflow.com/q/49433314
answers question: http://stackoverflow.com/q/49433314
type: Answer
upvote count: 2

http://stackoverflow.com/q/49314543
downvote count: 0
has answer: http://stackoverflow.com/a/49314794
has comment: http://stackoverflow.com/comment/85630548
has answer: http://stackoverflow.com/a/49315398
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49316966
has answer: http://stackoverflow.com/a/67496153
score: 5
tagged with: performance
has comment: http://stackoverflow.com/comment/85630500
upvote count: 5
tagged with: numba
tagged with: python
has title: Close form solution for finding a root
answer count: 4
type: AnsweredQuestion
has body: Suppose I have a Pandas Series s whose values sum to 1 and whose values are also all greater than or equal to 0. I need to subtract a constant from all values such that the sum of the new Series is equal to 0.6. The catch is, when I subtract this constant, the values never end up less than zero. In math formula, assume I have a series of x's and I want to find k MCVE import pandas as pd import numpy as np from string import ascii_uppercase np.random.seed([3, 141592653]) s = np.power( 1000, pd.Series( np.random.rand(10), list(ascii_uppercase[:10]) ) ).pipe(lambda s: s / s.sum()) s A 0.001352 B 0.163135 C 0.088365 D 0.010904 E 0.007615 F 0.407947 G 0.005856 H 0.198381 I 0.027455 J 0.088989 dtype: float64 The sum is 1 s.sum() 0.99999999999999989 What I've tried I can use Newton's method (among others) found in Scipy's optimize module from scipy.optimize import newton def f(k): return s.sub(k).clip(0).sum() - .6 Finding the root of this function will give me the k I need initial_guess = .1 k = newton(f, x0=initial_guess) Then subtract this from s new_s = s.sub(k).clip(0) new_s A 0.000000 B 0.093772 C 0.019002 D 0.000000 E 0.000000 F 0.338583 G 0.000000 H 0.129017 I 0.000000 J 0.019626 dtype: float64 And the new sum is new_s.sum() 0.60000000000000009 Question Can we find k without resorting to using a solver?
tagged with: pandas
has answer: http://stackoverflow.com/a/49316966
accepted answer: http://stackoverflow.com/a/49314794

http://stackoverflow.com/comment/85602369
type: Comment
has text: Thanks, regions and points were GeoDataFrames, and adding geometry it worked perfectly !
type: AnswerComment
comment on: http://stackoverflow.com/a/49300259
score: 0

http://stackoverflow.com/q/49305978
favorite count: 0
type: AnsweredQuestion
has title: How to parse tuple data from csv format in pyspark?
has answer: http://stackoverflow.com/a/49308086
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85614509
answer count: 1
tagged with: python
score: -1
has body: The dataset is in CSV format. Every line in this file contains a tuple where the first element is the name of a plant, and the remaining elements are the states in which the plant is found. Example: abelia,fl,nc abelia x grandiflora,fl,nc abelmoschus,ct,dc,fl,hi,il,ky,la,md,mi,ms,nc,sc,va,pr,vi How do I parse this and create a dataframe with columns plants and states(this will contain all the data except for the plant like a list)?
has comment: http://stackoverflow.com/comment/85615216
accepted answer: http://stackoverflow.com/a/49308086
type: Question
has comment: http://stackoverflow.com/comment/85617219
tagged with: apache-spark-sql
upvote count: 0
has comment: http://stackoverflow.com/comment/85614868
linked to: http://stackoverflow.com/q/48427185
tagged with: bigdata
tagged with: pyspark
downvote count: 1

http://stackoverflow.com/comment/126681707
type: Comment
comment on: http://stackoverflow.com/a/49322295
score: 2
type: AnswerComment
has text: The `--output` flag unfortunately only affects the formatting of the journal output displayed after the service status information.

http://stackoverflow.com/comment/85817002
type: QuestionComment
type: Comment
has text: I'm not trying to sort the data. I want to read back the csv file and retain the original format. Since the biases is a list of arrays, i am unable to read back the data as the same list of arrays. It would be helpful if you can give a work around for this problem. Thanks in advance!
score: 0
comment on: http://stackoverflow.com/q/49406747

http://stackoverflow.com/comment/85708431
comment on: http://stackoverflow.com/q/49354014
score: 0
has text: I've added " .split(" ")[0] " next to logs function in the main file(not the one listed there) to resolve the input problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49313125
tagged with: apache-spark
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49315100
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85628205
has answer: http://stackoverflow.com/a/49313304
tagged with: python-3.x
type: AnsweredQuestion
has title: Convert and slice Python string to list?
has body: I am given a raw string which is a path or "direction" to a string in JSON. I need the following string converted to a list containing dictionaries.. st = """data/policy/line[Type="BusinessOwners"]/risk/coverage[Type="FuelHeldForSale"]/id""" The list should look like this paths = ['data','policy','line',{'Type':'BusinessOwners'},'risk','coverage',{"Type":"FuelHeldForSale"},"id"] I then iterate over this list to find the object in the JSON (which is in a Spark RDD) I attempted st.split(\) which gave me st.split('/') Out[370]: ['data', 'policy', 'line[Type="BusinessOwners"]', 'risk', 'coverage[Type="FuelHeldForSale"]', 'CalculationDisplay'] But how do I convert and split items like 'line[Type="BusinessOwners"]' to 'line',{'Type':'BusinessOwners'} ?
tagged with: oop
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/85650394
possible better answer: http://stackoverflow.com/a/49313304
accepted answer: http://stackoverflow.com/a/49313345
answer count: 4
linked to: http://stackoverflow.com/q/36068779
has answer: http://stackoverflow.com/a/49313345
has comment: http://stackoverflow.com/comment/85628149
has comment: http://stackoverflow.com/comment/85628909
score: 0
has answer: http://stackoverflow.com/a/49313412
has comment: http://stackoverflow.com/comment/85628114

http://stackoverflow.com/comment/85850940
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49424968
has text: Possible duplicate of [Dynamic module import in Python](https://stackoverflow.com/questions/301134/dynamic-module-import-in-python)

http://stackoverflow.com/comment/85608420
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49303116
score: 0
has text: You don't need to loop through each character and call `replace`. Just call it on the whole string (like what you do above) and remove that inner for loop. Second `replace` returns the new string, so when you do `letter.replace(...` the result is lost. I would suspect that `contents = contents.replace('"', '').replace("'", '')` is enough to get rid of quotes. If that doesn't work, verify that your quotes are regular ASCII quotes.

http://stackoverflow.com/q/49343822
has comment: http://stackoverflow.com/comment/85688003
has comment: http://stackoverflow.com/comment/85687984
has comment: http://stackoverflow.com/comment/121426446
has comment: http://stackoverflow.com/comment/105242160
tagged with: python
has title: django.db.utils.IntegrityError: null value in column "category" violates not-null constraint
has comment: http://stackoverflow.com/comment/85701956
favorite count: 0
type: Question
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85687938
has comment: http://stackoverflow.com/comment/85688002
answer count: 0
has body: I've deleted this field from my Post model, but it's still bringing up this error when create make a Post instance: return self.cursor.execute(sql, params) File "/home/james/app/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/james/app/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/james/app/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "category" violates not-null constraint When I removed category from my Post model and performed makemigrations &amp; migrate, it succesfully generated this file in my migrations folder: 0002_remove_post_category # -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-03-16 22:56 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('post', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='post', name='category', ), ] so It shouldn't be causing problems any more, but it still is. Any idea why?
upvote count: 2
has comment: http://stackoverflow.com/comment/85688009
type: UnansweredQuestion
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/85687959

command-line-arguments
tags question: http://stackoverflow.com/q/49429412
type: Tag
tags question: http://stackoverflow.com/q/49335880
tags question: http://stackoverflow.com/q/49319484
tag name: command-line-arguments
tags question: http://stackoverflow.com/q/49385767

http://stackoverflow.com/a/49292362
score: 17
has comment: http://stackoverflow.com/comment/85641322
has comment: http://stackoverflow.com/comment/85637987
accepted answer of: http://stackoverflow.com/q/49282078
has body: You need to add renderers for each plot. Check this. Also do not use samey label for both values change the names. from bokeh.models import HoverTool from bokeh.plotting import figure source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime',plot_width=800, plot_height=300) plot1 =plot.line(x='x',y= 'wind',source=source,color='blue') plot.add_tools(HoverTool(renderers=[plot1], tooltips=[('wind',"@wind")],mode='vline')) plot2 = plot.line(x='x',y= 'coal',source=source,color='red') plot.add_tools(HoverTool(renderers=[plot2], tooltips=[("coal","@coal")],mode='vline')) show(plot) The output look like this.
answers question: http://stackoverflow.com/q/49282078
type: AcceptedAnswer
downvote count: 0
upvote count: 17
type: Answer

http://stackoverflow.com/comment/85743428
has text: it print like my print function there `('felix',)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49371033

http://stackoverflow.com/a/49380591
score: 1
has body: You are encoding the string tweet=all_data["text"].encode("utf-8") and then try to run re.findall on it: tweet=" ".join(re.findall("[a-zA-Z]+", tweet)) Try without the encode call
accepted answer of: http://stackoverflow.com/q/49379615
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49379615
type: Answer

http://stackoverflow.com/q/49280574
tagged with: numpy
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
answer count: 1
has title: Efficiently collect data from 2 large DataFrames and merge it in to a numpy array
upvote count: 1
favorite count: 0
type: Question
tagged with: performance
has answer: http://stackoverflow.com/a/49281755
has body: I have 2 large dataframe's which are too big for merge. Both contain user log data for different months. I need to efficiently collect all data for each id, and create an img/array. Example import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler,MinMaxScaler import time n_rows = 90000000 cols = [ 'id','date','d1','d2','d3'] df_march = pd.DataFrame(np.random.randint(1,100, size=(n_rows, len(cols))), index=np.arange(n_rows), columns=cols) df_feb = pd.DataFrame(np.random.randint(1,100, size=(n_rows, len(cols))), index=np.arange(n_rows), columns=cols) What I tried def create_img_for_id(id): start = time.time() df = df_march[df_march.id==id] end = time.time() print 'collecting march data:', end - start start = time.time() df = df.append(df_feb[df_feb.id==id]) end = time.time() print 'appending feb data: ', end - start start = time.time() df = df.sort_values(by=['date'], ascending=[False]) end = time.time() print 'sort', end - start start = time.time() img = StandardScaler().fit_transform(df'd1','d2','d3') end = time.time() print 'fit', end - start return img img = create_img_for_id(8) The result collecting march data: 31.3800001144 appending feb data: 10.9200000763 sort 0.576999902725 fit 0.484999895096 I need to create the img data in batches for learning process. around 526 images each. I need to create it dynamically, due to memory limitation. How can I use groupby for my problem ? or any other efficient way.
score: 1
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/49281755

http://stackoverflow.com/q/49290187
type: Question
has comment: http://stackoverflow.com/comment/85583987
tagged with: arrays
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85608582
has answer: http://stackoverflow.com/a/49315236
has answer: http://stackoverflow.com/a/49290421
has answer: http://stackoverflow.com/a/49290576
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/85598159
answer count: 3
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85588153
tagged with: numpy
has body: Using python/numpy, I can create the 3D array (note the matrix exponential function) I want like so import numpy as np from scipy.linalg import expm a = np.arange(3) B = np.ones((2,2)) C = np.zeros((2,2,3)) for i in range(3): C[:,:,i] = expm(a[i]*B) which yields for C, the 3D array [[[ 1. 4.19452805 27.79907502] [ 0. 3.19452805 26.79907502]] [[ 0. 3.19452805 26.79907502] [ 1. 4.19452805 27.79907502]]] But I'd like to eliminate the loop. Is there any way I can get rid of the for loop? Perhaps by NumPy broadcasting? I had thought of np.kron but can't seem to figure out a good way to reshape so that I can apply the expm function, which requires a square array as an argument.
has title: Using NumPy, create 3D array from function of 1D and 2D without loop

http://stackoverflow.com/a/49315349
score: 0
has body: There's python standart XML DOM processors and there's BeautifulSoup library. Both able to manipulate DOM tree similar to JS.
type: Answer
answers question: http://stackoverflow.com/q/49315139

http://stackoverflow.com/a/49391942
answers question: http://stackoverflow.com/q/49391891
has comment: http://stackoverflow.com/comment/85785427
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49391891
has body: You need to convert to radians first: Try: c = (a**2)+(b**2)-(2*a*b*(math.cos(math.radians(C)))) print(math.sqrt(c)) #5.29866662196

http://stackoverflow.com/a/49285127
type: Answer
accepted answer of: http://stackoverflow.com/q/49285076
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85573239
has comment: http://stackoverflow.com/comment/85573268
has body: Use ManyToMany on project. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') project = models.ManyToManyField(Project) This way one profile can have as many project as he/she wants On your view you can use this field to filter based on project
answers question: http://stackoverflow.com/q/49285076
downvote count: 0
score: 1

http://stackoverflow.com/a/54236136
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49299609
has body: You could use linear layer to project the 600 dimensional space down to 300 before you apply the shared projection. This way you still get the advantage that the entire embedding (possibly) has a non-zero gradient for each mini-batch but at the risk of increasing the capacity of the network slightly.
type: Answer
accepted answer of: http://stackoverflow.com/q/49299609
score: 3
upvote count: 3

http://stackoverflow.com/comment/85728609
type: Comment
has text: Possible duplicate of [Python: BeautifulSoup extract text from anchor tag](https://stackoverflow.com/questions/11716380/python-beautifulsoup-extract-text-from-anchor-tag)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49364097

http://stackoverflow.com/q/49376997
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49377120
has answer: http://stackoverflow.com/a/49377102
tagged with: data-analysis
type: Question
tagged with: pandas
type: AnsweredQuestion
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85754912
score: 1
accepted answer: http://stackoverflow.com/a/49377102
favorite count: 0
has title: Python : Function which works on initial/default values if no parameters are passed
has body: I have defined a function which calculates the mean of a column Test 1 in my dataframe between two time limits. The dataframe is -:- df = pd.DataFrame({'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88, 2.05, 2.98, 3.45, 3.99, 4.06],'Test 1':[5, 9, 4, 6, 4, 1, 6, 8, 2, 9, 3, 9, 4]}) And the function is -:- def custom_mean(x,y): return df.loc[df['Time'].between(x,y), 'Test 1'].mean() The function custom_mean(x,y) calculates the mean between the two time limits x and y. How can I define a function or write a piece of code which does exactly the same thing (calculates mean between two limits) when the parameters are passed and calculates the mean of whole column starting from the very first value till the last if no parameters are passed (e.g. mean of the values corresponding to the time limit from 0.00 to 4.06 in my dataframe)?
tagged with: function
possible better answer: http://stackoverflow.com/a/49377120
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85754950

http://stackoverflow.com/q/49403423
has title: Inserting QlineEdit.text() into Sqlite3 table give an error sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type
has comment: http://stackoverflow.com/comment/85811349
tagged with: pyqt4
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49406218
downvote count: 0
upvote count: 1
score: 1
tagged with: sqlite
answer count: 1
has body: I am using python 2.7 with pyqt4.10 and sqlite3 Db, trying to get the user input from QlineEdit to insert into sqlite3 table that is already created Table structure CREATE TABLE `categories` ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `category_name` TEXT NOT NULL UNIQUE ); And am trying to refresh the list in a Qlistwidget with the new data after adding the input Here is my full code : def proc(): input_user = self.lineEdit.text() conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, )) conn.commit() conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("SELECT category_name FROM categories") category_all = c.fetchall() for items in category_all: self.listWidget.addItem(items) conn.close() As you see i used input_user = self.lineEdit.text() to get the user input from the QlineEdit The error is : Traceback (most recent call last): File "C:\python\townoftechwarehouse\add_category.py", line 63, in proc c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, )) sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
accepted answer: http://stackoverflow.com/a/49406218
favorite count: 0
type: Question

http://stackoverflow.com/comment/85750804
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49374737
type: QuestionComment
has text: `import itertools` `x = 15; y = 10; z = 5` `for i, j, k in itertools.product(range(x), range(y), range(z)): print i, j, k`

http://stackoverflow.com/comment/85881945
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49428061
has text: @NickTo, Python 3.6, GPyOpt 1.2.1, Numpy 1.13

http://stackoverflow.com/comment/85840658
type: QuestionComment
comment on: http://stackoverflow.com/q/49419351
score: 0
has text: edited to show full list
type: Comment

http://stackoverflow.com/q/49318157
has comment: http://stackoverflow.com/comment/85645913
downvote count: 1
favorite count: 0
tagged with: numpy
has body: I have a data set where the gross per day per movie and the production budget is registered. I try to find the payback period per movie with it. This is done my the min{i: 0 &lt; i &lt; Len(gm) and sum from j=0 to i of gm j &gt;= Production Budget} When running this code, the folowing error occur. 'int' object is not subscript able My other code is: for n in range (0, 4798+1): min(sum([grouped['Gross']])&gt;= 'Production Budget' for grouped in range(0, 5285+1)) genre movie Date Gross Days 0 Action 0 2009-12-18 26752099 1 1 Action 0 2009-12-19 25529036 2 2 Action 0 2009-12-20 24744346 3 3 Action 0 2009-12-21 16385820 4 4 Action 0 2009-12-22 16086461 5 genre mid movie_title Release Date Production Budget 0 Action 0 Avatar 2009-12-18 425000000 1 Adventure 2 Pirates of the Caribbean 2007-05-24 300000000 2 Action 3 Spectre 2015-11-06 300000000 Thanks in advance
has comment: http://stackoverflow.com/comment/85645736
has comment: http://stackoverflow.com/comment/85645632
has answer: http://stackoverflow.com/a/49322824
type: Question
has comment: http://stackoverflow.com/comment/85643820
has comment: http://stackoverflow.com/comment/85637544
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85646198
tagged with: pandas
has title: sum variables that depend on a range
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85645947

http://stackoverflow.com/comment/85598979
comment on: http://stackoverflow.com/a/49297838
type: Comment
type: AnswerComment
has text: Well, using a raw query IS a "single-query solution". wrt/ ORMs, Django's has been designed to make the 80% simple cases easy, and leave you with either not-so-trivial solutions and raw queries for the more complex cases. Some other ORMs try to be as complete as possible to cover 100% use cases - technically reimplementing the whole SQL language as Python objects - but end up being practically at least twice more complicated to use for the 80% simple cases.
score: 0

http://stackoverflow.com/comment/88994436
type: QuestionComment
score: 0
has text: @Fxs7576 ..a field on the model such as 'is_completed' from False to True or whatever - some sort of boolean to indicate that all of the info has been entered. I don't know if I've explained it clear enough for someone to implement so let me know if you have any questions!
type: Comment
comment on: http://stackoverflow.com/q/49338302

http://stackoverflow.com/a/49290175
has comment: http://stackoverflow.com/comment/85584373
has body: The bytes type may do just what you want, it transforms a string into an immutable sequence of ascii values. title = 'THEINCREDIBLES' sum(bytes(title.encode())) # 1029 Now what you need is to apply this only to the nested strings in your table. table = [[1, 'THEINCREDIBLES'], [2, 'IRONMAN']] new_table = [[id, sum(bytes(title.encode()))] for id, title in table] # new_table: [[1, 1029], [2, 532]]
type: Answer
has comment: http://stackoverflow.com/comment/85584300
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49290046

http://stackoverflow.com/comment/85781955
comment on: http://stackoverflow.com/a/49387176
type: Comment
has text: @Christoph's solution is a bit neater than mine, so I'd recommend that
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85750401
score: 0
type: AnswerComment
has text: This would work if I was dealing with a package, in my scenario this just leads to ValueError: attempted relative import beyond top-level package
type: Comment
comment on: http://stackoverflow.com/a/49374523

http://stackoverflow.com/comment/85839706
score: 0
comment on: http://stackoverflow.com/q/49419056
type: Comment
has text: One minor thing: Your "W" program passes a `bowling` argument to `game`, which is ignored, and you pass an empty string. Surely this should be the filename, like it is in the "R" program?
type: QuestionComment

http://stackoverflow.com/comment/85578337
has text: Notice that this is not a `NameError` but an UnboundLocalError. When you assign to a variable somewhere later in the same scope, python recognizes this (even before you come to the command!) and thinks the variable is local. You have to explicitly say that the variable is global via `global variable`. Also the `global` in your `config.py` is superflous, the variable is already global.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49287627
score: 0

http://stackoverflow.com/q/49289133
downvote count: 0
has body: I am running Python 2.7 on Ubuntu 16. I have install matplotlib, but I'm getting the following error when I run a Python script. Any idea? Here is the version number for matplotlib Version: 2.2.0 Traceback (most recent call last): File "stock/app.py", line 24, in &lt;module&gt; import scan File "/home/ubuntu/eyefin/stock/scan.py", line 6, in &lt;module&gt; from stock.chart import get_chart File "/home/ubuntu/eyefin/stock/chart.py", line 4, in &lt;module&gt; from matplotlib.finance import candlestick_ohlc ImportError: No module named finance Here is my Python script import os import re from matplotlib.finance import candlestick_ohlc import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib.dates import num2date, date2num import numpy as np import matplotlib.dates import pandas from stock.models import Pricing, Symbol, Peak from stock.utils import Utils def get_chart(symbol_obj, title=None, caption=None): ...
has comment: http://stackoverflow.com/comment/85581522
upvote count: 1
linked to: http://stackoverflow.com/q/44700715
favorite count: 0
has title: Python matplotlib: No module named finance
type: Question
duplicate of: http://stackoverflow.com/q/42373104
tagged with: importerror
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/42373104

http://stackoverflow.com/q/49292383
accepted answer: http://stackoverflow.com/a/49292431
tagged with: python
type: Question
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
has body: I have a large data frame which contains more than million records. I want to split this data frame into four chunks based on customer id, So I tried following script. unique_customer=df['Customer'].unique() n=len(unique_customer) a=n/4 s1=a s2=s1+a s3=s2+a s4=n l1= unique_customer[:s1] l2= unique_customer[s1:s2] l3= unique_customer[s2:s3] l4= unique_customer[s3:s4] df1=df[df['Customer'].isin(l1)] df2=df[df['Customer'].isin(l2)] df3=df[df['Customer'].isin(l3)] df4=df[df['Customer'].isin(l4)] It works fine for smaller data set. But It takes a long time for large data set. Is there any other alternative method to this problem? Sample Data: Input: Customer val1 0 a1 112 1 a2 2 2 a1 11 3 a3 154 4 a4 76 5 a5 12 6 a2 6 7 a4 7 8 a6 33 9 a5 67 10 a3 121 11 a5 21 12 a5 77 13 a4 3 14 a7 21 15 a5 65 16 a6 98 17 a8 45 18 a9 12 Output: df1 Customer val1 0 a1 112 1 a2 2 2 a1 11 6 a2 6 df2 Customer val1 3 a3 154 4 a4 76 7 a4 7 10 a3 121 13 a4 3 df3 Customer val1 5 a5 12 8 a6 33 9 a5 67 11 a5 21 12 a5 77 15 a5 65 16 a6 98 df4 Customer val1 14 a7 21 17 a8 45 18 a9 12
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has title: Effective way to split pandas dataframe
has answer: http://stackoverflow.com/a/49292431

http://stackoverflow.com/q/49313316
has answer: http://stackoverflow.com/a/49317857
score: 1
has comment: http://stackoverflow.com/comment/85629178
has comment: http://stackoverflow.com/comment/85628344
tagged with: kivy
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: debugging
type: UnansweredQuestion
has title: Debug method of logging package isn't working
has body: I have taken input from a form and passed them to this function from the kivy file (on_press property). The form data is fetched properly in the execute function but it won't get logged in myapp.log Here's the code: import logging import selenium class UIf(GridLayout): def execute(self, *args): print("First probe") logging.basicConfig(filename="myapp.log", level = logging.DEBUG, format='%(asctime)s:%(message)s') print("Second probe") for name in args: print("Third probe") logging.debug(name) class MyApp(App): def build(self): return UIf() if __name__ == '__main__': runapp = MyApp() runapp.run()
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85629066
has comment: http://stackoverflow.com/comment/85628415
tagged with: logging

http://stackoverflow.com/comment/85722585
type: QuestionComment
has text: Thanks, I managed to get it working with %cstring_output_allocate_size.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49346490

http://stackoverflow.com/comment/85706230
comment on: http://stackoverflow.com/q/49352249
type: Comment
has text: The code above isn't [mcve]. It's not sufficient to reproduce the error you claim it does while not being minimal either.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85711727
score: 0
comment on: http://stackoverflow.com/a/49355768
type: Comment
type: AnswerComment
has text: Glad I could help. If that answer was helpful feel free to accept it. This will help other users find good answers and will provide you with good reputation that grants you priviledge through the site

http://stackoverflow.com/comment/85719469
comment on: http://stackoverflow.com/q/49358679
type: QuestionComment
has text: I resolved my problem! Instead of using "presence_of_element_located", I used "frame_to_be_available_and_switch_to_it" and switched the 'mainFrame' which happens to have the html data that I needed.
score: 0
type: Comment

http://stackoverflow.com/a/49385217
has comment: http://stackoverflow.com/comment/85773195
has comment: http://stackoverflow.com/comment/85804969
type: Answer
has comment: http://stackoverflow.com/comment/110698076
has comment: http://stackoverflow.com/comment/85771543
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49385159
has comment: http://stackoverflow.com/comment/85777750
has body: Argmax returns the index where the maximum occurs over some dimension. In your case you are taking the argmax over a dimension of length 2, so it returns either a 0 or a 1 for every location in your (3, 512, 512) array. Both options are very dark on the 8-bit scale and will appear black! You have to make sure you display the binary images as binary. I haven't used this library before, but maybe try mode='I'? or some of the other modes here https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes. The return type of that argmax is important.

http://stackoverflow.com/comment/85821372
type: Comment
type: AnswerComment
has text: Many thanks. That solved the problem. Given the formula ∥r∥2=∥Xθ∗−y∥2, how would you know that Xθ∗ required the transpose method?
comment on: http://stackoverflow.com/a/49408861
score: 0

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/49437284

http://stackoverflow.com/comment/128362482
has text: Thank you! Even though `scandir` provides additional information to `listdir`, it still runs faster even for the whole directory (as I understand from this answer, https://stackoverflow.com/questions/59268696/why-is-os-scandir-as-slow-as-os-listdir). Of course, it will run even faster if it doesn't need to scan everything.
type: Comment
comment on: http://stackoverflow.com/a/66481406
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85848700
score: 0
has text: thanks. That's out of my windows abilities, but I trust your expertise in the field.
type: Comment
comment on: http://stackoverflow.com/q/49408302
type: QuestionComment

http://stackoverflow.com/a/49439996
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49439828
type: Answer
answers question: http://stackoverflow.com/q/49439828
has body: The regular expression ((?:\b\w+\b-)?\b\w*archipelag\w*\b(?:'s)?) works for this. If you have other requirements, you may want to modify it further. Note the use of non-capturing groups (?:) to group expressions so that we can then match zero or one of them using ? import re pat = re.compile(r"((?:\b\w+\b-)?\b\w*archipelag\w*\b(?:'s)?)") corpus = "This is my sentence about islands, archipelagos, and archipelagic spaces. I want to make sure that the archipelago's cat is not forgotten. And we cannot forget the meta-archipelagic and protoarchipelagic historians, who tend to spell the plural 'archipelagoes.'" for match in pat.findall(corpus): print(match) prints archipelagos archipelagic archipelago's meta-archipelagic protoarchipelagic archipelagoes Here it is on regex101
score: 1
type: AcceptedAnswer
downvote count: 0

gnu-make
type: Tag
tags question: http://stackoverflow.com/q/49370572
tags question: http://stackoverflow.com/q/49335880
tag name: gnu-make

http://stackoverflow.com/comment/85881042
score: 0
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ aha yep :-) that is it
comment on: http://stackoverflow.com/a/49439285
type: Comment

http://stackoverflow.com/comment/85671636
comment on: http://stackoverflow.com/q/49334585
has text: If the documentation for xlswriter says this is possible, why not report it as a bug on their issue tracker. Is this even possible in Excel? Look at the xlswriter source code. There, three courses of action: take your pick.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85815540
type: Comment
comment on: http://stackoverflow.com/a/49406733
has text: Why did you post this exact question twice?
type: AnswerComment
score: 0

http://stackoverflow.com/a/49286422
answers question: http://stackoverflow.com/q/49286230
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: To fix the above code, whenever you are printing list you can add those to other list (in below code adding them to final_list with extend) and finally return it at end of the function: def pascalstriangle(n): list = [1] final_list = [] for i in range(n): final_list.extend(list) newlist = [] newlist.append(list[0]) for i in range(len(list) - 1): newlist.append(list[i] + list[i + 1]) newlist.append(list[-1]) list = newlist return final_list print(pascalstriangle(3)) Result: [1, 1, 1, 1, 2, 1] One thing you may want to consider is not using list as variable and using somethin like my_list.

http://stackoverflow.com/a/49297520
has comment: http://stackoverflow.com/comment/85720023
accepted answer of: http://stackoverflow.com/q/49282688
type: Answer
score: 6
upvote count: 6
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87050922
downvote count: 0
has comment: http://stackoverflow.com/comment/85633123
answers question: http://stackoverflow.com/q/49282688
has comment: http://stackoverflow.com/comment/87039179
has body: Update 6/4/2020 Well, it seems that somebody created a GitHub Issue and the changes were already merged. Let's see if this is working in the next Bokeh Version Old Answer Research I believe you only can change the logo with toolbar_options like this: toolbar_options=dict(logo='gray') I hope there will more options in the future. I have checked how to achieve what you want (I needed to do it as well) and it seems that the gridplot uses an special toolbar to join all the plot toolbars together: a ProxyToolbar # Make the grid tools = [] rows = [] for row in children: row_tools = [] row_children = [] for item in row: if merge_tools: if item is not None: for plot in item.select(dict(type=Plot)): row_tools = row_tools + plot.toolbar.tools plot.toolbar_location = None if item is None: width, height = 0, 0 for neighbor in row: if isinstance(neighbor, Plot): width = neighbor.plot_width height = neighbor.plot_height break item = Spacer(width=width, height=height) if isinstance(item, LayoutDOM): item.sizing_mode = sizing_mode if isinstance(item, Plot): if plot_width: item.plot_width = plot_width if plot_height: item.plot_height = plot_height row_children.append(item) else: raise ValueError("Only LayoutDOM items can be inserted into Grid") tools = tools + row_tools rows.append(Row(children=row_children, sizing_mode=sizing_mode)) grid = Column(children=rows, sizing_mode=sizing_mode) if not merge_tools: return grid if toolbar_location: proxy = ProxyToolbar(tools=tools, **toolbar_options) toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location) The tools are gathered in a list to assign them to the special toolbar. I don´t see that the default active elements are collected anywhere. Alternative solution So what you could do is to create a toolbar and the gridplot manually, where you can set the attributes you want to the Toolbar class. Check this example I have built: from bokeh.models import Button, ColumnDataSource, Range1d, Toolbar, ToolbarBox from bokeh.models.to…

http://stackoverflow.com/comment/85677962
type: Comment
comment on: http://stackoverflow.com/a/49328156
score: 0
type: AnswerComment
has text: I've tried both '/rate_movie' and '/rate_movie/'. Both return a 404 error

glyph
type: Tag
tag name: glyph
tags question: http://stackoverflow.com/q/49367834

http://stackoverflow.com/q/49371170
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49371247
has comment: http://stackoverflow.com/comment/85743366
has title: Results won't be written into the txt file
tagged with: python
has body: Even though I'm using file.flush() at the end, no data will be written into the txt file. # some essential code to connect to the server while True: try: # do some stuff try: gaze_positions = filtered_surface['gaze_on_srf'] for gaze_pos in gaze_positions: norm_gp_x, norm_gp_y = gaze_pos['norm_pos'] if (0 &lt;= norm_gp_x &lt;= 1 and 0 &lt;= norm_gp_y &lt;= 1): with open('/the/path/to/the/file.txt', 'w') as file: file.write('[' + norm_gp_x + ', ' + norm_gp_y + ']') file.flush() print(norm_gp_x, norm_gp_y) except: pass except KeyboardInterrupt: break What am I doing wrong? Obvisouly I miss something, but I can't figure it out, what it is. Another odd thing: there's even no output for print(norm_gp_x, norm_gp_y). If I put the with open ... in a comment, I'll get the output.
has comment: http://stackoverflow.com/comment/85743449
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85743432
has comment: http://stackoverflow.com/comment/85743963
downvote count: 0
has answer: http://stackoverflow.com/a/49371247
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/85743415
linked to: http://stackoverflow.com/q/6470428

http://stackoverflow.com/q/49287407
tagged with: keras
has answer: http://stackoverflow.com/a/49309394
score: 2
has answer: http://stackoverflow.com/a/49290972
downvote count: 0
has title: Keras/Tensorflow CNN input shape
tagged with: tensorflow
has body: I have a textfile that is ~ 10k lines long. There are always 216 lines describe a fact with a total of 17 values. I want to build a tensor that is 216 lines high, 13 columns wide and about 1000 layers deep. That would be the input. The output would be one line high, 4 columns wide and also about 1000 layers deep. Current status: x_train = x_train.reshape (1308, 13, 216) y_train = y_train.reshape (1308, 4, 216) result = y_train [:,:, 0] Conv: model.add (Convolution2D (1, kernel_size = (13, 5), activation = 'relu', input_shape = (1308, 13, 216))) Afterwards little maxpooling, etc., which should not disturb. I absolutely do not get along with the reshapes rightly. Would be very bad if someone could help me. Current error message: Input arrays should have the same number of samples as target arrays. Found 1 input samples and 1308 target samples. Many Thanks
favorite count: 0
type: Question
answer count: 2
upvote count: 2
tagged with: convolution
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49396292
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85795359
has answer: http://stackoverflow.com/a/49396461
has body: I have django 1.11.5 and celery 4. I want to pass user in view to task (because I can't do this in tasks.py, right?) def form_valid(self, form): form.instance.user = self.request.user dict_obj = model_to_dict(self.request.user) # serialized = json.dumps(dict_obj) # print(serialized) task_number_one.delay(dict_obj['username']) return super().form_valid(form) In celery I got an error: ValueError: invalid literal for int() with base 10: 'my_username'
type: UnansweredQuestion
tagged with: django
tagged with: request
has answer: http://stackoverflow.com/a/49397223
tagged with: celery
tagged with: task
tagged with: python
has comment: http://stackoverflow.com/comment/85795251
has title: django celery 4 - ValueError: invalid literal for int() with base 10

http://stackoverflow.com/q/49319204
has answer: http://stackoverflow.com/a/49320816
has comment: http://stackoverflow.com/comment/85641354
has answer: http://stackoverflow.com/a/49328825
score: 0
tagged with: printing
has title: Printing the minimum and costomizing the outputs
has comment: http://stackoverflow.com/comment/85640446
type: Question
has body: In the following code I print out entire outputs and the minimum of them: l= 4.98648387414 q= 4.96850590047 l= 6.22734941766 8.30807062837 q= 2.50807065862 6.36351958551 l= 6.55113742501 8.91180674608 1.62449083617 q= 6.58695963821 0.0460316539106 6.79113942876 min is= [ 6.55113743 8.91180675 1.62449084] [ 6.58695964 0.04603165 6.79113943] But the output that I want to have is the minimum of l and the relevant q which means: min is= [1.62449084] [6.79113943] How should I do that and another question is that How should print out the outputs in a column not in front of each other. like this: l= 4.98648387414 q= 4.96850590047 #for i=1 l= 6.22734941766 q= 2.50807065862 #for i=2 l= 8.30807062837 q= 6.36351958551 #for i=2 the code is: from numpy import * import numpy as np a=None temp=1e10 for i in range (1,4): r=np.random.uniform(0,3,i) x=np.random.uniform(0,9,i) h=np.random.uniform(0,1,i) l=h*10 if (l&lt;1.0).any(): q=r elif (l&gt;1.0).any(): q=x print("l= ",*l, "q= ",*q) if (l&lt;temp).any(): temp=l a=q print("min is=", temp,a) I appreciate your help and your consideration.
answer count: 2
tagged with: minimum
type: UnansweredQuestion
tagged with: arrays
tagged with: python

http://stackoverflow.com/a/49327103
type: Answer
accepted answer of: http://stackoverflow.com/q/49326927
has comment: http://stackoverflow.com/comment/85655963
has body: str.join after str.split df=df.replace({' ':''},regex=True) df.Labels.str.split('|').apply(set).str.join('|') Out[339]: 0 Apple|Book|Car 1 2 Apple|Book|Car Name: Labels, dtype: object Base on the comment adding sorted df.Labels.str.split('|').apply(lambda x : sorted(set(x),reverse=False)).str.join(' | ')
upvote count: 3
has comment: http://stackoverflow.com/comment/85655899
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85662889
downvote count: 0
has comment: http://stackoverflow.com/comment/85656201
has comment: http://stackoverflow.com/comment/85656025
answers question: http://stackoverflow.com/q/49326927
score: 3

http://stackoverflow.com/comment/85827255
type: Comment
has text: Tensorboard charts clearly show vanishing gradient problem. You might want to look at a similar problem and solution [in this question](https://stackoverflow.com/q/48816873/712995)
comment on: http://stackoverflow.com/q/49411679
score: 1
type: QuestionComment

http://stackoverflow.com/a/49288981
downvote count: 0
upvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49288557
has body: I found a solution that works: df_filled=df.groupby(pd.Grouper(freq='10D')).fillna(method='bfill')

http://stackoverflow.com/q/49303800
accepted answer: http://stackoverflow.com/a/49304771
has comment: http://stackoverflow.com/comment/85611598
has title: staleelementreferenceexception in Selenium Python on Nested Loops
tagged with: python
type: Question
has body: recently I tried scraping, so this time i wanted to go from page to page until I get the final destination I want. Here's my code: sub_categories = browser.find_elements_by_class_name("ty-menu__submenu-link") for sub_category in sub_categories: sub_category = str(sub_category.get_attribute("href")) if(sub_category is not 'http://www.lsbags.co.uk/all-bags/view-all-handbags-en/' and sub_category is not "None"): browser.get(sub_category) print("Entered: " + sub_category) product_titles = browser.find_elements_by_class_name("product-title") for product_title in product_titles: final_link = product_title.get_attribute("href") if(str(final_link) is not "None"): browser.get(str(final_link)) print("Entered: " + str(final_link)) #DO STUFF I already tried doing the wait and the wrapper(the try and exception one) solutions from here, but I do not get why its happening, I have an idea why this s happening, because it the browser gets lost right? when it finishes one item? I don't know how should I express this idea. In my mind I imagine it would be like this: TIMELINE: *PAGE 1 is within a loop, ALL THE URLS WITHIN IT IS PROCESSED ONE BY ONE *The first url of PAGE 1 is caught. Thus do browser.get page turn to PAGE 2 *PAGE 2 has the final list of links I want to evaluate, so another loop here to get that url, and within that url #DO STUFF *After #DO STUFF get to the second url of PAGE 2 and #DO STUFF again. *Let's assume PAGE 2 has only two urls, so it finished looping, so it goes back to PAGE 1 *The second url of PAGE 1 is caught... and so on... I think I have expressed my idea in some poitn of my code, I dont know what part is not working thus returning the exception. Any help is appreciated, please help. Thanks!
has answer: http://stackoverflow.com/a/49304771
answer count: 1
tagged with: selenium
tagged with: web-scraping
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85584047
has text: The comment by @birryree is really all you need here. There are other ways you could improve things, but if you just change it to compare the digit characters to digits characters instead of numbers, your code will work, and if you understand it, that's good enough.
type: QuestionComment
comment on: http://stackoverflow.com/q/49290333
type: Comment
score: 0

http://stackoverflow.com/a/49415159
type: Answer
has comment: http://stackoverflow.com/comment/85833438
score: 0
has body: There's probably a better answer out there, but you could merge the two DataFrames together, and then determine if the df_new value is a record by comparing the columns. I wouldn't set the dates as an index, just keep them as a column. It makes it a little bit nicer. If they are your indices, then do this first: import pandas as pd df_new['Date'] = df_new.index df_record['Day'] = df_record.index Then: df_new['day'] = pd.to_datetime(df_new.Date).dt.day df_new['month'] = pd.to_datetime(df_new.Date).dt.month df_record['day'] = pd.to_datetime(df_record.Day, format='%M/%d').dt.day df_record['month'] = pd.to_datetime(df_record.Day, format='%M/%d').dt.month Merge the DataFrames and drop the columns we no longer need: df = df_new.merge(df_record, on=['month', 'day']).drop(columns=['month', 'day', 'Day']) Then check if a value is a record. If so, create a new DataFrame with the record values: record_low = df.X_x &lt; df.X_y record_high = df.Y_x &gt; df.Y_y pd.DataFrame({'Date': df[record_low]['Date'].tolist() + df[record_high]['Date'].tolist(), 'Record Value': df[record_low]['X_x'].tolist() + df[record_high]['Y_x'].tolist()}) Date Record Value 0 1/1/2015 10 1 1/2/2015 25 2 1/4/2015 21 3 1/1/2015 35 4 1/3/2015 38 5 1/5/2015 47
has comment: http://stackoverflow.com/comment/85835370
has comment: http://stackoverflow.com/comment/85832544
has comment: http://stackoverflow.com/comment/85833396
has comment: http://stackoverflow.com/comment/85833140
answers question: http://stackoverflow.com/q/49414329
has comment: http://stackoverflow.com/comment/85834396

http://stackoverflow.com/a/49354850
answers question: http://stackoverflow.com/q/49354578
has comment: http://stackoverflow.com/comment/85710813
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85710699
has body: I think the problem may be, you started a login shell which looks for ~/.bash_profile, and ~/.bash_aliases is not sourced in ~/.bash_profile. So the alias command in ~/.bash_aliases was never executed. You can check this by invoking alias python. BTW, export a variable named python is pointless in your case since it will never be used. Apropos which ~/.bash* files is read, you can reference man bash at the INVOCATION chapter. Here is some of them. When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.
accepted answer of: http://stackoverflow.com/q/49354578
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49386888
downvote count: 0
has comment: http://stackoverflow.com/comment/87199383
answers question: http://stackoverflow.com/q/49340520
score: 10
type: Answer
upvote count: 10
accepted answer of: http://stackoverflow.com/q/49340520
has body: It seems that your approach is quite advanced a use of matplotlib, but I would still recommend using a specialized graph plotting library (as does the networkx documentation). As graphs get bigger, more problems arise -- but problems that have already been solved in those libraries. A "go-to" option is graphviz, which handles drawing multi-graphs reasonably well. You can write dot files from networkx graphs, and then use one of the graph drawing tools (e.g. dot, neato, etc). Here is an example, building on graph attributes and multigraph edge attributes: import networkx as nx from networkx.drawing.nx_agraph import to_agraph # define the graph as per your question G = nx.MultiDiGraph([(1, 2), (1, 1), (1, 2), (2, 3), (3, 4), (2, 4), (1, 2), (1, 2), (1, 2), (2, 3), (3, 4), (2, 4)]) # add graphviz layout options (see https://stackoverflow.com/a/39662097) G.graph['edge'] = {'arrowsize': '0.6', 'splines': 'curved'} G.graph['graph'] = {'scale': '3'} # adding attributes to edges in multigraphs is more complicated but see # https://stackoverflow.com/a/26694158 G[1][1][0]['color'] = 'red' A = to_agraph(G) A.layout('dot') A.draw('multi.png') Note that you can also easily invoke the drawing from within an ipython shell: https://stackoverflow.com/a/14945560
has comment: http://stackoverflow.com/comment/108770994
type: AcceptedAnswer

http://stackoverflow.com/comment/85690087
score: 0
comment on: http://stackoverflow.com/q/49343923
type: QuestionComment
type: Comment
has text: Please show the error message.

http://stackoverflow.com/comment/85881051
type: QuestionComment
has text: I just added the code.
comment on: http://stackoverflow.com/q/49439182
type: Comment
score: 0

http://stackoverflow.com/comment/85743307
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49371071
has text: @AlexHall so what should I do ? Because the code template was given with that if statement
type: Comment

http://stackoverflow.com/comment/85677997
comment on: http://stackoverflow.com/q/49338927
has text: Have you made any effort at all? The code you show is not related to your expected output...
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49344332
score: 2
has comment: http://stackoverflow.com/comment/85689117
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49351977
has title: generator functions using the CPython api
upvote count: 2
has comment: http://stackoverflow.com/comment/85689105
tagged with: cpython
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85689080
linked to: http://stackoverflow.com/q/1815812
has comment: http://stackoverflow.com/comment/85689067
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49351977
has comment: http://stackoverflow.com/comment/85689024
has comment: http://stackoverflow.com/comment/85688965
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/85695472
has body: I'm trying to figure out how to write a generator function in C using the CPython api. Unfortunately i do not understand how to and the docs do not explain it very well. Could someone explain how generator functions work in low level code and how i could create them? Something that would work alike to def gen_func(*args): for arg in args: yield arg
has comment: http://stackoverflow.com/comment/85689059
tagged with: generator
has comment: http://stackoverflow.com/comment/85689050

http://stackoverflow.com/comment/85620742
type: QuestionComment
comment on: http://stackoverflow.com/q/49308981
has text: well if that is so, then what do you think I should do to make it work?
score: 0
type: Comment

http://stackoverflow.com/q/49392488
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49393453
has body: I am looking into several tutorials of how to implement learning rate decay while training models using Tensorflow. I noticed in a few examples that it is implemented as follows. For example, in this tutorial on how to model language using recurrent neural networks: self._lr = tf.Variable(0.0, trainable=False) optimizer = tf.train.GradientDescentOptimizer(self._lr) # Some other code... self._new_lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") self._lr_update = tf.assign(self._lr, self._new_lr) The learning rate is updated by invoking the following method: def assign_lr(self, session, lr_value): session.run(self._lr_update, feed_dict={self._new_lr: lr_value}) Then, during training: for i in range(config.max_max_epoch): lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0) m.assign_lr(session, config.learning_rate * lr_decay) Why it is implemented this way? At the first glance it seems to be a bit too complicated. Why something like this wouldn't work? self._lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") optimizer = tf.train.GradientDescentOptimizer(self._lr) # Some other code...
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49393453
answer count: 1
downvote count: 0
has title: How the update of learning rate is performed in Tensorflow tutorials?

http://stackoverflow.com/comment/85637250
comment on: http://stackoverflow.com/q/49317551
type: QuestionComment
has text: Why not just encrypt the home directory which the script stores?
score: 0
type: Comment

http://stackoverflow.com/comment/90026240
has text: Please post some code so we can try to be of anny help
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49349722
type: Comment

http://stackoverflow.com/q/49283834
score: 0
has comment: http://stackoverflow.com/comment/85570476
has comment: http://stackoverflow.com/comment/85570482
has title: Python: Clock source for Time module
tagged with: python
has body: There was no code have been wrote for this question and I was curious about how the time module counts time elapsed in execution. I read Python documentation and the clue that I have it depends on processor time. Therefore would it be correct if I think that Python time module depends on processor crystal oscillator to keep track of the time elapsed in execution? Or it depends on some other hardware to keep track of time? If the thought of it depends on crystal oscillator is correct, would it be for an execution to stop at certain line of code like time.sleep(10) forever as it was waiting for the time to reach? One more question.. Is it possible to run an execution if time module is not needed in an execution? I guess it is possible to run because the execution doesn't need to know any information of time?
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: time
linked to: http://stackoverflow.com/q/27830403

http://stackoverflow.com/q/49341281
tagged with: python
score: 2
has title: Spark executor JVM crashes
has body: I have a EMR cluster with one master node and four worker nodes. Each node has 4 cores and 16gb of RAM. I tried to run the below code to fit Logistic Regression on my data: from pyspark.ml.evaluation import BinaryClassificationEvaluator, MulticlassClassificationEvaluator from pyspark.ml.classification import LogisticRegression from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.classification import GBTClassifier from pyspark.ml.classification import MultilayerPerceptronClassifier from pyspark.ml.tuning import ParamGridBuilder, CrossValidator lr = LogisticRegression(labelCol="label", featuresCol="features") paramGrid = (ParamGridBuilder() .addGrid(lr.regParam, [0.01, 2.0]) .addGrid(lr.elasticNetParam, [0.0, 1.0]) .addGrid(lr.maxIter, [5, 10]) .build()) # Create 2-fold CrossValidator cv = CrossValidator(estimator=lr, estimatorParamMaps=paramGrid, evaluator=MulticlassClassificationEvaluator(metricName="f1"), numFolds=2) # Run cross validations cvModel = cv.fit(age_training_data) My spark-defaults.conf is: spark.driver.extraLibraryPath /usr/lib/hadoop-current/lib/native spark.executor.extraLibraryPath /usr/lib/hadoop-current/lib/native spark.driver.extraJavaOptions -Dlog4j.ignoreTCL=true spark.executor.extraJavaOptions -Dlog4j.ignoreTCL=true spark.hadoop.yarn.timeline-service.enabled false spark.driver.memory 10g spark.yarn.driver.memoryOverhead 5g spark.driver.cores 3 spark.executor.memory 10g spark.yarn.executor.memoryOverhead 2048m spark.executor.instances 4 spark.executor.cores 2 spark.default.parallelism 48 spark.yarn.max.executor.failures 32 spark.network.timeout 10000000s spark.rpc.askTimeout 10000000s spark.executor.heartbeatInterval 10000000s spark.yarn.historyServer.address emr-header-1.cluster-60683:18080 spark.ui.view.acls * #spark.serializer org.apache.spark.serializer.KryoSerializer spark.executor.extraJavaOptions -XX:+UseG1GC #spark.kryoserializer.buffer.max 128m A lot of the executors are killed throughout the process. One of th…
upvote count: 2
has comment: http://stackoverflow.com/comment/85686860
has comment: http://stackoverflow.com/comment/85693518
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85690254
tagged with: jvm
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pyspark

http://stackoverflow.com/q/49404068
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has title: How do I transform a Panda Dataframe from 5 columns into 1 column using column header as value to populate?
answer count: 3
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/49404492
tagged with: dataframe
has comment: http://stackoverflow.com/comment/85810504
has answer: http://stackoverflow.com/a/49404621
has answer: http://stackoverflow.com/a/49404492
has body: This is data collected from a survey where there was a radio button to select from 1 of 5 choices. What is stored in the column is a simple 1 as a flag to say it was selected. I am wanting to end up with a single column with the column headers as the values. Someone suggested using the IDXMAX method on my dataframe, but when I looked at the docs I couldn't really figure out how to apply it. It does look like it would be useful for this though... I have a dataframe: old = pd.DataFrame({'a FINSEC_SA' : [1,'NaN','NaN','NaN','NaN',1,'NaN'], 'b FINSEC_A' : ['NaN',1,'NaN','NaN','NaN','NaN','NaN'], 'c FINSEC_NO' : ['NaN','NaN',1,'NaN','NaN','NaN','NaN'], 'd FINSEC_D' : ['NaN','NaN','NaN',1,'NaN','NaN',1], 'e FINSEC_SD' : ['NaN','NaN','NaN','NaN',1,'NaN','NaN']}) I would like to end up with a dataframe like this: new = pd.DataFrame({'Financial Security':['a FINSEC_SA','b FINSEC_A', 'c FINSEC_NO','d FINSEC_D','e FINSEC_SD','a FINSEC_SA','d FINSEC_D']}) I only have about 65k rows of data so performance is not top of list for me. I am most interested in learning a good way to do this - that is hopefully fairly simple. It would be really nice if the idxmax does this fairly easily.
type: Question
possible better answer: http://stackoverflow.com/a/49404438
tagged with: transformation
has comment: http://stackoverflow.com/comment/85832364
has answer: http://stackoverflow.com/a/49404438
downvote count: 0

http://stackoverflow.com/a/49442429
type: Answer
has body: This is a modified version of the proposed answer that also includes the original desired intent of allowing the user to cycle through the months and will also increment the year. from calendar import * import datetime try: from tkinter import * # Python 3.x except: from Tkinter import * # Python 2.x class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(row=0, column=0, sticky='news') DateNow = datetime.datetime.now() self.month = int(DateNow.month) self.year = int(DateNow.year) self.createDaysOfWeekLabels() # Create frames and button controls for previous, current and next month. self.frameList = [] # List that contains the frame objects. self.buttonList = [] # List that contains the button objects. self.split() def split(self): month_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] leftArrow = Button(self, text="&lt;", command=self.prevMonth) leftArrow.grid(row = 0, column = 0) rightArrow = Button(self, text="&gt;", command=self.nextMonth) rightArrow.grid(row = 0, column = 1) for i in range(3): try: print i, "this is i" print self.month mFrame = Frame(self) self.createMonth(mFrame) self.frameList.append(mFrame) mButton = Button(self, text=month_name[self.month-1]) mButton['command'] = lambda f=mFrame, b=mButton: self.showMonth(f, b) mButton.grid(row=1, column=i) # Grid each frame mFrame.grid(row=3, column=0, columnspan=7, sticky='news') if (i == 1): mButton['relief'] = 'flat' else: mButton.grid_remove() # Remove all but the ith frame. More efficient to remove than forget and configuration is remembered. mFrame.grid_remove() self.buttonList.append(mButton) except: pass # Create year widget at top right of top frame label = Label(self, text=self.year)#displaying year label.grid(row=0, column=6) print "-------------------" def prevMonth(self): self.month -= 1 print self.month, "this is month in PREV" if self.month &lt;= 0: self.month = 12 print self.month, "month inside forinif in …
score: 2
accepted answer of: http://stackoverflow.com/q/49396207
answers question: http://stackoverflow.com/q/49396207
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49365864
linked to: http://stackoverflow.com/q/9066956
type: AnsweredQuestion
upvote count: 8
has answer: http://stackoverflow.com/a/49365953
answer count: 3
tagged with: versioning
has body: Right now, on the "All releases" page of the Python Software Foundation website, the "Download latest release" links to the Python 3.6.4 version. However, you can find on the page that the release is from the 2017-12-19 and there has been two others release since, for Python 3.5.5 and Python 3.4.8 . I understand why there is two parallel version of Python with 3 and 2.7, but I do not understand why they are multiple versions of Python 3, as it should be backward compatible with Python 3 code.
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49366160
downvote count: 4
has answer: http://stackoverflow.com/a/49366160
tagged with: python
has title: Why are they some new releases of Python 3 on older Python 3 versions?
score: 4
has answer: http://stackoverflow.com/a/49366418
possible better answer: http://stackoverflow.com/a/49365953
favorite count: 0

conv-neural-network
tags question: http://stackoverflow.com/q/49369472
tags question: http://stackoverflow.com/q/49404205
tags question: http://stackoverflow.com/q/49338923
tags question: http://stackoverflow.com/q/49305461
tags question: http://stackoverflow.com/q/49416470
tags question: http://stackoverflow.com/q/49364933
type: Tag
tags question: http://stackoverflow.com/q/49419504
tags question: http://stackoverflow.com/q/49282546
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/49406654
tags question: http://stackoverflow.com/q/49388477

http://stackoverflow.com/q/49338242
tagged with: decimal
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49338333
has body: I'm trying to develop a simple program that finds decimal numbers that are equal to the average of their digits. Example 4.5 (4+5=9 / 2)= 4.5 In order to do this I need to take averages that have several decimal points and compare them to a big iterated list of decimal numbers (I'm using a nested loop to do this). When I use the Decimal library to do simple division, the answer comes out with four decimal points, like I want: 0.2727 But when I try to print the the averages of my loop. (Decimal(i + y + z + q)) / Decimal(4)) the averages only come out to the hundredth decimal point (0.25 0.5 0.75, etc). Why? I've tried converting into str() and int() before passing into Decimal() and it doesn't work. from decimal import * getcontext().prec = 4 print(Decimal(3)/Decimal(9)) numbers1to10 = [0,1,2,3,4,5,6,7,8,9] for i in numbers1to10: for y in numbers1to10: for z in numbers1to10: for q in numbers1to10: if: (Decimal(i + y + z + q)) / Decimal(4)) == ((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100)+ (Decimal(q)/1000)): print (((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100) + (Decimal(q)/1000)))
has title: Python: Getting decimal library to return the right amount of decimals?
score: 0
tagged with: nested-loops
has answer: http://stackoverflow.com/a/49338356
tagged with: python
tagged with: decimal-point
type: Question

http://stackoverflow.com/a/49338333
answers question: http://stackoverflow.com/q/49338242
score: 0
has body: Can't say for sure, but those numbers (0.25 0.5 0.75) look quite "round" to me, by that I mean that they are just 1/4, 2/4 and 3/4 and they don't have any other decimals to show. Then it's normal that you only get to the hundredth. 0.5 is 0.5, no need to show 0.5000. If you really want to show to 4 decimals with additional zeroes at the end, use the format functions. Example: print("%.4f" % 0.5) Displays 0.5000.
type: Answer

http://stackoverflow.com/q/49392087
has comment: http://stackoverflow.com/comment/85786590
has comment: http://stackoverflow.com/comment/85789898
has answer: http://stackoverflow.com/a/49393055
has answer: http://stackoverflow.com/a/49393867
tagged with: python
has body: I got used to working in IDLE, but got a recommendation to use PyCharm instead. As I'm just getting used to it, I have a question on accessing elements of a matrix. I'm getting different string inputs from the user and filling the matrix with them; from numpy import * row=int(input()) col=int(input()) m=range(row*col) m=reshape(m,(row,col)) for i in range(0,row): for j in range(0,col): el=int(input()) m[i][j]=el What PyCharm is telling me: Class 'ndarray' does not define 'getitem', so the '[]' operator cannot be used on its instances less... This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. Could anyone please explain to me how I can change/fix this?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85785846
answer count: 3
tagged with: matrix
accepted answer: http://stackoverflow.com/a/49393055
has title: Accessing matrix elements
has answer: http://stackoverflow.com/a/49393012
possible better answer: http://stackoverflow.com/a/49393012
type: Question
tagged with: numpy

parsing
tags question: http://stackoverflow.com/q/49402786
tags question: http://stackoverflow.com/q/49322847
tags question: http://stackoverflow.com/q/49321054
tags question: http://stackoverflow.com/q/49416500
tags question: http://stackoverflow.com/q/49393703
tags question: http://stackoverflow.com/q/49312250
tags question: http://stackoverflow.com/q/49310725
tags question: http://stackoverflow.com/q/49403315
tag name: parsing
tags question: http://stackoverflow.com/q/49319996
tags question: http://stackoverflow.com/q/49321998
tags question: http://stackoverflow.com/q/49418428
tags question: http://stackoverflow.com/q/49395064
tags question: http://stackoverflow.com/q/49337956
tags question: http://stackoverflow.com/q/49288932
tags question: http://stackoverflow.com/q/49435630
tags question: http://stackoverflow.com/q/49410893
tags question: http://stackoverflow.com/q/49413362
tags question: http://stackoverflow.com/q/49326790
tags question: http://stackoverflow.com/q/49339622
tags question: http://stackoverflow.com/q/49399555
tags question: http://stackoverflow.com/q/49307863
tags question: http://stackoverflow.com/q/49360776
type: Tag

http://stackoverflow.com/a/49330150
type: AcceptedAnswer
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49330129
type: Answer
has body: List comprehension with conditional expression: [0 if i in toReplace else i for i in sourceArray] If the toReplace list is too big, it's preferable to make it a set to get O(1) lookup. Example: In [21]: sourceArray = [0,1,2,3,4,5,5,6,7] ...: toReplace = [5,6] ...: In [22]: [0 if i in toReplace else i for i in sourceArray] Out[22]: [0, 1, 2, 3, 4, 0, 0, 0, 7]
answers question: http://stackoverflow.com/q/49330129
score: 5

http://stackoverflow.com/q/49327630
has answer: http://stackoverflow.com/a/49327700
has body: I am new to python 3 and I'm working on sentiment analysis of tweets. My code begins with a for loop that takes in 50 tweets, which i clean and pre-process. After this (still inside the for loop) i want to save each tweet in a text file(every tweet on a new line) Here's how the code goes: for loop: .. print statments .. if loop: filename=open("withnouns.txt","a") sys.stdout = filename print(new_words)#tokenised tweet that i want to save in txt file print("\n") sys.stdout.close()#i close it because i dont want to save print statements OUTSIDE if loop to be saved in txt file .. .. print statements After running this its showing error: I/O operation on closed file on line 71 (the first print statement after if loop) My question is, is there any way I can temporarily close and then open sys.stdout and have it active only inside the if loop?
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85657282
possible better answer: http://stackoverflow.com/a/49327820
has answer: http://stackoverflow.com/a/49327820
type: AnsweredQuestion
answer count: 3
tagged with: sentiment-analysis
score: 1
has comment: http://stackoverflow.com/comment/85690921
has answer: http://stackoverflow.com/a/49327910
has title: how to close sys.stdout in a nested loop so that it doesnt copy print statements outside inner loop in file
favorite count: 0
accepted answer: http://stackoverflow.com/a/49327700
type: Question
tagged with: file-handling
tagged with: python-3.x

http://stackoverflow.com/comment/85723294
comment on: http://stackoverflow.com/a/49361644
type: Comment
has text: The test string may contain values like `.87%`. So you can use `\d*` in that case
type: AnswerComment
score: 0

activation-function
tags question: http://stackoverflow.com/q/49412717
type: Tag
tag name: activation-function
tags question: http://stackoverflow.com/q/49374126

http://stackoverflow.com/a/49436165
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49414667
type: AcceptedAnswer
type: Answer
has body: query = query.options(joinedload('attached_addresses').joinedload('address')) By chaining address joinedload to attached_addresses I was able to significantly speed up the query. My understanding of why this is the case: Address objects were not being loaded with the initial query. Every iteration thru the loop, the db would get hit to retrieve the Address object. With joined load, Address objects are now loaded upon initial query. Thanks to Corley Brigman for the help.
accepted answer of: http://stackoverflow.com/q/49414667

http://stackoverflow.com/q/49326131
has title: WeasyPrint - Https certificate verify failed
answer count: 1
tagged with: python
tagged with: weasyprint
type: Question
type: UnansweredQuestion
has body: I am using weasyprint on windows Python script as below: from weasyprint import HTML HTML('https://localhost:82/page/').write_pdf('weasyprint.pdf') https is SSL is local iis express Error as below: weasyprint.urls.URLFetchingError: URLError: &lt;urlopen error [SSL:CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) As we are using iis express certificate for the website. Is there a way to skip this error?
has comment: http://stackoverflow.com/comment/85655960
score: 0
has answer: http://stackoverflow.com/a/51747369

http://stackoverflow.com/comment/85646430
score: 0
type: QuestionComment
has text: Try renaming your proc_data_lib.py to proc_data_lib.zip and unzip it
comment on: http://stackoverflow.com/q/49322509
type: Comment

http://stackoverflow.com/q/49418059
has comment: http://stackoverflow.com/comment/85838345
type: Question
has body: I'm a newbie to Python but have experience in MATLAB/Scilab. I'm creating a mathematical model in Scilab, but the input data is generated from a Python (2.7) code. As a result, I'm trying to make use of the Python module scilab2py (see http://blink1073.github.io/scilab2py/source/installation.html) in order to run Scilab from inside Python to allow the process to be much simpler. I installed all the required Python modules for scilab2py (i.e. Scipy, Numpy) and have Scilab installed in my PATH, so I installed scilab2py using pip install scilab2py which it says was successful. However, if I enter Python and try import scilab2py I am met with the following error: Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; import scilab2py File "C:\Python27\lib\site-packages\scilab2py\__init__.py", line 46, in &lt;module&gt; lib1 = ctypes.CDLL(os.path.join(basepath, 'core', 'libmmd.dll')) File "C:\Python27\lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found Does anyone know how to fix this error? Or perhaps know where I am going wrong with implementation? Thanks in advance.
favorite count: 0
tagged with: scilab
has title: Python/Scilab bridge: scilab2py error
answer count: 0
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
score: 1
tagged with: integration

http://stackoverflow.com/comment/85844832
type: QuestionComment
has text: your statsmodel plot is wrong. It should be x*param[1] + param[0]
comment on: http://stackoverflow.com/q/49421990
score: 0
type: Comment

http://stackoverflow.com/comment/85664400
score: 0
type: Comment
type: QuestionComment
has text: @SrinivasSuresh remove it from the file please.
comment on: http://stackoverflow.com/q/49331171

http://stackoverflow.com/q/49291033
score: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/64031801
type: Question
has body: As we know C/C++ has macro function to do text replacement, here is an example: #include <string> #include <iostream> using namespace std; #define FIRST_NAME Print("Moon") #define FAMILY_NAME Print("Sun") string Print(string name) { cout << name << endl; return name; } int main() { string name = FIRST_NAME + FAMILY_NAME; return 0; } As you can see the FIRST_NAME and FAMILY_NAME are macros which will be replaced by the function Print(). My question is does Python have a similar feature? Or what can I do to create this kind of feature?
has answer: http://stackoverflow.com/a/49291124
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/64031997
has title: Use macro replacement in Python like C/C++
upvote count: 2
answer count: 3

http://stackoverflow.com/comment/85732994
score: 1
comment on: http://stackoverflow.com/a/49366013
type: Comment
type: AnswerComment
has text: The file may have more than one dot like /tmp/filename.tar.gz for example.

http://stackoverflow.com/comment/85582888
has text: Did you try calling `import gc; gc.collect()`? Garbage collection need not happen immediately.
comment on: http://stackoverflow.com/q/49289830
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49335765
score: 0
has body: Your best bet are Unix domain sockets and Named Pipes / FIFOs. For comparison you can see this answer. For simplicity you can use JSON as message format.
type: Answer
answers question: http://stackoverflow.com/q/49335575

http://stackoverflow.com/comment/85780845
type: Comment
score: 0
type: AnswerComment
has text: `str(whatever)` will never be equal to an int (e.g., `4`)
comment on: http://stackoverflow.com/a/49389648

http://stackoverflow.com/a/49369180
has body: If you are not running on current versions of both Chrome and chromedriver, please update to Chrome build 65 and chromedriver 2.37 HERE. To update your Chrome, go to help &gt; About google chrome and it should update automatically. If you cannot update to current builds, try using this: from selenium import webdriver ChromeOptions = webdriver.ChromeOptions() ChromeOptions.add_argument('--disable-browser-side-navigation') driver = webdriver.Chrome('your/path/to/chromedriver.exe', chrome_options=ChromeOptions) Also, refer to Python - selenium webdriver stuck at .get() in a loop, for more help about .get() hang issues with selenium.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49366589
score: 0
has comment: http://stackoverflow.com/comment/85757441
type: Answer
has comment: http://stackoverflow.com/comment/85778548
accepted answer of: http://stackoverflow.com/q/49366589

http://stackoverflow.com/comment/128362235
has text: @Rimov you are right. First, I agree that these two codes are copied. Yes, the methods are similar, but the code structure and details (and even the answer structure) are very distinctive for a programmer. Usually small one-time sites copy code from StackOverflow, but this proves another case, because... Second: the article was published on April 15, 2018, which can be seen from the Web Archive (http://web.archive.org/web/20180531030548/http://thispointer.com/python-how-to-check-if-a-directory-is-empty). I think it will be right to add this article link (or an older article?) as the source.
comment on: http://stackoverflow.com/a/59050548
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/49355224
has comment: http://stackoverflow.com/comment/85710837
has comment: http://stackoverflow.com/comment/85710792
upvote count: 1
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49355269
has comment: http://stackoverflow.com/comment/85710857
has title: How to place a number into a string?
has body: I want to create the following function Left_padded(n, width) That returns, for example: Left_padded(6, 4): ' 6' #number 6 into a 4 digits space Left_padded(54, 5) ' 54' #number 54 into a 5 digits space
has comment: http://stackoverflow.com/comment/85710781
tagged with: python
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85710798
has comment: http://stackoverflow.com/comment/85710867
has comment: http://stackoverflow.com/comment/85710788
answer count: 2
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/49355444

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/49375054
type: Tag

http://stackoverflow.com/comment/85686905
comment on: http://stackoverflow.com/q/49341214
has text: my bad. Indeed, it should be thread safe (but though `extend` is, `append` is not). I will post couple snippets to try
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49339543
has comment: http://stackoverflow.com/comment/85679508
has comment: http://stackoverflow.com/comment/85679474
accepted answer of: http://stackoverflow.com/q/49339512
has comment: http://stackoverflow.com/comment/85679581
has comment: http://stackoverflow.com/comment/85679365
type: Answer
has comment: http://stackoverflow.com/comment/85679426
has comment: http://stackoverflow.com/comment/85679419
answers question: http://stackoverflow.com/q/49339512
has comment: http://stackoverflow.com/comment/85680402
has comment: http://stackoverflow.com/comment/85679297
score: 2
upvote count: 2
has body: I believe you need groupby all columns and use GroupBy.size: #create DataFrame from online source #df = pd.read_csv('someonline.csv') #df = pd.read_html('someurl')[0] #L = [] #for x in iterator: #in loop added data to list # L.append(x) ##created DataFrame from contructor #df = pd.DataFrame(L) df = df.groupby(df.columns.tolist()).size().reset_index(name='repeat') #if need specify columns #df = df.groupby(['name','zip']).size().reset_index(name='repeat') print (df) name zip repeat 0 boo 30004 1 1 boo 30750 1 2 foo 02895 1 3 roo 02895 1 4 too 02895 2
has comment: http://stackoverflow.com/comment/85679612
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85882733
score: 0
comment on: http://stackoverflow.com/a/49398948
type: Comment
has text: Once, I have trained the classifiers to give me the best predictions based on best confidence levels, for which I can test it on the training instances using `cross_val_predict` without messing with test data, I want to finally predict using the X_test so that it gives me y_preds and then get the `f1_score` on the y_preds and y_test_sl. Once again I am sorry if I am confusing you. If you want to be more clear you can ask more question. Your help means a lot and I would definitely mention your contribution in my project.
type: AnswerComment

http://stackoverflow.com/a/49354082
has comment: http://stackoverflow.com/comment/85708578
has comment: http://stackoverflow.com/comment/85708525
accepted answer of: http://stackoverflow.com/q/49353986
has body: You can use the following dictionary comprehension with numpy: import numpy as np median_dict_of_lists = {i : list(np.median([x[i] for x in list_of_dicts_of_lists], axis=0)) for i in 'abcd'} Which returns the same: {'a': [1.5, 2.0], 'c': [2.0, 4.0], 'b': [3.0, 3.0], 'd': [3.0, 5.0]} To explain, np.median([x[i] for x in list_of_dicts_of_lists], axis=0), embedded in the dictionary comprehension, is going through each key i in ['a', 'b', 'c', 'd'], and getting the median of each key for all of your dicts in your original list of dicts. This median is getting assigned to a new dictionary with the appropriate key via the dictionary comprehension syntax. There is a good explanation of the dictionary comprehension syntax here, and the documentation for np.median explains the function itself quite well
type: Answer
has comment: http://stackoverflow.com/comment/85708611
answers question: http://stackoverflow.com/q/49353986
has comment: http://stackoverflow.com/comment/85708488
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85738091
has text: It gives the proper latex output for me: `10 \cdot 100 \cdot 100 \cdot 1000 \cdot 1000 \cdot 10000 \cdot 100000`
score: 0
comment on: http://stackoverflow.com/a/49368381
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85585166
type: Comment
has text: Thank you!! I found it easiest that I just save my List RDD with JSON to textfile, that output out the set of objects I was looking for. No need for the dataframe at all.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49290728

pdb
tags question: http://stackoverflow.com/q/49296023
type: Tag
tag name: pdb

http://stackoverflow.com/a/49381902
has body: non_field_errors is a method, not a regular attribute as errors is: print('Non Errors:', form_post.non_field_errors())
answers question: http://stackoverflow.com/q/49381132
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85576505
type: QuestionComment
comment on: http://stackoverflow.com/q/49283825
score: 0
has text: I've tested this on Python 3.6 and it works. As I do not have Python 2.7, I could not test it. I've edited the code further as it might be helpful.
type: Comment

http://stackoverflow.com/comment/85587342
comment on: http://stackoverflow.com/q/49292334
type: Comment
type: QuestionComment
has text: Some of your files probably have an empty line at the end or elsewhere.
score: 0

http://stackoverflow.com/comment/85886402
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49424846
type: Comment
has text: Tried best to minimize code (added inline). There's some data in the beginning that has to be parsed into a dict and that is a necessary part mouse event handler.

anaconda
tags question: http://stackoverflow.com/q/49310483
tags question: http://stackoverflow.com/q/49393300
tags question: http://stackoverflow.com/q/49319808
tags question: http://stackoverflow.com/q/49378958
tags question: http://stackoverflow.com/q/49361288
tags question: http://stackoverflow.com/q/49359605
tags question: http://stackoverflow.com/q/49432452
tags question: http://stackoverflow.com/q/49286473
type: Tag
tags question: http://stackoverflow.com/q/49353418
tags question: http://stackoverflow.com/q/49330685
tags question: http://stackoverflow.com/q/49400154
tag name: anaconda
tags question: http://stackoverflow.com/q/49291278
tags question: http://stackoverflow.com/q/49283143
tags question: http://stackoverflow.com/q/49434422
tags question: http://stackoverflow.com/q/49320481
tags question: http://stackoverflow.com/q/49340776
tags question: http://stackoverflow.com/q/49349096
tags question: http://stackoverflow.com/q/49312229
tags question: http://stackoverflow.com/q/49424554
tags question: http://stackoverflow.com/q/49405016
tags question: http://stackoverflow.com/q/49397373
tags question: http://stackoverflow.com/q/49397459
tags question: http://stackoverflow.com/q/49388901
tags question: http://stackoverflow.com/q/49313832
tags question: http://stackoverflow.com/q/49434908
tags question: http://stackoverflow.com/q/49348949
tags question: http://stackoverflow.com/q/49398834
tags question: http://stackoverflow.com/q/49310532
tags question: http://stackoverflow.com/q/49411277
tags question: http://stackoverflow.com/q/49373535
tags question: http://stackoverflow.com/q/49397462
tags question: http://stackoverflow.com/q/49396520
tags question: http://stackoverflow.com/q/49363172
tags question: http://stackoverflow.com/q/49345786
tags question: http://stackoverflow.com/q/49336202
tags question: http://stackoverflow.com/q/49291015
tags question: http://stackoverflow.com/q/49298058
tags question: http://stackoverflow.com/q/49364525

http://stackoverflow.com/q/49435233
has answer: http://stackoverflow.com/a/49435451
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86323855
has comment: http://stackoverflow.com/comment/85872603
has body: I'm used to typing !! in bash when I want to reference the last command executed in that shell. $ ls -la drwxr-xr-x 4 me wheel 136 Jan 19 2013 wireshark_stuff ... (etc) ... -rw-r--r-- 1 me wheel 11 Mar 13 13:51 old_PS1 $ !! |grep for_something_in_those_results ls -la |grep for_something_in_those_results /grep_results Is there a way to do this in python? &gt;&gt;&gt; complicated_dict.['long_key_name'][0] (response) &gt;&gt;&gt; my_func(!!) This would get really handy as the interpreter commands become increasingly complicated. Sure, I could just use a plethora of local variables - but sometimes it's handy to just invoke the last thing run...
tagged with: python
has comment: http://stackoverflow.com/comment/85872350
has comment: http://stackoverflow.com/comment/85872531
tagged with: read-eval-print-loop
has answer: http://stackoverflow.com/a/49435830
answer count: 4
has answer: http://stackoverflow.com/a/49435269
has comment: http://stackoverflow.com/comment/85872628
score: 3
has answer: http://stackoverflow.com/a/49435284
linked to: http://stackoverflow.com/q/200020
has comment: http://stackoverflow.com/comment/85872434
upvote count: 3
has comment: http://stackoverflow.com/comment/85872478
downvote count: 0
favorite count: 0
type: Question
has title: Does Python(2.7)'s interactive shell have an equivalent to bash's "!!" (bang bang)?
has comment: http://stackoverflow.com/comment/85872579
has comment: http://stackoverflow.com/comment/85872700

http://stackoverflow.com/a/49311162
answers question: http://stackoverflow.com/q/49311098
score: 0
type: Answer
has body: The first argument in your function is redundant. Try this: def make_special_tree(arg1, arg2): tree = Tree() other_stuff = things(arg1) modify_tree(tree, other_stuff, arg2) return tree blah = make_special_tree(foo, bar)
has comment: http://stackoverflow.com/comment/85624221

http://stackoverflow.com/a/49321865
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49321725
upvote count: 5
has body: When you do dd = cc, both dd and cc are now references to the same object (same for bb = aa). Nothing is being copied! When you do bb = bb * 2, the * operator creates a new object and bb now refers to that object. No existing object is changed. When you do dd *= 2, the object that dd refers to (and which cc also refers to) is changed. So the difference is that * creates a new object and = makes a variable refer to a new object (rather than changing the object in any way), whereas *= changes the object. It may be counter-intuitive that x *= y behaves differently than x = x * y, but those are the semantics of the language, not a bug.
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49321725

http://stackoverflow.com/a/49344515
has comment: http://stackoverflow.com/comment/85697689
answers question: http://stackoverflow.com/q/49344455
score: 0
has body: You could use startswith() : for tag in tags: if tag.get('href').startswith('pre'): print(tag.get('href'))
has comment: http://stackoverflow.com/comment/85697572
type: Answer

http://stackoverflow.com/comment/85777128
comment on: http://stackoverflow.com/q/49387819
score: 1
type: Comment
type: QuestionComment
has text: What's the problem? If you compare some point to all 6 cluster-rows and calculate the distance for each, just get the index of the minimum and access column ```clust``` with that index? If metric-trees would help, probably depends on the size of the datasets.

http://stackoverflow.com/comment/85813122
score: 0
has text: Sorrry I missed the date in the code, so the X axis will be the datetime.datetime.now() , to give a continuous line. Maybe I need to add a time delay ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49405499

http://stackoverflow.com/comment/85565878
type: AnswerComment
has text: The key is not being held down, just repetitively pressed for 5 seconds.
comment on: http://stackoverflow.com/a/49281458
score: 1
type: Comment

http://stackoverflow.com/a/49368179
score: 3
upvote count: 3
downvote count: 0
has body: As mentioned by daniel451, numpy isn't parallelizing the cumsum operation, so you can parallelize it explicitly to gain at least a little performance. For example, using multiprocessing.dummy (a thread-backed copy of the multiprocessing API), you could do: import numpy as np from multiprocessing.dummy import Pool from itertools import repeat forcing = np.random.rand(380*1400*620).reshape((380,1400,620)) # Make an output array of matching size, that can be populated piecemeal # in each thread forceres = np.zeros_like(forcing) # Compute cumsum in parallel over second dimension with Pool() as pool: # Use module function with np.rollaxis to avoid need to define # worker to do slicing pool.starmap(np.cumsum, zip(np.rollaxis(forcing, 1), repeat(0), repeat(None), np.rollaxis(forceres, 1))) I tested this with ipython3's %time/%%time magic on an eight core machine, and found it reduced runtime vs. the original code by almost 70%, from 5.49 seconds to 1.73 seconds; your machine is clearly faster, so if the same speed up occurs on your machine I'd expect it to take ~0.66 seconds. My comparison was: &gt;&gt;&gt; %%time ... forcesres = np.zeros_like(forcing) ... with Pool() as pool: ... pool.starmap(np.cumsum, zip(np.rollaxis(forcing, 1), repeat(0), repeat(None), np.rollaxis(forceres, 1))) CPU times: user 10 s, sys: 213 ms, total: 10.2 s Wall time: 1.73 s vs. &gt;&gt;&gt; %time forcing.cumsum(axis=0); None # ; None avoids output CPU times: user 5.27 s, sys: 218 ms, total: 5.49 s Wall time: 5.49 s
type: Answer
answers question: http://stackoverflow.com/q/49367278
has comment: http://stackoverflow.com/comment/85737485

http://stackoverflow.com/comment/85859443
has text: I agree to @TomdeGeus. In Python you can only overload operators not functions. Just call plotting mehods.
score: 0
comment on: http://stackoverflow.com/q/49428050
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85593170
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49295322
has text: Typing it shows you the object which is indeed an array... Try calling `print(m2)` instead ?

http://stackoverflow.com/comment/85894284
has text: Okay I understand what you are doing now, I should have been clearer. That's not what I meant. The non-zero elements take up a 3x2 block within the array of 4x3 which includes 2 zeros, so the answer is 3 and 2.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49437123
type: Comment

http://stackoverflow.com/q/49393734
score: 1
tagged with: child-process
has title: Parent loggers in child processes
favorite count: 0
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/85791648
accepted answer: http://stackoverflow.com/a/49393919
has answer: http://stackoverflow.com/a/49393919
tagged with: python
has body: In the Logging Cookbook on Python, there are the following comments in the section "A more elaborate multiprocessing example": # The worker process configuration is just a QueueHandler attached to the # root logger, which allows all messages to be sent to the queue. # We disable existing loggers to disable the "setup" logger used in the # parent process. This is needed on POSIX because the logger will # be there in the child following a fork(). # The listener process configuration shows that the full flexibility of # logging configuration is available to dispatch events to handlers however # you want. # We disable existing loggers to disable the "setup" logger used in the # parent process. This is needed on POSIX because the logger will # be there in the child following a fork(). What is exactly the problem of having a parent logger in a child process?
tagged with: logging
type: AnsweredQuestion
tagged with: posix
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49379063
tagged with: matplotlib
has title: Is there any way to install matplotlib in Python 3.3?
tagged with: python
has comment: http://stackoverflow.com/comment/85772887
answer count: 0
has comment: http://stackoverflow.com/comment/85758726
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85759652
has comment: http://stackoverflow.com/comment/85759633
has comment: http://stackoverflow.com/comment/85759215
has comment: http://stackoverflow.com/comment/85772999
type: Question
has body: Is there any way for Matplotlib to be installed in Python 3.3? After using pip to try and install it, I am unable to get it installed as matplotlib uses Python 3.4. I was wondering if there was any earlier version of matplotlib that is compatible with python 3.3?
has comment: http://stackoverflow.com/comment/85766676
has comment: http://stackoverflow.com/comment/85759713
score: 0
has comment: http://stackoverflow.com/comment/85758753

http://stackoverflow.com/comment/85586621
type: QuestionComment
score: 2
has text: Please Upload the original image as well ?
comment on: http://stackoverflow.com/q/49291770
type: Comment

http://stackoverflow.com/a/49480920
accepted answer of: http://stackoverflow.com/q/49394526
has comment: http://stackoverflow.com/comment/86082645
has comment: http://stackoverflow.com/comment/85965220
answers question: http://stackoverflow.com/q/49394526
type: Answer
has comment: http://stackoverflow.com/comment/86082577
has body: The symbols within libpython (e.g. libpython2.7.dylib) are being resolved correctly. For example, under the above described scenario, I see PyModule_GetDict() get called 155 times before the incorrectly resolved call. The problem is that python itself is compiling shared libraries, and it's using dlopen() to load them. You can see the dlopen() happening by setting the environment variable PYTHONVERBOSE when running: $ PYTHONVERBOSE=1 ./main 2&gt;&amp;1 | grep dlopen which produces: dlopen(".../lib/python2.7/lib-dynload/_locale.so", 2); The 2 argument corresponds to RTL_NOW, but that doesn't matter too much. The issue is that this separate library isn't able to indicate that it's symbols should be resolved against the libpython2.7.dylib library. Yet, it does have several python symbols; in particular, this one that ends up causing the problem: $ nm prefix/lib/python2.7/lib-dynload/_locale.so | grep GetDict U _PyModule_GetDict So, when python dlopen()s the library, all it can do is resolve the symbol without the qualification. Apparently, the semantic of the dl functionality is to resolve such symbols based on the order the libraries are loaded, as you noted. So, things work fine until we load _locale.so, as you can see from the following backtrace: * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x50) * frame #0: 0x00000001003f3fc1 libpython3.6m.dylib`PyErr_FormatV [inlined] PyErr_Restore at errors.c:42 [opt] frame #1: 0x00000001003f3fb7 libpython3.6m.dylib`PyErr_FormatV [inlined] PyErr_Clear at errors.c:355 [opt] frame #2: 0x00000001003f3fb7 libpython3.6m.dylib`PyErr_FormatV(exception=0x00000001004cba18, format="%s:%d: bad argument to internal function", vargs=0x00007fff5fbfdcb0) at errors.c:841 [opt] frame #3: 0x00000001003f2c39 libpython3.6m.dylib`PyErr_Format(exception=&lt;unavailable&gt;, format=&lt;unavailable&gt;) at errors.c:860 [opt] frame #4: 0x0000000100358220 libpython3.6m.dylib`PyModule_GetDict(m=0x0000000101a5…
upvote count: 6
has comment: http://stackoverflow.com/comment/85965584
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85965225
score: 6
has comment: http://stackoverflow.com/comment/85965859

http://stackoverflow.com/a/54393709
has body: So, if I'm understanding you correctly, you're having trouble getting the right output based on what the user, or in your case the audio file, has said. E.g. the audio/user will say "Hi there!" the output may be "Something complete different". Reviewing your code, I noticed you're using three types of different audio files. Each file is speaking in a different language. When you'll open the documentation of SpeechRecognition you'll see that there is a library reference. In this library reference there will be notes on using PocketSphinx. The first thing that will stand out is that: By default, SpeechRecognition's Sphinx functionality supports only US English. Additional language packs are also available, but not included due to the files being too large I guess you have installed all the needed packages for this. I'm not going to explain that part because it's pretty self-explanatory. Anyway, the documentation also explains that you can: Once installed, you can simply specify the language using the language parameter of recognizer_instance.recognize_sphinx. For example, French would be specified with "fr-FR" and Mandarin with "zh-CN". I am not sure if the code above is yours, or you just copy and paste it from somewhere. Anyway, there are some issues with your code. You keep overriding your AUDIO_FILE variable with another file. So instead of "obtain the path to "english.wav" in the same folder as this script", you obtain the path to "chinese.flac". Now, I guess you already know what might be the problem with the "accuracy for speech to text". It's "listening" to Chinese and trying to output it as English words. It's pretty self-explanatory... To fix this, just add a language parameter and set it to the language you want it to be specified to. E.g., import speech_recognition as sr # Obtain path to "chinese.flac" in the same folder as this script from os import path # AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "english.wav") # AUDIO_FILE = path.joi…
score: 5
downvote count: 0
upvote count: 5
answers question: http://stackoverflow.com/q/49297291
type: Answer

http://stackoverflow.com/q/49338772
has comment: http://stackoverflow.com/comment/85677831
upvote count: 1
has comment: http://stackoverflow.com/comment/85677752
favorite count: 0
has answer: http://stackoverflow.com/a/49338910
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49339107
accepted answer: http://stackoverflow.com/a/49338910
tagged with: python
has title: if statements with 'str' or 'int'?
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85677808
possible better answer: http://stackoverflow.com/a/49338854
has body: My question is relatively simple. Is 'str' easier than 'int' in the following examples? slot_1 = 'med kit' if slot_1 == 'med kit': print('med kit ready') is that faster to run and better than slot_1 = 0 #0 represents med kit if slot_1 == 0: print('med kit ready') Or is the one using integers more pythonic, and runs better? What if I were to have multiple things, not just med kit. Would it still be better to use strings? If you want any more information I can edit.
has answer: http://stackoverflow.com/a/49338854
downvote count: 2

http://stackoverflow.com/q/49412717
has answer: http://stackoverflow.com/a/49412848
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/58255821
has body: def newactivation(x): if x&gt;0: return K.relu(x, alpha=0, max_value=None) else : return x * K.sigmoid(0.7* x) get_custom_objects().update({'newactivation': Activation(newactivation)}) I am trying to use this activation function for my model in keras, but I am having hard time by finding what to replace if x&gt;0: ERROR i got: File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 614, in bool raise TypeError("Using a tf.Tensor as a Python bool is not allowed. " TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if &gt;t is not None: instead of if t: to test if a tensor is defined, and >use TensorFlow ops such as tf.cond to execute subgraphs conditioned on >the value of a tensor. Can someone make it clear for me?
downvote count: 0
tagged with: activation-function
tagged with: keras
has answer: http://stackoverflow.com/a/49413194
answer count: 4
tagged with: tensorflow
favorite count: 0
type: Question
has title: Advanced Custom activation function in keras + tensorflow
upvote count: 2
possible better answer: http://stackoverflow.com/a/49412966
has answer: http://stackoverflow.com/a/61652659
accepted answer: http://stackoverflow.com/a/49412848
tagged with: python
has answer: http://stackoverflow.com/a/49412966

http://stackoverflow.com/q/49358449
has answer: http://stackoverflow.com/a/49370484
has answer: http://stackoverflow.com/a/49418066
tagged with: python
has comment: http://stackoverflow.com/comment/85723527
has title: How to get coordinates of complex RTL-SDR signal peaks?
answer count: 4
score: 0
has body: I'm able to capture signals from a RTL-SDR by using the following: from rtlsdr import * i = 0 signals = [] sdr = RtlSdr() sdr.sample_rate = 2.8e6 sdr.center_freq = 434.42e6 sdr.gain = 25 while True: samples = sdr.read_samples(1024*1024) decibel = 10*log10(var(samples)) if decibel &gt;= -10: signals.append(samples) i += 1 if i == 2: break If I plot the signals using Matplotlib and Seaborn, they look something like this: Now, what I would need is to get the coordinates of all peaks above a certain power level, e.g., -20. I found a rather promising listing of the various Python options. However, all those examples use a simple Numpy array which the different algorithms can easily work with. This was the best attempt (because my guess is that I get a complex signal from the RTL-SDR and have to "transform" it to an array with real values?): import numpy as np import peakutils.peak real_sig = np.real(signals[0]) indexes = peakutils.peak.indexes(real_sig, thres=-20.0/max(real_sig), min_dist=1) print("Peaks are: %s" % (indexes)) With these few lines added to the script above I do get some output, but, first, there are way too many values for the just five peaks above power level -20. And, second, the values don't make much sense in the given context. So, what do I need to change to get meaningful results like "Peak 1 is at 433.22 MHz"? Ideally, I should get coordinates like Peak 1: X = 433.22, Y = -18.0, but I guess I can figure that out myself once I know how to get the correct X-values.
tagged with: peakutils
has comment: http://stackoverflow.com/comment/85722604
has answer: http://stackoverflow.com/a/49370987
has comment: http://stackoverflow.com/comment/85721652
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85718312
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49369427

http://stackoverflow.com/a/49474250
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49422913
upvote count: 1
has body: I found out my error. In Flask-SQLAlchemy pagination, if nothing is found in a page, it abort(404)s. To prevent this from happening I did this: #... Post.query.paginate(per_page=10, page=page_num, error_out=False).items #the error_out=False part #... And then I handle the problems on my own such as negative page number, no posts found in page etc.
accepted answer of: http://stackoverflow.com/q/49422913
type: Answer

join
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/49324898
tags question: http://stackoverflow.com/q/49416969
tags question: http://stackoverflow.com/q/49359266
tags question: http://stackoverflow.com/q/49297376
tags question: http://stackoverflow.com/q/49426435
tags question: http://stackoverflow.com/q/49329997
tags question: http://stackoverflow.com/q/49362926
tags question: http://stackoverflow.com/q/49431864

http://stackoverflow.com/q/49395052
has answer: http://stackoverflow.com/a/49406265
has comment: http://stackoverflow.com/comment/85808682
tagged with: concatenation
answer count: 3
tagged with: pandas
score: 1
has title: Pandas DataFrames in a loop, df.to_csv()
has comment: http://stackoverflow.com/comment/85792329
upvote count: 1
favorite count: 0
type: Question
tagged with: export-to-csv
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49396141
has body: I am trying to write a df to a csv from a loop, each line represents a df, but I am finding some difficulties once the headers are not equal for all dfs, some of them have values for all dates and others no. I am writing the df using a function similar to this one: def write_csv(): for name, df in data.items(): df.to_csv(meal+'mydf.csv', mode='a') and it creates a csv for each meal (lunch an dinner) each df is similar to this: Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 or: Name Meal 22-03-18 23-03-18 25-03-18 Peter Dinner 12 10 9 I was trying to use pandas concatenate, but I am not finding a way to implement this in the function. My goal is to have the headers with all the dates (as the example of desired output), independent if the DataFrame appended to the csv have or not values in all dates. Actual output: Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 Mathew Lunch 12 11 11 10 9 Ruth Lunch 9 9 8 9 Anna Lunch 10 12 11 13 10 output with headers: Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Mathew Lunch 12 11 11 10 9 Name Meal 21-03-18 22-03-18 24-03-18 25-03-18 Ruth Lunch 9 9 8 9 Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Anna Lunch 10 12 11 13 10 Output desired: Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Peter Lunch 12 10 9 Mathew Lunch 12 11 11 10 Ruth Lunch 9 9 8 9 Anna Lunch 10 12 11 13 10
downvote count: 0
has answer: http://stackoverflow.com/a/49395370
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/49425270
has body: I need some help on this, I try to use folium in my code but keep getting this error message : Attribute Error : Map object has no attribute 'create_map' Here is what I get (and there is not create_map in the list) : dir(folium.Map) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_self_bounds', '_repr_html_', '_repr_png_', '_to_png', 'add_child' , 'add_children', 'add_tile_layer', 'add_to', 'choropleth', 'fit_bounds', 'get_bounds', 'get_name', 'get_root', 'render', 'save', 'to_dict', 'to_json'] The code is : import folium map_osm = folium.Map(location=[45.5236, -122.6750]) map_osm.create_map(path='osm.html') P.S : folium version 0.5.0 // Python 3.6.4
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85852159
has answer: http://stackoverflow.com/a/76015169
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/85852003
has title: Attribute Error : Map object has no attribute 'create_map'
answer count: 3
tagged with: folium
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85851669
has answer: http://stackoverflow.com/a/53362747
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52144758

http://stackoverflow.com/q/49372156
answer count: 1
tagged with: python
has title: Download HTML as Zip Issue
has comment: http://stackoverflow.com/comment/85754379
has comment: http://stackoverflow.com/comment/85747691
type: Question
tagged with: google-drive-api
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85746333
tagged with: google-sheets
has comment: http://stackoverflow.com/comment/85753522
score: 0
accepted answer: http://stackoverflow.com/a/50482403
type: AnsweredQuestion
has body: I'm using the google drive API to download a google sheet. Unfortunately I need to download it as an HTML to embed in an email however when I run export_request = drivesrvc.files().export_media(fileId=file_id, mimeType='application/zip') fh = io.FileIO("data.zip", "wb") downloader = apiclient.http.MediaIoBaseDownload(fh, export_request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100) The request goes through, but the zip file is empty! If I try any other file format it works just fine but the zip is always empty for some reason and I need to get the HTML. The documentation specifies that the above call should return a Zip archive containing HTML files corresponding the the worksheets in the google sheet, yet all I get is an empty Zip archive.
has answer: http://stackoverflow.com/a/50482403

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/49314033
type: Tag

http://stackoverflow.com/comment/85744618
type: AnswerComment
has text: Thanks for your answer but I actually prefer Maxim's. Its more direct.
type: Comment
comment on: http://stackoverflow.com/a/49350002
score: 0

http://stackoverflow.com/a/49340953
score: 0
has comment: http://stackoverflow.com/comment/85682405
has body: I think tis should work (it did for me): new = ['|&lt;', '@', '1', '3', '7', '0', '8', '\/'] old = ['K', 'A', 'L', 'E', 'T', 'O', 'B', 'V'] ask_user = input("Type a sentence: ") def ask_replace_letters(): ask_user2=input("Do you want to replace letters? ").upper()#different name for variable if ask_user2== "YES": ask_user1 = input("What letters do you want to replace? ").upper() letters=[]#letters to replace for letter in ask_user1: if letter not in old: print("This program cannot replace the letter: ", letter)#may be repeated else: letters+=letter#add letter to letters to replace print(replace_letters(letters))#replace them elif ask_user2 == "NO": print(replace_letters()) else: print("Please enter yes or no.") def replace_letters(letters=[]):#input for which chars to replace, rather than all result = ask_user.upper()#so it will match for i in letters:#for each to replace pos=old.index(i)#get pos in old/new lists result = result.replace(old[pos], new[pos])#replace return result.lower()#lower, since we have done upper ask_replace_letters() This will, however, make it all lower. Remove the last line of replace letters to make it all upper.
type: Answer
has comment: http://stackoverflow.com/comment/85682563
answers question: http://stackoverflow.com/q/49340762

http://stackoverflow.com/comment/85844757
score: 0
comment on: http://stackoverflow.com/q/49421958
type: Comment
has text: Same way you execute every other executable, unless you know more about the script itself.
type: QuestionComment

http://stackoverflow.com/a/49332400
answers question: http://stackoverflow.com/q/49331852
has comment: http://stackoverflow.com/comment/85667045
upvote count: 2
has comment: http://stackoverflow.com/comment/85666993
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85666985
type: AcceptedAnswer
has body: Decorators can be used to change the behaviour of functions in such ways by making them stateful. Here, we can inject a dict argument with some state that the function can update and reuse through its lifetime. def inject_state(state): def wrapper(f): def inner_wrapper(*args, **kwargs): return f(state, *args, **kwargs) return inner_wrapper return wrapper @inject_state({'print': True}) def myFunction(state, first, second, third): if first == True: pass # Do this elif second == True: c = third * 3 # We print provided 'print' is True in our state if state['print']: print(c) # Once we printed, we do not want to print again state['print'] = False return c else: print("Error") Here you see that the second call indeed does not print anything. myFunction(False, True, 1) # 3 # prints: 3 myFunction(False, True, 1) # 3 # prints nothing
accepted answer of: http://stackoverflow.com/q/49331852
has comment: http://stackoverflow.com/comment/85667011

http://stackoverflow.com/q/49333835
has title: Trying to download a csv file with data after running a search query using Python 3. Don't know if the code works
answer count: 1
type: Question
tagged with: python-3.x
tagged with: download
type: UnansweredQuestion
has body: Is this the correct code to run the search query and download the resulting csv file (you have to click Download CSV on the website to download the file). If not, how should i modify it and where should I look for the downloaded file? In the default Downloads folder or elsewhere? import requests, csv, urllib from urllib import request URL = 'http://families.naeyc.org/programs/csv/CSV?attach=list' response = urllib.request.urlopen(URL).read() with open('file.csv','wb') as fx: fx.write(response)
tagged with: python
has answer: http://stackoverflow.com/a/49334076
score: 0

http://stackoverflow.com/a/49344475
accepted answer of: http://stackoverflow.com/q/49341214
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49341214
has body: If you are not stuck with using joblib you could try some standard library parallel processing modules. In python2/3 multiprocessing.Pool is available and provides functions for mapping a task across parallel threads. A simplified version would look like this: from multiprocessing import Pool import requests HEADERS = {} # define headers here def parallel_request(symbols): response = requests.get('https://api01.iq.questrade.com/v1/symbols?names={}'.format(symbols), headers=HEADERS) return response.json() if __name__ == '__main__': p = Pool() batch_result = ['AAME,ABAC,ABIL,...', 'BLDP,BLIN,BLNK,...', 'CUR,CVONW,CXDC,...', ...] p.map(parallel_request, batch_result) # will return a list of len(batch_result) responses There are asynchronous and iterable versions of map that you would probably want for larger sized jobs, and of course you could add parameters to your parallel_requests task to avoid hard coding things like I did. A caveat with using Pool is that any arguments passed to it have to be picklable. In python3 the concurrent.futures module actually has a nice example of multithreaded url retrieval in the docs. With a little effort you could replace load_url in that example with your parallel_request function. There is a version of concurrent.futures backported to python2 as the futures module, as well. These might require a bit more work in refactoring, so if there is a solution that sticks with joblib feel free to prefer that. On the off-chance that your problem is a bug in joblib, there are plenty of ways you could do this in a multithreaded fashion with standard library (albeit with some added boilerplate).
type: Answer

http://stackoverflow.com/a/49368313
has body: One way is to create an array of your date range and use numpy.digitize. df['Date'] = pd.to_datetime(df['Date'], dayfirst=True) date_ranges = pd.date_range(df['Date'].min(), df['Date'].max(), freq='5D')\ .astype(np.int64).values df['Bin'] = np.digitize(df['Date'].astype(np.int64).values, date_ranges) Result: ID Date Bin 0 111 2018-01-01 1 1 222 2018-01-05 1 2 333 2018-01-07 2 3 444 2018-01-08 2 4 555 2018-01-09 2 5 666 2018-01-13 3
answers question: http://stackoverflow.com/q/49367995
type: Answer
score: 0

http://stackoverflow.com/q/49309779
has answer: http://stackoverflow.com/a/49310671
accepted answer: http://stackoverflow.com/a/49310671
score: 0
favorite count: 0
type: Question
answer count: 1
has body: I am on a closed network (aka no access to the internet) thus I need to create my own PyPi server. I am following the instructions here: How to set up and use a private PyPI repo The only differences: I did not do was set up Apache authentication. No need for it. I put everything in /src/pypi (all pointers were updated) I was able to get Apache operational and (supposedly) got my ~/.pip/pip.conf file operational. Here are the contents: [global] extra-index-url=https://pypi.myserver.com/pypi/ trusted-host = pypi.myserver.com When I try to run the command: pip install foobar-utils I get the following: Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at xxx&gt;: Failed to establish a new connection: [Errorno -2] Name or service not known',)' /simple/foobar-utils I know it's hitting apache, I see it in my logs. Any help would be great. Thanks
tagged with: pip
upvote count: 1
tagged with: python
has title: Private PyPi Repository in Closed Network
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/85752405
has text: When I remove encode('utf-8'),a mistake has happened.UnicodeEncodeError: 'cp932' codec can't encode character '\u554a' in position 48: illegal multibyte sequence Call stack: File "test1.py", line 2161, in <module> logger.error('aaaくれ対応我啊')
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49375525

http://stackoverflow.com/comment/85850735
type: AnswerComment
has text: Thanks so much Pankaj Joshi ! I found the issue. In essence you are right. But if you install spyder inside your environment, and you have a python2.x and not 3.x version, then spyder will automatically link to that version of python. So be sure that your new env. actually is running the desired python version.
comment on: http://stackoverflow.com/a/49408240
type: Comment
score: 0

http://stackoverflow.com/comment/85818213
score: 0
has text: Successors are a node's neighbours in one specific direction. That's why I need `successorTable` which is a graph's attribute, not a node's. I would however use `Node.neighbours` in a non-oriented Graph.
comment on: http://stackoverflow.com/q/49408230
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49325937
tagged with: numpy
has comment: http://stackoverflow.com/comment/85686583
tagged with: physics
tagged with: nested-loops
has title: Projectile motion sim, index out of bounds error, nested for/while loops
tagged with: python
has comment: http://stackoverflow.com/comment/85709040
has answer: http://stackoverflow.com/a/49369331
accepted answer: http://stackoverflow.com/a/49369331
has body: I'm trying to graph the optimum angle of launch as a function of the mass and graph it. for each element of mlist I want it to calculate the distance traveled for that m for each element of thetalist, then take the highest distance for that m and get the theta that gave that answer and make a new list of these so called theta_optimum and plot it vs mlist. Here is my code: import matplotlib.pylab as plt import numpy as np import math ############# Die = 10.0 B = 1.6e-4 b = B*Die g = 9.81 tmax = 1000 dt = 0.01 v = 100.0 mlist = np.arange(1.0, 100.0, 1.0) thetalist = np.arange(0.1, math.pi / 2.0, 0.1) theta_op = [] for j in range(len(mlist)): for i in range(len(thetalist)): vy = math.sin(thetalist[i]) * v vx = math.cos(thetalist[i]) * v t = 0.0 x = 0.0 y = 0.0 xlist = [] while y &gt;= 0.0: vx1 = -b/mlist[j]*vx vx = vx + vx1*dt dx = vx * dt x = x + dx vy1 = -g-b/mlist[j]*vy vy = vy + vy1 * dt dy = vy * dt y = y + dy t = t + dt xlist.append(x) theta_op.append(thetalist[xlist.index(max(xlist))]) plt.plot(mlist, theta_op, color='red') plt.show() The error I am getting is: line 39, in &lt;module&gt; theta_op.append(thetalist[xlist.index(max(xlist))]) IndexError: index 202 is out of bounds for axis 0 with size 15 My question is how do I fix this error in my code and why has it arisen. I know the physics is right but as I am new to coding I am not sure if the way I have made my lists and loops is correct. I have looked for other questions like this but haven't found any.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85709201
score: 0
has comment: http://stackoverflow.com/comment/85709121
has comment: http://stackoverflow.com/comment/85709247
tagged with: index-error
has comment: http://stackoverflow.com/comment/85653839
answer count: 1
type: Question

databricks
tag name: databricks
tags question: http://stackoverflow.com/q/49286282
type: Tag
tags question: http://stackoverflow.com/q/49303286
tags question: http://stackoverflow.com/q/49290029
tags question: http://stackoverflow.com/q/49318402

http://stackoverflow.com/comment/85752124
comment on: http://stackoverflow.com/a/49356663
score: 0
type: Comment
has text: The specific optimization here is that when you do `a + b`, it always calls `type(a).__add__(a, b)` instead of `a.__getattribute__('__add__')(b)`. The first one technically should call `type(type(a)).__getattribute__(type(a), '__add__')`, so you can make the proxy work by messing with the metaclass.
type: AnswerComment

http://stackoverflow.com/q/49415106
type: Question
has title: Opening a PDF based on URL
accepted answer: http://stackoverflow.com/a/49450420
tagged with: django
tagged with: python
has body: So, my goal here is for a user to click the link for an invoice, and it opens up a window with the PDF of that invoice displayed. Currently, I'm getting the following error: NoReverseMatch at /laptops/invoices/ Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/wordpress-pdf-invoice-plugin-sample.pdf'}' not found. 1 pattern(s) tried: ['laptops\\/invoices\\/(?P<invoice>[^/]+)\\/$'] Bad programming practices, I know. I just wanted to get it to work before I cleaned it up a bit, but I don't know what I'm doing wrong. urls.py urlpatterns = [ path('',views.laptop_list, name ="list"), path('add/',views.laptop_add,name="add"), path('invoices/', views.invoice_list,name="invoices"), path('invoices/<str:invoice>/', views.pdf_view, name ="pdfview") ] views.py def pdf_view(request, invoice): invoicename=Laptop.objects.get(invoicename=invoice) pdfpath = settings.MEDIA_ROOT with open(pdfpath+'/'+invoicename, encoding="latin-1") as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') return response laptop_invoices.html View invoices {%for i in invoices%} {{i.invoice}} {%endfor%}
has comment: http://stackoverflow.com/comment/85833807
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49450420
has comment: http://stackoverflow.com/comment/85834404
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/49391652
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46864740
tagged with: python
has body: I am trying to use Python3 and Pandas to shape a dataframe. My current frame looks like this: Col1 Col2 Col3 0 X Y 1 Z B I am trying to drop the row if the second column is blank (so drop row 2, index 1, only here), but the name of the second column can change depending on the file being used so Im attempting to use ix but to no avail... c = df.ix[:,1] df.dropna(subset=c, how='all', inplace=True) Any advice?
has answer: http://stackoverflow.com/a/49392261
has answer: http://stackoverflow.com/a/49396110
has comment: http://stackoverflow.com/comment/85785170
has comment: http://stackoverflow.com/comment/85793162
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85793164
has comment: http://stackoverflow.com/comment/85784887
has title: Pandas: Drop row if second column is blank
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85785074
has comment: http://stackoverflow.com/comment/85786700

http://stackoverflow.com/q/49384846
has comment: http://stackoverflow.com/comment/85773533
has comment: http://stackoverflow.com/comment/85771333
answer count: 1
type: Question
has body: I have a dataframe with days as indexes, categories as columns, and each element is a set of items corresponding to each day. I read that "keeping lists in a frame, while allowed, it not efficient at all": corresponding pandas-dev issue I need to be able to build columnwise unions and intersections of these lists, and to use each of them in queries. What would you suggest as an efficient alternative?
has comment: http://stackoverflow.com/comment/85771378
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49385349
score: 0
has comment: http://stackoverflow.com/comment/85770501
has title: What's the best alternative to using lists as elements in a pandas dataframe?
has answer: http://stackoverflow.com/a/49385349
tagged with: pandas

http://stackoverflow.com/comment/85881008
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49439158
has text: But dataframe already has X column..Just use `df['X']`. As I said, description is not most helpful here.
type: Comment

http://stackoverflow.com/q/49372231
has body: I am working on building a site to pull data from several sources, combine it into one database and then using thus data to calculate number for each respected team. I am fairly new to python, peewee, and Selenium. Here is all of my code: from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup from models import * import os # File I/O import time import shutil import glob import configparser config_parser = configparser.ConfigParser() config_parser.read("config.ini") #Var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] download_dir = os.path.abspath('./downloads/') ids = ['XXXXXX', 'DDDDDD', 'WWWWWW', 'AAAAAAA', 'VVVVVV', 'FFFFFFF'] filelist = glob.glob(download_dir + '/*.html') dbpath = ('./db') def store_data(download_dir): # if dbpath == ' ': # print(dbpath) # else: # print('DataBase exists, will now attempt to remove!') # os.remove('./db/budget.db') # print('Removed') database.connect() database.create_tables([Charge], safe=False) database.close() for root, dir, files in os.walk(download_dir): for file in files: print(file) file_markup = '' with open(os.path.abspath(os.path.join(download_dir, file)), 'r') as html: file_markup = html.read() if file_markup == '': print('ERROR: File was not read') print('Reading {0} into BS4'.format(file)) soup = BeautifulSoup(file_markup, 'html.parser') print('File parsed') data = [] table = soup.find('table') #, attrs={'class':'lineItemsTable'} # First 56 tr's are headings rows = table.find_all('tr') # …
tagged with: peewee
downvote count: 0
answer count: 1
tagged with: selenium
score: 1
upvote count: 1
has title: Database connection problems
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49372488
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49372488
tagged with: python

http://stackoverflow.com/comment/85689488
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49344388
has text: okay ch essentially then sticks to a single value after i reset it is there a way for ch to be part of the loop after
type: Comment

http://stackoverflow.com/q/49341424
has comment: http://stackoverflow.com/comment/85683001
has title: List comprehensions with nested lists
has comment: http://stackoverflow.com/comment/85683058
accepted answer: http://stackoverflow.com/a/49341505
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85683004
has comment: http://stackoverflow.com/comment/85683021
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49341505
has comment: http://stackoverflow.com/comment/85682953
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/85683140
has comment: http://stackoverflow.com/comment/85683024
type: AnsweredQuestion
has body: Would like to ask question related to nested lists in Python. I have a nested list list_1 = [[1,3,0,1], [1,1,0,2,3,0,4,], [2,1,2,2,3,4]] I want to perform rounding and dision operation on nested list but keep it grouped as it is now (to make it more clear I need to flatten list perform operations and that unflatten it again in same groups). For example the result for list 'list_1' after division by 2 shoud be list_2 = [[0.5,1.5,0,0.5],[0.5,0.5,0,1,1.5,0,2],[1,0.5,1,1,1.5,2]] The code I use to perform this for signle list is below: list_2 = [round(b,2) for b in [a / 2 for a in list_1]] Could you please suggest way to solve this issue. Currently I am getting error "unsupported operand type(s) for /: 'list' and 'float'" Thank you.
upvote count: 0
tagged with: list
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/85746508
comment on: http://stackoverflow.com/a/49356056
type: Comment
type: AnswerComment
has text: In my example, `Position` is basically an `IntEnum`.
score: 0

http://stackoverflow.com/comment/85838582
comment on: http://stackoverflow.com/a/49418309
type: AnswerComment
score: 0
type: Comment
has text: @Jim421616, I recommend you use another function, maybe `format_output()`, which runs `translate()` and prints in the format you desire. It's still a good idea to have your logic functions `return` values.

http://stackoverflow.com/a/49330273
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85666841
has comment: http://stackoverflow.com/comment/85665939
accepted answer of: http://stackoverflow.com/q/49329997
has comment: http://stackoverflow.com/comment/85666747
has comment: http://stackoverflow.com/comment/85678193
has comment: http://stackoverflow.com/comment/85686675
answers question: http://stackoverflow.com/q/49329997
type: Answer
score: 2
upvote count: 2
has body: Here is one way to accomplish what you're trying to do. First use merge() twice. First on air_id, then on hpg_id. For both, ignore the trivial case when the key is an empty string. result = df2\ .merge( df1[df1['air_id']!=''].drop(['hpg_id'], axis=1), on=['air_id'], how='left' )\ .merge( df1[df1['hpg_id']!=''].drop(['air_id'], axis=1), on=['hpg_id'], how='left' ) print(result) # air_id hpg_id ignore_me_x latitude_x longitude_x ignore_me_y \ #0 hpg1 NaN NaN NaN 91 #1 air2 hpg2 92.0 102.0 52.0 92 #2 hpg3 NaN NaN NaN 93 # # latitude_y longitude_y #0 101 51 #1 102 52 #2 103 53 However, this creates duplicates for the columns you want. (I drop the other join key on each call to merge to avoid duplicate column names for those.) We can coalesce these values by adapting one of the methods described on this post. cols = ['latitude', 'longitude'] colsx = list(map(lambda c: c+"_x", cols)) # list needed for python3 colsy = list(map(lambda c: c+"_y", cols)) # list needed for python3 result[cols] = pd.DataFrame( np.where(result[colsx].isnull() == True, result[colsy], result[colsx]) ) result = result[['air_id', 'hpg_id'] + cols] print(result) # air_id hpg_id latitude longitude #0 hpg1 101.0 51.0 #1 air2 hpg2 102.0 52.0 #2 air3 103.0 53.0 UPDATE In the case where the merge produces duplicate entries, you can use pandas.DataFrame.drop_duplicates(). result = result.drop_duplicates()
downvote count: 0

http://stackoverflow.com/q/49392693
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: xpath
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49392944
has body: I am having trouble selecting a particular dropdown element via Selenium. The website is password protected so I have shared a snapshot of it. The attached snapshot shows what is visible when I right-click on the element and choose 'Inspect'. I am selecting XPATH which I have pasted in the pictures address bar to show what it is. Then I use the following line in my script to click it but it says element is not visible. WebDriverWait(Chromedriver, 240).until(EC.presence_of_element_located((By.XPATH, '//*[@id="dateRangeType"]'))).click() I have noticed that this element does not have a class to it. If that is the reason it is not working, how would I select an element with id, name but no class?
downvote count: 0
upvote count: 1
tagged with: python
tagged with: selenium-chromedriver
has title: select a dropdown box using Selenium python

http://stackoverflow.com/comment/85736600
type: AnswerComment
comment on: http://stackoverflow.com/a/49367804
score: 1
has text: and as an advice, I would select something like `article.search-listing` as the real container, then in only one loop i would be able to find all needed children.
type: Comment

http://stackoverflow.com/comment/85719432
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49359470
has text: @Aran-Fey Exactly. :)
type: Comment

http://stackoverflow.com/a/49359884
has comment: http://stackoverflow.com/comment/85723559
has comment: http://stackoverflow.com/comment/85769350
type: Answer
has comment: http://stackoverflow.com/comment/85726440
has comment: http://stackoverflow.com/comment/85726224
has comment: http://stackoverflow.com/comment/85753736
has comment: http://stackoverflow.com/comment/85725253
has comment: http://stackoverflow.com/comment/85726447
has comment: http://stackoverflow.com/comment/85721103
has comment: http://stackoverflow.com/comment/85723231
has comment: http://stackoverflow.com/comment/85724028
answers question: http://stackoverflow.com/q/49355891
has comment: http://stackoverflow.com/comment/85726400
has comment: http://stackoverflow.com/comment/85720946
has comment: http://stackoverflow.com/comment/85724646
has comment: http://stackoverflow.com/comment/85724138
has comment: http://stackoverflow.com/comment/85721588
has comment: http://stackoverflow.com/comment/85723781
score: 1
has comment: http://stackoverflow.com/comment/85721548
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85724231
has comment: http://stackoverflow.com/comment/85724006
accepted answer of: http://stackoverflow.com/q/49355891
upvote count: 1
has comment: http://stackoverflow.com/comment/85726049
has body: I think need: out = pd.DataFrame({ 'Date': pd.to_datetime(['2015-01-01','2015-05-01','2015-07-01','2015-10-01','2015-04-01','2015-12-01','2016-01-01','2016-02-01','2015-05-01', '2015-10-01']), 'Churn': ['Yes'] * 8 + ['No'] * 2 }) print (out) Churn Date 0 Yes 2015-01-01 1 Yes 2015-05-01 2 Yes 2015-07-01 3 Yes 2015-10-01 4 Yes 2015-04-01 5 Yes 2015-12-01 6 Yes 2016-01-01 7 Yes 2016-02-01 8 No 2015-05-01 9 No 2015-10-01 df = (out.loc[out['Churn'] == 'Yes'] .groupby([out["Date"].dt.year,out["Date"].dt.quarter])["Churn"] .count() .rename_axis(('year','quarter')) .reset_index(name='count')) print(df) year quarter count 0 2015 1 1 1 2015 2 2 2 2015 3 1 3 2015 4 2 4 2016 1 2 For separate DataFrames by years is possible create dictionary of DataFrames: dfs = dict(tuple(out.groupby(out['Date'].dt.year))) print (dfs) {2016: Churn Date 6 Yes 2016-01-01 7 Yes 2016-02-01, 2015: Churn Date 0 Yes 2015-01-01 1 Yes 2015-05-01 2 Yes 2015-07-01 3 Yes 2015-10-01 4 Yes 2015-04-01 5 Yes 2015-12-01 8 No 2015-05-01 9 No 2015-10-01} print (dfs.keys()) dict_keys([2016, 2015]) print (dfs[2015]) Churn Date 0 Yes 2015-01-01 1 Yes 2015-05-01 2 Yes 2015-07-01 3 Yes 2015-10-01 4 Yes 2015-04-01 5 Yes 2015-12-01 8 No 2015-05-01 9 No 2015-10-01 Tenure column looks like this out["tenure"].unique() Out[14]: array([ 8, 15, 32, 9, 48, 58, 10, 29, 1, 66, 24, 68, 4, 53, 6, 20, 52, 49, 71, 2, 65, 67, 27, 18, 47, 45, 43, 59, 13, 17, 72, 61, 34, 11, 35, 69, 63, 30, 19, 39, 3, 46, 54, 36, 12, 41, 50, 40, 28, 44, 51, 33, 21, 70, 23, 16, 56, 14, 62, 7, 25, 31, 60, 5, 42, 22, 37, 64, 57, 38, 26, 55]) It contains no of months, it seems like 1 to 72. I need to split tenure column into "range". For example, this column contains 1 to 72 numbers, need to range up to 4 range. like 1 to 18 --&gt; 1 range 19 to 36 --&gt; 2nd range 37 to 54 --&gt; 3rd range like that here i found quarterlywise churn count and with that churn count later i found churn rate with churn count and total count. quarterly_churn_yes = out.loc[out[…
has comment: http://stackoverflow.com/comment/85720699
has comment: http://stackoverflow.com/comment/85723620
has comment: http://stackoverflow.com/comment/85755667
has comment: http://stackoverflow.com/comment/85721176
has comment: http://stackoverflow.com/comment/85726575
has comment: http://stackoverflow.com/comment/85726297
has comment: http://stackoverflow.com/comment/85721061
has comment: http://stackoverflow.com/comment/85723760
has comment: http://stackoverflow.com/comment/85727181
has comment: http://stackoverflow.com/comment/85725197
has comment: http://stackoverflow.com/comment/85724195
has comment: http://stackoverflow.com/comment/85723193
has comment: http://stackoverflow.com/comment/85754354
has comment: http://stackoverflow.com/comment/85767936
has comment: http://stackoverflow.com/comment/85725293
has comment: http://stackoverflow.com/comment/85723826
has comment: http://stackoverflow.com/comment/85725063
has comment: http://stackoverflow.com/comment/85723985

http://stackoverflow.com/q/49286614
tagged with: django-models
tagged with: python
has body: In models.py I have following models: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') town = models.CharField(max_length=100) project = models.ManyToManyField(Project) def __str__(self): return str('Advanced user informations') class News(models.Model): title = models.CharField(max_length=255, blank=False) content = HTMLField() author = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) In my views.py I have: def news(request): news_list = News.objects.all().order_by('-id') paginator = Paginator(news_list, 5) page = request.GET.get('page') news = paginator.get_page(page) return render(request, 'news.html', {'news': news}) Now I want to achieve that a User can only see news for a project he participates. Something like: News.objects.filter(News with a project that the User is linked to) But I am not sure what could be a valid way to solve this. Maybe someone has a tip?
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49287062
tagged with: django
has title: Django filter from another model
type: Question
has answer: http://stackoverflow.com/a/49290599
accepted answer: http://stackoverflow.com/a/49290599
possible better answer: http://stackoverflow.com/a/49287062

http://stackoverflow.com/a/49418683
has comment: http://stackoverflow.com/comment/85839852
accepted answer of: http://stackoverflow.com/q/49418578
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85839115
type: AcceptedAnswer
has body: In your serializer fields you can use the source argument to specify a field on the model. If you're trying to access the reverse relation from the Client model you should be using the MODELNAME_set field on as your source. This field is added to the other end of a ForeignKey by Django. I.e. assignment = PrimaryKeyRelatedField( source='clientassignment_set', many=True, read_only=True, ) Note that with read_only=True you don't need to specify a queryset either. Your other choice would be to specify a related_name field on your ForeignKey's which overrides the MODELNAME_set auto-generated fields, and set these to "assignment" and "detail".
upvote count: 5
has comment: http://stackoverflow.com/comment/85839150
answers question: http://stackoverflow.com/q/49418578
has comment: http://stackoverflow.com/comment/85937256
has comment: http://stackoverflow.com/comment/85839314
type: Answer

http://stackoverflow.com/comment/85841917
type: Comment
has text: Interesting. This seems promising but a couple of questions though, what do you mean here when you say "Since, there is only one class we can't continue this process for this data"? Is it because there's just one target label in y_train? Also, once I have the predictions through this, how can I use them to check the accuracy of the predictions? Again, sorry if I don't make sense.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49398948

http://stackoverflow.com/comment/85789911
comment on: http://stackoverflow.com/q/49393269
type: QuestionComment
has text: Good catch. I updated post to snip[0][3]. I went ahead and changed my code so I can work with lists instead of tuples. Should be easier to handle now.
score: 0
type: Comment

http://stackoverflow.com/q/49321272
answer count: 1
tagged with: pyqt5
type: Question
tagged with: python-3.x
has body: I am trying to show/disappear some widgets in QHBoxLayout dependently on signal changes from QCheckBox. I have read some articles (PyQt How to remove a layout from a layout; pyqt: how to remove a widget?) how to remove the layouts/widgets but still have not managed to amend the code so that it worked correctly. After first click the new widgets in QHBoxLayouts appear but after another click (unchecking the button) it simply does not work and these do not disappear. At third click it crashes. Here below is a snippet of my code: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class CheckableComboBox(QComboBox): def __init__(self, parent = None): super(CheckableComboBox, self).__init__(parent) self.view().pressed.connect(self.handleItemPressed) self.setModel(QStandardItemModel(self)) self.setStyleSheet("QComboBox{" "font-size:11px;" "color:black;" "background-color:white;" "border:1px solid black;" "padding:1px;""}") self.setEditable(True) self.lineEdit().setAlignment(Qt.AlignCenter) self.lineEdit().setReadOnly(True) self.setMinimumSize(200,40) def handleItemPressed(self, index): item = self.model().itemFromIndex(index) if item.text() != ' ' and item.checkState() == Qt.Checked: item.setCheckState(Qt.Unchecked) if item.text() != ' ' and item.checkState() != Qt.Checked: item.setCheckState(Qt.Checked) class Main(QWidget): def __init__(self, parent = None): super(Main, self).__init__(parent) self.years = [' ', '2017', '2018', '2019', '2020'] self.months = [' ', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] self.metrics = [' ', 'Seller', 'Section', 'Store'] self.units = [' ', 'Number of Pieces Sold', 'Total Value'] self.setWindowTitle('Dialog') self.resize(360, 200) self.sMetric = QLabel('Select metric(s):') self.sUnit = QLabel('Select unit(s):') self.sYear = QLabel('Select year(s):') self.sMonth = QLabel('Select month(s):') self.timeWise = QCheckBox('Time-wise Overview') self.timeWise.stateChanged.connect(self.…
linked to: http://stackoverflow.com/q/5899826
linked to: http://stackoverflow.com/q/37564728
has title: Removing widgets in QHBoxLayout when QCheckBox signal changes
tagged with: python
has answer: http://stackoverflow.com/a/49322898
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49420107
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41810246
has title: Issue installing PySFML with pipenv
has answer: http://stackoverflow.com/a/50564321
downvote count: 0
tagged with: pip
score: 1
upvote count: 1
has body: I tried following the instructions here to install PySFML. pip flat out would not accept this command: pip git+https://github.com/Sonkun/python-sfml?egg=pySFML ERROR: unknown command "git+https://github.com/Sonkun/python-sfml?egg=pySFML" I tried with pipenv (which is what I ideally want to use anyway) and it gave: pipenv install git+https://github.com/Sonkun/python-sfml?egg=pySFML zsh: no matches found: git+https://github.com/Sonkun/python-sfml?egg=pySFML I changed the url to be a # instead of a ? and it seemed to start working but then: Installing git+https://github.com/Sonkun/python-sfml#egg=pysfml… ⠦Warning: You installed a VCS dependency in non–editable mode. This will work fine, but sub-dependencies will not be resolved by $ pipenv lock. To enable this sub–dependency functionality, specify that this dependency is editable. Collecting pysfml from git+https://github.com/Sonkun/python-sfml#egg=pysfml Cloning https://github.com/Sonkun/python-sfml to /tmp/pip-build-7z0jrlmi/pysfml Error: An error occurred while installing git+https://github.com/Sonkun/python-sfml#egg=pysfml! No files/directories in /tmp/pip-build-7z0jrlmi/pysfml/pip-egg-info (from PKG-INFO) (Note: switching ? to # gives the same error for pip) How can I proceed from here to get pipenv to install PySFML?
answer count: 1
favorite count: 0
tagged with: pipenv
type: Question

http://stackoverflow.com/comment/85659886
comment on: http://stackoverflow.com/q/49328936
type: Comment
has text: What logic exactly would possibly yield that ordering? (`30 883 547 898`) None of the answers attempt to answer the question since they ignore your strange and unexplained desired order, as @janos points out. EDIT: Brendan's does respect the order you ask for.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85713897
type: Comment
has text: The documentation suggests you should? That might be the problem you have, since the error also suggests the same (`ConfigParser` is failing)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49293729

http://stackoverflow.com/comment/85596876
has text: Is there any other field in `Instrument_df` ? If no, your model seems wrong...
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49297376

http://stackoverflow.com/q/49334113
has body: This is my Siamese Network, features are 98 images encoded as numpy ndarray which works fine, labels are 0,1,2,3,4 and i.e. they are converted to onehot using tensorflow later, works fine. The mode is "TRAIN" for now. I am following and editing the code of mnist dataset example of tensorflow. I have 98 images which can be of class 0..4. Everything works fine until logits, its dimension not being the same as my labels is the issue. def siamese_network(features, labels, mode): """Model function for Siamese Network""" input_layer = tf.reshape(features, [-1, 28, 28, 1]) conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.layers.dropout( inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN) logits = tf.layers.dense(inputs=dropout, units=5) print(logits) #gives (294,5) predictions = { "classes": tf.argmax(input=logits, axis=1), "probabilities": tf.nn.softmax(logits, name="softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=5) print(onehot_labels) #dimension is (98,5) print(logits) # dimension is (294,5) #error in this line,until here everything is fine loss = tf.losses.softmax_cross_entropy( onehot_labels=onehot_labels, logits=logits) The error I got at the loss line is this:- ValueError: Shapes (294, 5) and (98, 5) are incompatible I tried playing with "pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) , changing poolsize to [5,5]" and the dimensions of l…
has comment: http://stackoverflow.com/comment/85676898
has comment: http://stackoverflow.com/comment/85676594
tagged with: python
has comment: http://stackoverflow.com/comment/85676947
has comment: http://stackoverflow.com/comment/85677027
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85677150
type: UnansweredQuestion
has title: Using onehot labels and matching dimensions in tensor flow
has comment: http://stackoverflow.com/comment/85676988
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85677179
has comment: http://stackoverflow.com/comment/85676753
tagged with: dimensions
has comment: http://stackoverflow.com/comment/85677080

http://stackoverflow.com/a/49413482
answers question: http://stackoverflow.com/q/49413345
score: 1
type: Answer
has body: No, in order to do that, you would need to create a separate model Contact and join to it from Family using a OneToOneField if there can only be one contact per family, or using a ForeignKey in your Contact model if there can be more than one contact per family.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49413345
upvote count: 1

http://stackoverflow.com/a/49386355
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49370995
has comment: http://stackoverflow.com/comment/85781367
score: 1
has body: I suppose you plainly forgot to press "save" after adding the value=… stuff. If I replay your problem outer = [["name1",1],["name2",2],["name3",3]] # this must have been your original approach and was the same as in the linked question ll = [lambda: inner[1] for inner in outer] print(ll[0](), ll[1](), ll[2]()) # gives 3 3 3 # your approach ll = [lambda value=inner[1]: value for inner in outer] print(ll[0](), ll[1](), ll[2]()) # gives 1 2 3 # alternative approach ll = [lambda value=inner: value[1] for inner in outer] print(ll[0](), ll[1](), ll[2]()) # gives 1 2 3 As was mentioned in the previously linked question, the lambda always accesses the inner variable via its closure, only getting its last and persisting value. The alternative approaches go the way to link the lambda to the value which is current at creation time and should definitely work. (Note that instead of doung things with buttons, I concentrate on the labda problem.) Another way could be to have a function which creates "printers" as needed: def printer(value): return lambda: print(value) With them, you can easily create lambdas which do as you want: print the given value, such as button.clicked.connect(printer(inner[1]))print(value))
answers question: http://stackoverflow.com/q/49370995
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85641322
comment on: http://stackoverflow.com/a/49292362
has text: @user3087409 Yes,The underlying concept is same, whereas the solution is specific to this problem. Also you said it didn't worked for you. So changed code to your scenario and posted.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/59402535
has body: I was receiving the same selenium trace error: WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127 My issue was due to using a different version of chromedriver (version 78) than browser (version 79) when trying to manually run the chromedriver I would see Segmentation fault (core dumped) Once I updated my chromedriver to match the browser it was able to start successfully Starting ChromeDriver 79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-heads/3945@{#614}) on port 9515 Only local connections are allowed. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49323099

matching
tags question: http://stackoverflow.com/q/49297349
type: Tag
tag name: matching

sqlite
tags question: http://stackoverflow.com/q/49304114
tags question: http://stackoverflow.com/q/49362017
tags question: http://stackoverflow.com/q/49282199
tags question: http://stackoverflow.com/q/49341165
tags question: http://stackoverflow.com/q/49438354
tags question: http://stackoverflow.com/q/49383930
tags question: http://stackoverflow.com/q/49388200
tags question: http://stackoverflow.com/q/49439339
tags question: http://stackoverflow.com/q/49360525
tags question: http://stackoverflow.com/q/49306266
tags question: http://stackoverflow.com/q/49332259
type: Tag
tags question: http://stackoverflow.com/q/49403423
tags question: http://stackoverflow.com/q/49395423
tags question: http://stackoverflow.com/q/49407991
tags question: http://stackoverflow.com/q/49383386
tags question: http://stackoverflow.com/q/49284203
tags question: http://stackoverflow.com/q/49288618
tags question: http://stackoverflow.com/q/49331935
tags question: http://stackoverflow.com/q/49336469
tags question: http://stackoverflow.com/q/49420836
tags question: http://stackoverflow.com/q/49306456
tags question: http://stackoverflow.com/q/49436746
tags question: http://stackoverflow.com/q/49355011
tags question: http://stackoverflow.com/q/49334636
tags question: http://stackoverflow.com/q/49342139
tags question: http://stackoverflow.com/q/49427601
tags question: http://stackoverflow.com/q/49283494
tag name: sqlite
tags question: http://stackoverflow.com/q/49340877
tags question: http://stackoverflow.com/q/49368505
tags question: http://stackoverflow.com/q/49395393

http://stackoverflow.com/q/49306762
type: Question
has answer: http://stackoverflow.com/a/49308083
accepted answer: http://stackoverflow.com/a/49308083
has comment: http://stackoverflow.com/comment/85627127
answer count: 1
tagged with: model-mommy
tagged with: django
has title: How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
tagged with: python
tagged with: unit-testing
has body: I am trying to test a date filter but have been unable to set the created date using mommy.make(). When I make the objects with model mommy the created field is set to the time the objects were created rather than what I passed in with mommy.make() def test_mommy(self): today = arrow.now() yesterday = today.replace(days=-1) mommy.make('Model', created=today.naive) mommy.make('Model', created=yesterday.naive) model_1_created = Model.objects.all()[0].created model_2_created = Model.objects.all()[1].created self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d')) This test fails with the Assertion Error: AssertionError: '2018-03-15' == '2018-03-15' I may have a misunderstanding of how model_mommy creates these objects. But I would think this should create it and set the created dates properly. Though it looks like the default TimeStampedObject behavior is taking over.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85990887
score: 0

http://stackoverflow.com/a/49322010
accepted answer of: http://stackoverflow.com/q/49321748
has body: There is no such method find_element_by_class. Use this method instead: find_element_by_class_name http://selenium-python.readthedocs.io/locating-elements.html#locating-elements-by-class-name
score: 2
answers question: http://stackoverflow.com/q/49321748
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85759198
type: QuestionComment
comment on: http://stackoverflow.com/q/49378857
type: Comment
has text: I think admin site is pretty secure. If you want to change `/admin/` the default endpoint of admin site, you can do it on `urls.py`.... `url(r'^some_other_endpoint/', admin.site.urls),`
score: 0

http://stackoverflow.com/comment/85709219
comment on: http://stackoverflow.com/q/49354390
type: QuestionComment
type: Comment
score: 0
has text: in last line try: tabs.append(pd.DataFrame([filename,xl], columns=['filename','tabs']))

http://stackoverflow.com/a/49355689
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49308245
has body: @all! I recieved some help from my professor and the solution is replacing; tile = (i[0] * tile.size, i[1] * tile.size) with this_tile = (i[0] * tile.size, i[1] * tile.size) and everything is working perfectly now. This was his explanation: In the tuple you've just created, there are no named fields. Hence, the interpreter does not find size anymore. If you change the line to this_tile = (i[0] * tile.size, i[1] * tile.size) and then use in the subsequent lines this_tile instead of tile it appears to work.
answers question: http://stackoverflow.com/q/49308245

http://stackoverflow.com/q/49380416
has answer: http://stackoverflow.com/a/49380461
score: 1
tagged with: django-models
tagged with: python
tagged with: django-forms
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Problems with extended models in Django
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
has body: I am currently working on a webapp for user authentication. The user should edit his attributes but when I try to extend the user model, it can not display the attributes. Here is my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User) salutation = models.CharField(max_length=100, default='') title = models.CharField(max_length=100, default='') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here my forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'title', ) ) And this is the template: &lt;form method="post"&gt; {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} The profile:form.as_p does not do anything and when I try to save the changes it also does not do anything. Clearly I am missing something, but I just cannot find it.

http://stackoverflow.com/a/49408575
has body: linprog expects A to have one row per inequation and one column per variable, and not the other way around. Try this: from scipy.optimize import linprog c = [60, 40, 50] A = [[20, 10, 10], [10, 10, 20]] b = [350, 400] res = linprog(c, A, b) print(res) Output: fun: -0.0 message: 'Optimization terminated successfully.' nit: 0 slack: array([ 350., 400.]) status: 0 success: True x: array([ 0., 0., 0.])
answers question: http://stackoverflow.com/q/49408242
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85831175
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49408242

http://stackoverflow.com/comment/85602348
has text: [`django-guardian`](https://django-guardian.readthedocs.io/en/stable/)
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49300215

http://stackoverflow.com/comment/85742711
comment on: http://stackoverflow.com/q/49370769
score: 0
has text: Thanks , makes sense now .
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85788903
has text: @PatrickArtner Sorry for being amateur searching for clear answer. Im handling this kind of exception for first time and documentation was unclear for me and other tutorials I found were exact copies of documentation from pythons page.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49393057

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/49427574

http://stackoverflow.com/comment/85808331
comment on: http://stackoverflow.com/q/49398457
type: QuestionComment
has text: Before the Dense layer, try a Flatten() layer available with Keras
type: Comment
score: 0

http://stackoverflow.com/q/49400711
has answer: http://stackoverflow.com/a/49401036
answer count: 1
has title: Django Check if User Is in Many to Many User Field (template)
favorite count: 0
type: Question
score: 5
upvote count: 5
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49401036
has body: I have a model: class Projects(models.Model): name = models.CharField(max_length=200) users = models.ManyToManyField(User) As you can see, the model contains a ManytoMany field with User model. In my template, I want to check if the current authenticated user is in the Projects users field that was passed to the template: @login_required def index(request): projects = Projects.objects.all() context = { 'projects' : projects } return render(request,'app/index.html',context) The template code will look something like this: {% for project in projects %} {% if user is in project.user %} {% endif %} {% endfor %} Any help will be appreciated!

http://stackoverflow.com/comment/85765067
type: QuestionComment
comment on: http://stackoverflow.com/q/49360384
has text: Could you show the source of your application that connects to Firebird?
score: 0
type: Comment

calculated-field
type: Tag
tag name: calculated-field
tags question: http://stackoverflow.com/q/49407991

http://stackoverflow.com/a/49418662
has body: The 'UnboundLocalError: local variable 'data' referenced before assignment' error indicates that 'data' has not been assigned when it is being called in Line 9 of your code. Either 'data' is defined outside of the get_data() function, or the initial try-block in which 'data' is defined is not being called. I was able to get this code to run as expected -- double-check that your code is indented correctly and that there are no other formatting errors. The following code functions as expected: def get_data(): try: source = someURL data = requests.get(source) try: with open('data_file.csv', 'a') as file: writer = csv.DictWriter(file, fieldnames=['Column']) writer.writerow({'Column':data}) except: pass except: pass
type: Answer
answers question: http://stackoverflow.com/q/49418227
has comment: http://stackoverflow.com/comment/85839082
score: 0

http://stackoverflow.com/q/49361288
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/85732469
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85735237
has comment: http://stackoverflow.com/comment/85725968
has comment: http://stackoverflow.com/comment/85727085
has title: Using f distribution in python with anaconda
has comment: http://stackoverflow.com/comment/85730174
has body: I have very strange issue in my anaconda - spyder. For some purpose, I want to use f distribution fit. So I imported and tried f distribution via scipy as this import numpy as np from scipy.stats import f a = f.rvs(29, 18, size = 1000) #29 and 18 params are used in official site f.fit(a) and I recieved following error: C:\Users\rpaca\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:2303: RuntimeWarning: invalid value encountered in double_scalars Lhat = muhat - Shat*mu It looks very much as package problem. Is there a way how to solve it?
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/49310671
answers question: http://stackoverflow.com/q/49309779
has body: If you want to completely replace PyPI you must use index-url instead of extra-index-url. With extra-index-url pip still search packages at https://pypi.org, extra-index-url is an additional server to search. Your pip.conf must be [global] index=https://pypi.myserver.com/pypi/ index-url=https://pypi.myserver.com/pypi/ trusted-host = pypi.myserver.com index is for pip search, index-url for pip install.
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49309779

http://stackoverflow.com/q/49303679
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85731589
has answer: http://stackoverflow.com/a/49304658
has title: Intersection between two multi-dimensional arrays with tolerance - NumPy / Python
answer count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8317022
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85609479
has body: i am stuck at a problem. I have two 2-D numpy arrays, filled with x and y coordinates. Those arrays might look like: array1([[(1.22, 5.64)], [(2.31, 7.63)], [(4.94, 4.15)]], array2([[(1.23, 5.63)], [(6.31, 10.63)], [(2.32, 7.65)]], Now I have to find "duplicate nodes". However, i also have to consider nodes as equal within a given tolerance of the coordinates, therefore, i can't use solutions like this . Since my arrays are quite big (~200.000 lines each) two simple for loops are not an option as well. My final output should look like this: output([[(1.23, 5.63)], [(2.32, 7.65)]], I would appreciate some hints. Cheers,
has answer: http://stackoverflow.com/a/49304571
has comment: http://stackoverflow.com/comment/85609937
score: 3
has answer: http://stackoverflow.com/a/49305725
upvote count: 3
has comment: http://stackoverflow.com/comment/85643387
has comment: http://stackoverflow.com/comment/85780006
has answer: http://stackoverflow.com/a/49304631
linked to: http://stackoverflow.com/q/25962838
has answer: http://stackoverflow.com/a/49304816
favorite count: 0

http://stackoverflow.com/comment/85655171
has text: Possible duplicate of [I expect 'True' but get 'None'](https://stackoverflow.com/questions/15210646/i-expect-true-but-get-none)
score: 0
comment on: http://stackoverflow.com/q/49326410
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/119670071
score: 0
has text: great solution thanks !
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49355810

java
tags question: http://stackoverflow.com/q/49359392
tags question: http://stackoverflow.com/q/49379760
tags question: http://stackoverflow.com/q/49419621
tags question: http://stackoverflow.com/q/49344715
tag name: java
tags question: http://stackoverflow.com/q/49320412
tags question: http://stackoverflow.com/q/49352731
tags question: http://stackoverflow.com/q/49309357
tags question: http://stackoverflow.com/q/49432252
tags question: http://stackoverflow.com/q/49435630
tags question: http://stackoverflow.com/q/49431565
tags question: http://stackoverflow.com/q/49323532
tags question: http://stackoverflow.com/q/49292192
type: Tag
tags question: http://stackoverflow.com/q/49328173
tags question: http://stackoverflow.com/q/49374199

http://stackoverflow.com/comment/85853083
type: QuestionComment
comment on: http://stackoverflow.com/q/49397761
score: 0
type: Comment
has text: This error has been reported at least 20 times at the [gis.se] Stack Exchange: https://gis.stackexchange.com/questions/tagged/error-000800 For ArcPy questions I think you should research/ask there first.

http://stackoverflow.com/q/49279544
accepted answer: http://stackoverflow.com/a/49279594
favorite count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/49279594
tagged with: function
upvote count: 0
tagged with: python
has title: Invalid syntax when defining python function
downvote count: 1
type: AnsweredQuestion
has body: I'm trying to define a function that will calculate the minimum amount of steps (and type of steps) to be taken to turn a string into another string. I have the below: def cost(matrix[i][j]): a = matrix[i-1][j][0]+1 b = matrix[i][j-1][0]+1 if a[i] = b[i]: c = matrix[i-1][j-1][0] else: c = matrix[i-1][j-1][0] +1 cost0 = min(a, b, c) if cost0 = a: cost1 = Operation.DELETED elif cost0 = b: cost1 = Operation.INSERTED else: cost1 = Operation.SUBSTITUTED return (cost0, cost1) as part of my program, where a, b, and c are ints, but when I run it, it throws an invalid syntax error like the following: line 23 def cost(matrix[i][j]): ^ SyntaxError: invalid syntax what could it be?
tagged with: matrix
has comment: http://stackoverflow.com/comment/85561716
answer count: 1

http://stackoverflow.com/comment/85605646
type: Comment
comment on: http://stackoverflow.com/a/49301876
has text: Nice indeed. Would fit best if this was OP's real use case.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85633123
type: AnswerComment
comment on: http://stackoverflow.com/a/49297520
has text: Thank you very much for your extensive answer. I have not yet decided whether this makes me use another library. If not, I will probably give it a try using your code. Also thanks for the developer input!
score: 0
type: Comment

http://stackoverflow.com/comment/85727867
comment on: http://stackoverflow.com/q/49359744
has text: I see now that it does seem to say something about build 3.7 but I'm not sure why it would, I should be on 3.6.4, the one thats live on website. Maybe not... And pip is updated as well. I updated everything that I found online that it suggested to update so maybe it is python needing a downgrade. Also, i never got just pip install whatever to work, i either used the full path or py -m pip install, should that matter? Or could it also be pandas is trying to install for 3.7??
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85662805
comment on: http://stackoverflow.com/q/49330223
score: 3
has text: Not sure why this would be marked as a duplicate considering the three links provided as "already have an answer" have absolutely nothing to do with my question. Oh well.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85818721
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49405668
has text: @Tar I've added a new solution. It is not a one-liner but it is nicer.

http://stackoverflow.com/q/49286434
tagged with: pyspark
tagged with: python
possible better answer: http://stackoverflow.com/a/49287017
has title: Pyspark agregate sort and score
has answer: http://stackoverflow.com/a/49287017
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/49286589
has body: Let's say a table A: Year product rating 07/02/2018 A good 07/02/2017 B good 07/02/2016 A bad 07/02/2015 C medium 07/02/2016 C bad In a first phase, I wish to obtain the following table: product year score A 07/02/2018 1 A 07/02/2016 3 B 07/02/2017 1 C 07/02/2016 3 C 07/02/2015 2 The second phase: product year score for oldest date A 07/02/2016 3 B 07/02/2017 1 C 07/02/2015 2 what is the shortest way to do this ? ( ranking, change scores from strings to numbers, aggeregate). Can I do all these steps in one shot ? Thank you
has answer: http://stackoverflow.com/a/49286589
linked to: http://stackoverflow.com/q/44776283
type: Question
tagged with: apache-spark-sql

http://stackoverflow.com/a/49426318
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49424554
has body: just export PYTHONPATH=$PYTHONPATH:/usr/lib/python3/dist-packages/ To keep it at next reboot, put this line in your ~/.bashrc : # added by Anaconda3 4.2.0 installer export PATH="/home/my_user_name/anaconda3/bin:$PATH" export PYTHONPATH="/usr/lib/python3/dist-packages/:$PYTHONPATH" to active new .bashrc, do not forget to run source ~/.bashrc
score: 1
answers question: http://stackoverflow.com/q/49424554
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85749092
comment on: http://stackoverflow.com/q/49373592
score: 0
type: Comment
type: QuestionComment
has text: Did you use pip3 install lxml?

http://stackoverflow.com/a/49397270
answers question: http://stackoverflow.com/q/49397153
has comment: http://stackoverflow.com/comment/85832097
has comment: http://stackoverflow.com/comment/85832200
has comment: http://stackoverflow.com/comment/85831403
score: 3
has comment: http://stackoverflow.com/comment/85826533
has comment: http://stackoverflow.com/comment/85828234
has comment: http://stackoverflow.com/comment/85827210
type: Answer
has body: You can raise the object, catch the exception and then use the is keyword to check that the raised exception is the object or an instance of the object. If anything else was raised, it was a TypeError meaning the object was not raisable. Furthermore, to handle absolutely any raisable object, we can use sys.exc_info. This will also catch exceptions such as KeyboardInterrupt, but we can then reraise them if the comparison with the argument is inconclusive. import sys def is_raisable(obj): try: raise obj except: exc_type, exc = sys.exc_info()[:2] if exc is obj or exc_type is obj: return True elif exc_type is TypeError: return False else: # We reraise exceptions such as KeyboardInterrupt that originated from outside raise is_raisable(ValueError) # True is_raisable(KeyboardInterrupt) # True is_raisable(1) # False
has comment: http://stackoverflow.com/comment/85826441
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49412811
tagged with: pandas
has comment: http://stackoverflow.com/comment/85827703
has comment: http://stackoverflow.com/comment/85827583
has comment: http://stackoverflow.com/comment/85827421
has comment: http://stackoverflow.com/comment/85827415
has comment: http://stackoverflow.com/comment/85827917
has comment: http://stackoverflow.com/comment/85827953
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85827479
answer count: 0
has comment: http://stackoverflow.com/comment/85827902
has body: I try to make this code work, but it have error: for myname in mn: mydf = df.loc[df.Teacher_name == myname] mydf.to_excel(writer, sheet_name = myname) writer.save() File "&lt;stdin&gt;", line 4 writer.save() ^ SyntaxError: invalid syntax import= import pandas as pd writer = writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter') mn = mn = df['name'].unique().tolist() mn = ['Teacher A', 'Teacher B', 'Teacher C'] To make df was used this query: df = pd.read_csv('XXX.csv', names=['Teacher_name', 'Studen_name','Extra']) df otput: Teacher_name Student_name Extra 1 Teacher A Student 1 xxxx 2 Teacher A Student 2 xxxx 3 Teacher B Student 3 xxxx 4 Teacher C Student 4 xxxx
type: UnansweredQuestion
tagged with: python
has title: Python (Pandas) - Syntax Error - Invalid Syntax - writer.save()
has comment: http://stackoverflow.com/comment/85827749
has comment: http://stackoverflow.com/comment/85827521
has comment: http://stackoverflow.com/comment/85828185
has comment: http://stackoverflow.com/comment/85827738
score: 0
has comment: http://stackoverflow.com/comment/85828111

http://stackoverflow.com/a/49382573
downvote count: 0
has comment: http://stackoverflow.com/comment/85765862
type: Answer
has body: You can use the python method writelines(&lt;iterable&gt;) on the fileobject. Something like: with open('template.txt', 'r') as template_file: file_lines = template_file.readlines() file_lines = [line.rstrip('\n') for line in file_lines] for i in range(10): with open('output_%s' % i, 'w') as new_file: new_file.write_lines(file_lines) Also not sure you need the rstrip('\n') as readlines() already should be removing newlines.
score: 2
answers question: http://stackoverflow.com/q/49382244
upvote count: 2

http://stackoverflow.com/comment/85868639
has text: `f.write(s)` writes `s` into your file `f`, so you should be passing in the content of what you want to write into, rather than the file path.
comment on: http://stackoverflow.com/q/49433355
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85881069
has text: @MarkH exactly!
comment on: http://stackoverflow.com/a/49438887
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49309844
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85625810
answers question: http://stackoverflow.com/q/49308372
has comment: http://stackoverflow.com/comment/85674524
has comment: http://stackoverflow.com/comment/85622206
accepted answer of: http://stackoverflow.com/q/49308372
type: Answer
has body: def func(c, g, P): z = g + np.log10(c)*np.log10(P) return np.median(z**2) if __name__ == '__main__': # Your arrays go here g = np.log10(y) - np.log10(x) args = (g, P) result = differential_evolution(func, bounds, args=(g, P)) # will print the value of c and value of the optimized function print (result.x, result.fun)
has comment: http://stackoverflow.com/comment/85713488
has comment: http://stackoverflow.com/comment/85709624
downvote count: 0

http://stackoverflow.com/a/49325315
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You can using isin data[data.index.minute.isin([0,15,30,45])]
answers question: http://stackoverflow.com/q/49325236
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/49325236

http://stackoverflow.com/comment/85685187
type: AnswerComment
has text: @juanpa.arrivillaga good point, I was a bit lazy on the wording, kind of counting on other users to call me out on it with something better, so thanks, improved!
score: 1
comment on: http://stackoverflow.com/a/49341787
type: Comment

http://stackoverflow.com/comment/85689973
score: 0
has text: @jkff I want to load data from biquery to elasticsearch. In my sample transform, I am doing operations like creating, reindexing, deleting elasticsearch indexes. So first i need to create an temp index, second loading data and to ES temp index, third reindex it, fourth delete my temp index. So I want to execute all these task in ordered manner. but here creating, reindexing and deleting tasks are executed first and finally load data has executed. (you can see logs "*****" showed at last)
comment on: http://stackoverflow.com/q/49334778
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49380440
has title: difference between cars.iloc[[3, 0]], cars.iloc[[3],[0]] and cars.iloc[3, 0]
tagged with: python
score: 4
upvote count: 4
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49380548
has body: I am studying pandas and working on cars(a csv file). I ran the below commands: 1) cars.iloc[[3, 0]] Out[2]: cars_per_cap country drives_right IN 18 India False US 809 United States True 2) cars.iloc[[3],[0]] Out[7]: cars_per_cap IN 18 3) cars.iloc[3, 0] Out[9]: 18 I am getting confused in the 1st and 3rd command, I checked the type of all and the first 2 are the DataFrame and the 3rd one is not. However, why am I getting a different output for 1st and 3rd? Any help would be appreciated.
has answer: http://stackoverflow.com/a/49380548

http://stackoverflow.com/comment/85813776
has text: @BlueTomato I just edited the code, maybe makes more sense. But still it crashes :S
comment on: http://stackoverflow.com/a/49405706
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85775844
type: AnswerComment
has text: If you find the answers posted here useful or provides solution to your question, feel free to up-vote or mark as answered.
comment on: http://stackoverflow.com/a/49385636
type: Comment
score: 0

http://stackoverflow.com/comment/85566771
type: QuestionComment
comment on: http://stackoverflow.com/q/49281051
type: Comment
score: 0
has text: Well then, I wish teachers would teach for loops first. I understand they learned in either C or Lisp, where the equivalent of a for loop is a lot more complicated than a while loop, so their teacher started with while. But they’re teaching Python, not C, and the first problem they come up with is “loop over each string in this list”, they should teach the easy way to do it first.

http://stackoverflow.com/comment/85642867
type: Comment
comment on: http://stackoverflow.com/q/49320099
type: QuestionComment
has text: What if you `print(measureData.byYear)` ?
score: 0

http://stackoverflow.com/comment/85820940
comment on: http://stackoverflow.com/q/49408730
type: Comment
type: QuestionComment
has text: Well, now you'd have to show what the `FilesCreate2` form is, because that's what's processing when you submit. But you have a big mess there, that is hard to address in a comment, also because it's not entirely clear to me what you are trying to do. I don't know why you have two views and two forms, and you are mixing them up. Maybe carefully reading [the documentation on forms](https://docs.djangoproject.com/en/2.0/topics/forms/) would help.
score: 0

http://stackoverflow.com/q/49369657
type: Question
type: AnsweredQuestion
has body: I have the following working example in Python which takes a string, uses a dict comprehension and a regular expression on it and finally generates a dataframe from it: import re, pandas as pd junk = """total=7871MB;free=5711MB;used=2159MB;shared=0MB;buffers=304MB;cached=1059MB; free=71MB;total=5751MB;shared=3159MB;used=5MB;buffers=30MB;cached=1059MB; cached=1059MB;total=5751MB;shared=3159MB;used=5MB;buffers=30MB;free=109MB;""" rx = re.compile(r'(?P&lt;key&gt;\w+)=(?P&lt;value&gt;[^;]+)') records = [{m.group('key'): m.group('value') for m in rx.finditer(line)} for line in junk.split("\n")] df = pd.DataFrame(records) print(df) This yields buffers cached free shared total used 0 304MB 1059MB 5711MB 0MB 7871MB 2159MB 1 30MB 1059MB 71MB 3159MB 5751MB 5MB 2 30MB 1059MB 109MB 3159MB 5751MB 5MB Now how the ... can I do the same thing in R ? I messed around with lapply and regmatches but to no avail. Additionally, how would I do this with missing values?
accepted answer: http://stackoverflow.com/a/49369893
tagged with: python
possible better answer: http://stackoverflow.com/a/49370043
tagged with: regex
score: 4
has title: From Python to R - DataFrame from string
has answer: http://stackoverflow.com/a/49370043
upvote count: 4
tagged with: http://stackoverflow.com/tag/r
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49369893
favorite count: 0

http://stackoverflow.com/comment/85850294
type: Comment
has text: Thank you all guys for help and discussion. ^^*
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49424326

http://stackoverflow.com/q/49363172
favorite count: 0
tagged with: tensorflow
type: Question
tagged with: anaconda
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49363229
has comment: http://stackoverflow.com/comment/85726616
has title: Got a warning when importing Tensorflow in Python
tagged with: python
has answer: http://stackoverflow.com/a/49890401
score: 2
upvote count: 3
answer count: 2
downvote count: 1
has body: When I import tensorflow in Python I get this error: C:\Users\Sathsara\Anaconda3\envs\tensorflow\Lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters

http://stackoverflow.com/a/49314653
has comment: http://stackoverflow.com/comment/85633601
type: AcceptedAnswer
downvote count: 0
score: 8
has comment: http://stackoverflow.com/comment/85632763
has comment: http://stackoverflow.com/comment/85633084
upvote count: 8
has comment: http://stackoverflow.com/comment/85632872
has comment: http://stackoverflow.com/comment/85632579
accepted answer of: http://stackoverflow.com/q/49314624
type: Answer
has body: Use: set_index for only numeric columns replace $ with one or more whitespaces \s+ convert to floats by astype convert to custom format by applymap df = (df.set_index('Names') .replace('\$\s+','', regex=True) .astype(float) .applymap('{:,.2f}'.format)) print (df) Cider Juice Subtotal (Cider) Subtotal (Juice) Total Names Richard 13.00 9.00 71.50 40.50 112.00 George 7.00 21.00 38.50 94.50 133.00 Paul 0.00 23.00 0.00 103.50 103.50 John 22.00 5.00 121.00 22.50 143.50 Total 42.00 58.00 231.00 261.00 492.00 Average 10.50 14.50 57.75 65.25 123.00 EDIT: I try improve your solution: people_ordered = input('How many people ordered? ') Data = [] # Create the 4x3 table from user input for i in range(int(people_ordered)): names = input("Enter the name of Person #{}: ".format(i+1)) # type str cider_orderred = int(input("How many orders of cider did {} have? ".format(names))) # type str -&gt; int juice_orderred = int(input("How many orders of juice did {} have? ".format(names))) # type str -&gt; int #create in loop tuple and append to list Data Data.append((names, cider_orderred, juice_orderred)) #create DataFrame form list of tuples, create index by Names df1 = pd.DataFrame(Data, columns=['Names','Cider','Juice']).set_index('Names') #count all new columns, rows df1['Subtotal(Cider)'] = df1['Cider'] * 5.5 df1['Subtotal(Juice)'] = df1['Juice'] * 4.5 df1['Total'] = df1['Subtotal(Cider)'] + df1['Subtotal(Juice)'] df1.loc['Total'] = df1.sum() #remove row Total for correct mean df1.loc['Average'] = df1.drop('Total').mean() #get custom format of columns in list cols cols = ['Subtotal(Cider)','Subtotal(Juice)','Total'] df1[cols] = df1[cols].applymap('$ {:,.2f}'.format) #create column from index df1 = df1.reset_index() print(df1) Names Cider Juice Subtotal(Cider) Subtotal(Juice) Total 0 r 13.0 9.0 $ 71.50 $ 40.50 $ 112.00 1 g 7.0 21.0 $ 38.50 $ 94.50 $ 133.00 2 p 0.0 23.0 $ 0.00 $ 103.50 $ 103.50 3 j 22.0 5.0 $ 121.00 $ 22.50 $ 143.50 4 Total 42.0 58.0 $ 231.00 $ 261.00 $ 492.00 5 Average…
answers question: http://stackoverflow.com/q/49314624
has comment: http://stackoverflow.com/comment/85631933
has comment: http://stackoverflow.com/comment/85633354

http://stackoverflow.com/a/49293288
downvote count: 0
upvote count: 1
has body: You are leaving open the possibility that age &gt;= 8 but grade &lt; 3 in which you have no control flow to handle. You can correct this succinctly with an and statement age = float(raw_input("Enter your age: ")) grade = int(raw_input("Enter your grade: ")) if age &gt;= 8 and grade &gt;= 3: print "You can play this game." else: print "Sorry, you can't play the game."
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49293102
accepted answer of: http://stackoverflow.com/q/49293102
type: AcceptedAnswer

http://stackoverflow.com/comment/85870364
has text: @coldspeed method 2 works fine. thank you! npwhere is the key here. however npwhere might not be the best solution for a nested if condition thats why I tend to use df.apply
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49433907
score: 0

http://stackoverflow.com/q/49425991
has body: there I have some code with copy a files from root-dirs-subdirs and at beginning I would like to check, Did all dirs they've got same numbers of subdirs if not print a message something like "nr subdirs not same".I've got 5 dirs and each have to contain 12 subdirs(with different numbers of images). Its exactly in for folder in src_folders: src_sub_folders I have no idea how to scan 5 dirs and get answer back, all what I can find is how to compare 2 dirs but how do it with 5 ??? Any help will be appreciated from collections import defaultdict import shutil import os import re src_root = r'F:\img\img_test\2018-03-06' dst_root = src_root + '-copie' #os.makedirs(dst_root, exist_ok=True) src_dirname, src_folders, _ = next(os.walk(src_root)) src_folders = sorted(src_folders) src_folders = [os.path.join(src_root, folder) for folder in src_folders] print(src_folders) job = defaultdict(list) print('mes {} dossier cam'.format(len(src_folders))) for folder in src_folders: print() dirname, src_sub_folders, _ = next(os.walk(os.path.join(src_dirname, folder))) src_sub_folders = sorted(src_sub_folders, key=lambda x: [re.search(r'(\D+)', x).group(1)] + list(map(int, re.findall(r'\d+', x)))) print("mes 5 CAM avec {} time laps '{}'".format(len(src_sub_folders), folder)) for index, sub_folder in enumerate(src_sub_folders, start=1): job['Time Lapse-{}'.format(index)].append(os.path.join(dirname, sub_folder)) #print() for dst_folder, src_folders in sorted(job.items()): for index, src_folder in enumerate(src_folders, start=1): dst_new_folder = os.path.join(dst_root, dst_folder, 'CAM-{}'.format(index)) print('{} -&gt; {}'.format(src_folder, dst_new_folder)) shutil.copytree(src_folder, dst_new_folder) #shutil.rmtree(src_root) for root, dirs, files in os.walk(dst_root): for f in files: prefix = os.path.basename(root) prefix1 = os.path.basename(src_root) os.rename(os.path.join(root, f), os.path.join(root, "{}-{}-{}".format(prefix1, prefix, f))) print("images rennomer ") print("fini") print("…
has title: Checking for same numbers of subdirectories in directories python
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49428045
accepted answer: http://stackoverflow.com/a/49428045
type: AnsweredQuestion
score: 0
type: Question

http://stackoverflow.com/q/49423429
answer count: 4
has comment: http://stackoverflow.com/comment/85848191
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/49423590
has answer: http://stackoverflow.com/a/49424361
has body: I am using a bunch class to transform a dict to an object. class Bunch(object): """ Transform a dict to an object """ def __init__(self, kwargs): self.__dict__.update(kwargs) The problem is , i have a key with a dot in its name({'test.this':True}). So when i call: spam = Bunch({'test.this':True}) dir(spam) I have the attibute: ['__class__', '__delattr__', ... '__weakref__', 'test.this'] But i can't access it: print(spam.test.this) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-7-ea63f60f74ca&gt; in &lt;module&gt;() ----&gt; 1 print(spam.test.this) AttributeError: 'Bunch' object has no attribute 'test' i got an AttributeError. How can i access this attribute?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49423857
has comment: http://stackoverflow.com/comment/85848045
accepted answer: http://stackoverflow.com/a/49423857
score: 5
has title: How to access an object attribute with a dot in its name
upvote count: 6
has answer: http://stackoverflow.com/a/49423605
possible better answer: http://stackoverflow.com/a/49423605
tagged with: python

http://stackoverflow.com/a/50553153
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49369176
has body: You may already have fixed your issue, but I want to clarify what probably went wrong with your autoencoder so other people that have the same problem can understand what is happening. The main issue is that you didn't normalize your input data and you used sigmoid function as activation in the last layer. What this means is that you have an input that can range between -infinity and +infinity while your output data can only vary between 0 and 1. An autoencoder is a Neural Network that tries to learn the identity function. What this means is that if you have an input [0, 1, 2, 3], you want the network to output [0, 1, 2, 3]. What happened in your case is that you used sigmoid as an Activation Function in the last layer, which means that every value this layer receives, it will apply a sigmoid function. As said before, the sigmoid function squashes values between 0 and 1. So if you have [0, 1, 2, 3] as inputs, even if your hidden layer learns the identity function (which I think would be impossible in this case), the output would be sigmoid([0, 1, 2, 3]), which results in [0.5, 0.73, 0.88, 0.95] approximately. If you think about it, it's impossible that this autoencoder learns to replicate its inputs if the range of the inputs exceeds the 0 to 1 range, because when the loss function try to compare the result with the original data, it will always mismatch. In this case, the best thing you can do is to normalize your inputs so it varies between 0 and 1 just like your outputs.
type: Answer
score: 2

http://stackoverflow.com/comment/85716894
comment on: http://stackoverflow.com/a/49355027
score: 0
type: AnswerComment
has text: The program still crashes even though I've done that. Thank you for reply.
type: Comment

http://stackoverflow.com/comment/85810869
has text: Thank you so much for all your help. Code works now, I'm new to stackoverflow. I also upvoted your response
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49372599

http://stackoverflow.com/comment/85664771
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49331318
has text: This strategy is not helpful. What makes you think we will answer a question that does not follow the posting guidelines?

http://stackoverflow.com/comment/85697564
comment on: http://stackoverflow.com/a/49345259
type: Comment
score: 0
type: AnswerComment
has text: I had no idea that syntax was valid. I'll have to look into it a little more, but it worked with the toy program presented above. Thanks for the lead.

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/49294383
type: Tag

http://stackoverflow.com/q/49326927
has answer: http://stackoverflow.com/a/49326997
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has body: This is probably a very basic question but I haven't been able to find the answer so here goes... Question: Is there an say way to sort the values alphabetically while also removing any duplicate instances? Here's what I have: data = ['Car | Book | Apple','','Book | Car | Apple | Apple'] df = pd.DataFrame(data,columns=['Labels'] print(df) Labels 0 Car | Book | Apple 1 2 Book | Car | Apple | Apple Desired Output: Labels 0 Apple | Book | Car 1 2 Apple | Book | Car Thanks!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49327103
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/49327285
possible better answer: http://stackoverflow.com/a/49327285
score: 2
answer count: 3
upvote count: 2
tagged with: pandas
has title: How to sort values within Pandas DF Column and remove duplicates
accepted answer: http://stackoverflow.com/a/49327103

python-imaging-library
tags question: http://stackoverflow.com/q/49375502
tags question: http://stackoverflow.com/q/49415054
type: Tag
tags question: http://stackoverflow.com/q/49303554
tags question: http://stackoverflow.com/q/49412240
tags question: http://stackoverflow.com/q/49307497
tags question: http://stackoverflow.com/q/49282595
tags question: http://stackoverflow.com/q/49304423
tags question: http://stackoverflow.com/q/49330639
tags question: http://stackoverflow.com/q/49361219
tags question: http://stackoverflow.com/q/49280402
tags question: http://stackoverflow.com/q/49368783
tags question: http://stackoverflow.com/q/49320287
tags question: http://stackoverflow.com/q/49285554
tags question: http://stackoverflow.com/q/49339754
tags question: http://stackoverflow.com/q/49304307
tags question: http://stackoverflow.com/q/49390491
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/49342812

http://stackoverflow.com/a/49411638
upvote count: 4
has comment: http://stackoverflow.com/comment/85825083
has comment: http://stackoverflow.com/comment/85825233
downvote count: 1
has comment: http://stackoverflow.com/comment/85825155
has comment: http://stackoverflow.com/comment/85825211
answers question: http://stackoverflow.com/q/49411524
has comment: http://stackoverflow.com/comment/85824997
has body: How about this way: def extend(x, a): return a + {tuple: (x,), str: x, list: [x]}[type(a)] Of course, keep in mind that the number of datatypes is really big and a one-size-fits-all approach does not exist. So, take another hard look on whatever code comes before this and if you really need it, use this dictionary approach. EDIT If you need to do this many many times, do it with an if block. As @chepner says, building a dictionary every time will render this approach too smart for its own good. If subclassing is also an issue, you should change from type to isinstance as @Jean-FrancoisFabre says.
has comment: http://stackoverflow.com/comment/85825158
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85824971

http://stackoverflow.com/q/49289575
has body: import pytesseract from PIL import Image, ImageEnhance, ImageFilter pytesseract.pytesseract.tesseract_cmd="C:\Program Files (x86)\Tesseract- OCR\tesseract.exe" im = Image.open("d:\ss.png") # the second one im = im.filter(ImageFilter.MedianFilter()) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(2) im = im.convert('1') im.save('temp2.jpg') text = pytesseract.image_to_string(Image.open('temp2.jpg')) print(text) Above is the code to convert an image to text, but it shows the following error: Traceback (most recent call last): File "D:\txt14.py", line 10, in &lt;module&gt; text = pytesseract.image_to_string(Image.open('temp2.jpg')) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 193, in image_to_string return run_and_get_output(image, 'txt', lang, config, nice) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 140, in run_and_get_output run_tesseract(**kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 111, in run_tesseract proc = subprocess.Popen(command, stderr=subprocess.PIPE) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified Can you please help me figure out why this error is happening?
type: AnsweredQuestion
score: 0
tagged with: windows
has title: Image to Text Pytesseract Error
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49289651
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49289651
tagged with: pytesser

http://stackoverflow.com/comment/85817950
score: 0
has text: Possible duplicate of [Match linebreaks - \n or \r\n?](https://stackoverflow.com/questions/20056306/match-linebreaks-n-or-r-n)
comment on: http://stackoverflow.com/q/49337715
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49324569
answer count: 2
linked to: http://stackoverflow.com/q/38511373
tagged with: pandas
has title: Replicating Jupyter Notebook Pandas dataframe HTML printout
possible better answer: http://stackoverflow.com/a/63804020
linked to: http://stackoverflow.com/q/36897366
has answer: http://stackoverflow.com/a/63804020
favorite count: 0
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/49687866
type: Question
has body: I'm trying to replicate the output that jupyter uses for a pandas dataframe in their notebooks to html/css/js so that it's returnable by Flask jsonify as html that I later use in an AJAX call. I found this, and this, which suggested using the pandas builtin style functionality rather than CSS hacks but i'm struggling to get the desired functionality: def hover(hover_color="#add8e6"): return dict(selector="tr:hover", props=[("background-color", "%s" % hover_color)]) styles = [ hover(), dict(selector="th", props=[("font-size", "125%"), ("text-align", "center"), ("padding", "5px 5px")]), dict(selector="tr", props=[("text-align", "center")]), dict(selector="caption", props=[("caption-side", "bottom")]) ] # creating some dummy data index = pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']], labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]], names=['first', 'second']) df = pd.DataFrame(data=np.random.randn(8), index=index) # you'll see the html rendered bellow df.style.set_table_styles(styles).set_caption("test").render() Compared to jupyter notebooks, this is missing some default background color stripping, and the header shouldn't apply the hover class. The only way I can think to apply something on select elements would be to add class= or id= but the style functionality hides all that. Hover to highlight. 0 first second bar one -0.0690895 two -0.518092 baz one -0.163842 two -0.144757 foo one 1.22865 two 1.83947 qux one 0.793328 two -0.723836
has answer: http://stackoverflow.com/a/49687866
upvote count: 9
score: 9
downvote count: 0
tagged with: python
tagged with: css
type: AnsweredQuestion

http://stackoverflow.com/a/49329994
answers question: http://stackoverflow.com/q/49329886
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85662280
type: Answer
has comment: http://stackoverflow.com/comment/85662242
accepted answer of: http://stackoverflow.com/q/49329886
has body: datetime.utcnow() is the utc time, datetime.fromtimestamp() is the local time, which depends on your time zone. To add to timestamp, you just need to convert the timedelta to seconds: time.time() + timedelta(hours=3).total_seconds()
score: 2

http://stackoverflow.com/q/49438814
upvote count: 7
favorite count: 0
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/86073505
type: Question
has title: Opening already opened hdf5 file in write mode, using h5py
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86083516
tagged with: python
has body: I run the same Python program concurrently as different processes, and these all want to write to the same hdf5 file, using the h5py Python package. However, only a single process may open a given hdf5 file in write mode, otherwise you will get the error OSError: Unable to open file (unable to lock file, errno = 11, error message = 'Resource temporarily unavailable') During handling of the above exception, another exception occurred: OSError: Unable to create file (unable to open file: name = 'test.hdf5', errno = 17, error message = 'File exists', flags = 15, o_flags = c2) I want to resolve this by checking whether the file is already opened in write mode, and if so, wait a bit and check again, until it is no longer opened in write mode. I have not found any such checking capability of h5py or hdf5. As of now, my solution is based on this: from time import sleep import h5py # Function handling the intelligent hdf5 file opening def open_hdf5(filename, *args, **kwargs): while True: try: hdf5_file = h5py.File(filename, *args, **kwargs) break # Success! except OSError: sleep(5) # Wait a bit return hdf5_file # How to use the function with open_hdf5(filename, mode='a') as hdf5_file: # Do stuff ... I'm unsure whether I like this, as it doesn't seem very gentle. Are there any better way of doing this? Are there any change that my erroneous attempts to open the file inside the try can somehow corrupt the write process that is going on in the other process?
has answer: http://stackoverflow.com/a/52344419
tagged with: h5py
score: 7
linked to: http://stackoverflow.com/q/8231719
answer count: 1
downvote count: 0
tagged with: hdf5
tagged with: file-writing

http://stackoverflow.com/q/49353671
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85708033
has body: I'm doing a simple algorithm for the 8-Puzzle problem, but I want to show it in a GUI. This, is my loop to solve the problem: while puzzle != puzzleGoals: cont += 1 nRow = row(puzzle.index(0)) resolve(nRow) Resolve is the function who do all the work. It's working fine and gives the right result. I can create a screen with the order that I want a1 = Label(root, text = puzzle[0]).grid(row = 0, column = 0, sticky= W) a2 = Label(root, text = puzzle[1]).grid(row = 0, column = 1, sticky= W) a3 = Label(root, text = puzzle[2]).grid(row = 0, column = 2, sticky= W) b1 = Label(root, text = puzzle[3]).grid(row = 1, column = 0, sticky= W) b2 = Label(root, text = puzzle[4]).grid(row = 1, column = 1, sticky= W) b3 = Label(root, text = puzzle[5]).grid(row = 1, column = 2, sticky= W) c1 = Label(root, text = puzzle[6]).grid(row = 2, column = 0, sticky= W) c2 = Label(root, text = puzzle[7]).grid(row = 2, column = 1, sticky= W) c3 = Label(root, text = puzzle[8]).grid(row = 2, column = 2, sticky= W) looks like this So, how can I change the labels texts every time that's a new combination of the puzzle? There's a possibility of a kind of "label.setText("abc")? And how to input the root.mainloop() inside the while loop? Or its unnecessary? Many thanks
has answer: http://stackoverflow.com/a/49353742
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85713172
score: 0
answer count: 1
has title: Change the label text using TkInter
type: Question

http://stackoverflow.com/q/49398913
tagged with: sympy
has answer: http://stackoverflow.com/a/49414332
accepted answer: http://stackoverflow.com/a/49414332
tagged with: python
type: AnsweredQuestion
has title: Assumptions function not fully integrated in SymPy
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: I was doing homework with the python SymPy package where I met a problem. Suppose integrate a function psi1=A*exp(k1*x) from negative infinity to a fixed point a; the integrate function won't gave the exact result unless declare k1 to be positive. The simply solution was to put positive=True in the argument before use it, i.e. Symbol(k0,positive=True). However, I ran into another set of function called assumptions module Assumptions module and Assuming functions whcih was quiet power syntax. But the problem was that, if I declare k1 to be positive in the above methods i.e. global_assumptions.add(Q.positive(k1)) or with assuming(Q.positive(k1)): the integration integrate(psi1,(x,-oo,a)) would not calculate the exact result. I tried to use .evalf() and it still didn't work.
favorite count: 0
type: Question

http://stackoverflow.com/q/49396718
favorite count: 0
tagged with: driver
type: Question
has comment: http://stackoverflow.com/comment/85795246
tagged with: hex
tagged with: binary
accepted answer: http://stackoverflow.com/a/49396768
has answer: http://stackoverflow.com/a/49396768
upvote count: 0
has comment: http://stackoverflow.com/comment/85795219
tagged with: python
score: -1
has body: I'm writing a driver and am concatenating some hex instructions based on a few conditionals. Up until this point, all instructions have worked as intended. A new instruction I was working on isn't working as intended, so I attempted to print out the instruction after concatenation and before execution to see what was wrong. msg = '\xc2%s%s' % ('\x1b\x63', '07') assert self.dev.ctrl_transfer(0x21, 9, 0x0300, 0, msg) == len(msg) print(msg) When I print it after concatenation it clears the console and prints '07' and then continues the rest of the driver execution. I'm able to print and execute every other instruction I've concatenated, such as the following, without issue. msg = '\xc2%s%s' % ('\x1b\x72, '07') Does anyone have an idea why this is happening? Does the '\x63' byte tell python to do something I'm unaware of? It should just be concatenated to the rest of the instruction, followed by the '\x07' byte. Note, that if I include the '\x' before the '07' (unlike my code above) it still does the same thing, it just doesn't print '07', it leaves a blank line. Thanks!
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85795222
has title: Attempting to debug hex instruction, but python clears my console?
downvote count: 1

http://stackoverflow.com/comment/85677900
type: QuestionComment
comment on: http://stackoverflow.com/q/49338846
type: Comment
score: 0
has text: Python's `or` doesn't work like you think it does; read the linked duplicates for an explanation.

http://stackoverflow.com/a/49389649
has comment: http://stackoverflow.com/comment/85780975
score: 0
answers question: http://stackoverflow.com/q/49389509
type: Answer
has comment: http://stackoverflow.com/comment/85792070
has body: Reset index for both datafrmes and then create a column named 'Appointed' in df1 and assign the same column of df2 in it. After resetting index,both datafrmes have index beginning from 0. When we assign the column, they automatically align according to index which is a property of pandas dataframe df1.reset_index() df2.reset_index() df1['Appointed'] = df2['Appointed']

http://stackoverflow.com/q/49365757
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85782639
score: 0
accepted answer: http://stackoverflow.com/a/49508455
has title: How to draw inf values in networkx?
answer count: 1
has answer: http://stackoverflow.com/a/49508455
tagged with: networkx
type: Question
tagged with: colormap
has comment: http://stackoverflow.com/comment/85782671
has comment: http://stackoverflow.com/comment/85770020
tagged with: matplotlib
has body: I'm trying to draw a graph G with networkx, where the edge colors are given by the parameter parameter previously assigned to every edge. Some of the edges' parameter value is inf. This is drawn using the lowest color of the specified colorbar, I think. I'd like to draw edges with inf value in another color, e.g. red. Is this possible? If yes, how would I go about it? Here's the relevant part of my code: def plot_graph_colored_edges(G, node_positions, parameter): ''' plot graph G with node positions node_positions, color edges according to their parameter value ''' # calculate range for assigning colors to edges param_list = [] for edge in nx.to_edgelist(G): param_list.append(edge[2][parameter]) vmin = min(param_list) vmax = max(param_list) # choose color map cmap = plt.cm.Greens # draw graph plt.clf() # workaround to create colorbar, since nx.draw_networkx returns None... sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax)) sm._A = [] plt.colorbar(sm) # draw actual graph nx.draw( G, pos=node_positions, node_size=1, node_color='black', with_labels=False, edge_color=param_list, edge_cmap=cmap, edge_vmin=vmin, edge_vmax=vmax) Searching for a solution, I found this answer about plotting NaNs with matplotlib's imshow. I tried adding in something along the lines of current_cmap = plt.cm.get_cmap() current_cmap.set_bad(color='red') but it doesn't seem to change anything. Based on comments by @michaelg and @Bonlenfum I tried converting the inf values to NaN. Unfortunately, the technique I linked did not work here either. Do I have to add anything but the above two lines of code? Per request, here is the data I use. I didn't know how to get rid of the unneeded parameters, I hope that's not a problem. d = {1.0: {2.0: {'reactance': 0.059999999999999998, 'eta': 0.83909678373550689, 'flow': -9.1694698723315451, 'b_over_lambda': inf, 'weight': 16.666666666666668}, 3.0: {'reactance': 0.19, 'eta': 0.49047314849577706, 'flow': -14.360530127668513, 'b_over…
tagged with: python
linked to: http://stackoverflow.com/q/2578752

http://stackoverflow.com/a/49375265
has body: This is assuming your source data is in a file and looks/formatted like a list, but really isn't. When you open up the file and start to process it, it will be a string. So with that in mind other tasks need to be accomplished, mostly stripping out what isn't needed. Personally I think you need to format your source file better so that less work needs to be done. But here goes... This is how the data looks in a file called 'friends.txt' ['David\n', 'Geri\n', 'Jessica\n', 'Joe\n', 'John\n', 'Rose\n'] #!python3 def main(): s1 = ''; s2 = '' # strings to hold data being processed new_friends = [] # this will hold your new and exciting friends, but # without the baggage of square brackets, quotes, # new lines, or commas that are part of the string # use with open(), no closing of file required; # 'fp' stands for 'file pointer', call it whatever you want to call it; # all of the data in any file that gets opened up in this way is # always a string, it doesn't matter how it's formatted in the file with open('friends.txt', 'r') as fp: for line in fp: # strip out square brackets, quotes, and strings that look like # new lines but aren't new lines; split the statement over # 2 lines using a trailing backslash, doing so allows for easier # reading of the statement without excessive scrolling s1 = line.replace('[', '').replace(']', '') \ .replace("'", '').replace('\\n', '') # strip out trailing new line s1 = s1.rstrip() # split() returns a list, split string on a 'comma/space' new_friends = s1.split(', ') # sort list, print results, build string that will be written to file for item in sorted(new_friends): print(item) # print results s2 += item + '\n' # build string # write to new file; # 'wf' stands for 'write file', call it whatever you want to call it with open('new_freinds.txt', 'w') as wf: wf.write(s2) # start the program if __name__ == '__main__': main()
type: Answer
answers question: http://stackoverflow.com/q/49374773
score: 0

http://stackoverflow.com/comment/85685006
score: 1
comment on: http://stackoverflow.com/a/49341787
type: Comment
has text: @Carpetfizz note, it's quite consistent with the concatenation operator: `+`, so `L = [x]; L + L + L == L*3 == [x, x, x]`
type: AnswerComment

http://stackoverflow.com/comment/85788977
type: QuestionComment
has text: It's not clear whether you've noticed that `('Pathway1', 'Pathway2', 0.6)` and `('Pathway2', 'Pathway1', 0.6)` are completely different tuples; one has `'Pathway1'` in front and the other has it second.
comment on: http://stackoverflow.com/q/49393454
score: 1
type: Comment

http://stackoverflow.com/comment/85864704
comment on: http://stackoverflow.com/a/49430796
score: 0
has text: Sure, you can use a for loop. I will update with a simple example.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85575109
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49285793
has text: I believe your question has an answer here: https://stackoverflow.com/questions/22162321/search-for-a-value-in-a-nested-dictionary-python

http://stackoverflow.com/comment/85706361
has text: And you may want to consider importing what you need instead of everything (`from sympy import *`). The import time of some SymPy modules is noticeable.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49352487
score: 0

http://stackoverflow.com/a/49421303
upvote count: 1
downvote count: 1
has body: txt = open("document.txt").read() spt = txt.split() new_list = [] for i in spt: if i.endswith(','): w=i.rstrip(',') new_list.append(w) elif i.endswith('.'): w=i.rstrip('.') new_list.append(w) else: new_list.append(i) print(new_list)
type: Answer
answers question: http://stackoverflow.com/q/49419744
score: 0

http://stackoverflow.com/q/49381195
favorite count: 0
type: Question
has title: Semaphore in Python
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/71811745
has answer: http://stackoverflow.com/a/49382161
tagged with: semaphore
answer count: 2
has body: I'm trying to implement mutual exclusion using semaphore in Python. The two processes (proc1, proc2) are supposed to be two independent, concurrent processes. They do exactly the same thing: store n in array[n], then increment n. The purpose of the program is to show that using semaphore we can ensure that the array is filled properly: [0,1,2,3,4,5,6,7,8,9], without skipping any index. However, my code seems to store [0,1,0,0,0,0,0,0,0,0]. I haven't used threads in python before, so I don't know what's going on. import threading import time n = 0 array = [0]*10 sem = threading.Semaphore() def proc1(): global n, array while True: sem.acquire() array[n] = n n += 1 sem.release() time.sleep(0.25) def proc2(): global n, array while True: sem.acquire() array[n] = n n += 1 sem.release() time.sleep(0.25) t = threading.Thread(target = proc1) t.start() t2 = threading.Thread(target = proc2) t2.start() print (array)
downvote count: 0
score: 1

http://stackoverflow.com/comment/85798774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49398393
has text: @Sam I think Question has enough information to reproduce a problem. There's no need for extra file or data.
score: 1

http://stackoverflow.com/q/49350821
has comment: http://stackoverflow.com/comment/85731443
has answer: http://stackoverflow.com/a/59281658
has comment: http://stackoverflow.com/comment/85703203
tagged with: python
has answer: http://stackoverflow.com/a/60094385
has title: RuntimeWarning: coroutine was never awaited in tests
has comment: http://stackoverflow.com/comment/103222348
score: 19
upvote count: 19
has comment: http://stackoverflow.com/comment/103160817
tagged with: pytest
downvote count: 0
favorite count: 0
type: Question
has body: I'm trying to test a async Python function using pytest. My test is passing with a warning, when it should be failing. This is my test: import asynctest import pytest from Foo.bar import posts @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' assert True == False It passes with the following message: ================================== test session starts =================================== platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0 rootdir: /path/path/path/path, inifile: collected 1 item tests/unit/route_logic/test_post_helpers.py . [100%] ==================================== warnings summary ==================================== tests/unit/route_logic/test_post_helpers.py::test_get_post_exists /usr/local/lib/python3.6/site-packages/_pytest/python.py:155: RuntimeWarning: coroutine 'test_get_post_exists' was never awaited testfunction(**testargs) -- Docs: http://doc.pytest.org/en/latest/warnings.html ========================== 1 passed, 1 warnings in 0.10 seconds ==========================
answer count: 2
has comment: http://stackoverflow.com/comment/85703335
type: UnansweredQuestion

http://stackoverflow.com/a/49326252
type: Answer
answers question: http://stackoverflow.com/q/49326093
has comment: http://stackoverflow.com/comment/85655167
has comment: http://stackoverflow.com/comment/85655684
has comment: http://stackoverflow.com/comment/85654117
has comment: http://stackoverflow.com/comment/85656873
has comment: http://stackoverflow.com/comment/85655751
has comment: http://stackoverflow.com/comment/85655327
type: AcceptedAnswer
downvote count: 0
has body: You actually have everything you need at hand already. Just do it like this: import random import matplotlib.pyplot as plt import matplotlib.patches as patches n = 1000 xlo, xhi = -109, -102 ylo, yhi = 37, 41 x_rand = [random.uniform(xlo, xhi) for _ in range(n)] y_rand = [random.uniform(ylo, yhi) for _ in range(n)] ax = plt.figure().gca() ax.scatter(x_rand, y_rand, s=5) ax.add_patch(patches.Rectangle((xlo,ylo), abs(xlo-xhi), abs(yhi-ylo), linewidth=1, edgecolor='r', facecolor='none', linestyle='--')) plt.show() which gives you From your comments I sense you're looking for something like this: import random import matplotlib.pyplot as plt import matplotlib.patches as patches w = 1 n = 100 quadrants = [(x, y) for x in range(-1, 1) for y in range(-1, 1)] ax = plt.figure(figsize=(8,8)).gca() markers = ['x', '^', 'o', ','] for marker, q in zip(markers, quadrants): xlo, ylo = q xhi, yhi = xlo+w, ylo+w x_rand = [random.uniform(xlo, xhi) for _ in range(n)] y_rand = [random.uniform(ylo, yhi) for _ in range(n)] ax.scatter(x_rand, y_rand, s=25, marker=marker) ax.add_patch(patches.Rectangle((xlo,ylo), abs(xlo-xhi), abs(yhi-ylo), linewidth=1, edgecolor='k', facecolor='none', linestyle='--'))
upvote count: 1
has comment: http://stackoverflow.com/comment/85655509
accepted answer of: http://stackoverflow.com/q/49326093
has comment: http://stackoverflow.com/comment/85655047
has comment: http://stackoverflow.com/comment/85655668
has comment: http://stackoverflow.com/comment/85654786
has comment: http://stackoverflow.com/comment/85655284
has comment: http://stackoverflow.com/comment/85656706
score: 1
has comment: http://stackoverflow.com/comment/85655066

http://stackoverflow.com/q/49292321
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49376516
tagged with: spacy
tagged with: nltk
answer count: 1
downvote count: 0
score: 4
has body: The code as follows: import spacy from nltk import Tree en_nlp = spacy.load('en') parsed = en_nlp(u"Photos under low lighting are poor, both front and back cameras.") print(u'sentence:{0}'.format(parsed.text)) try2 = [] print(u'parsed_sentence_children::{0}'.format([(x.text,x.pos_,x.dep_,[(x.text,x.dep_) for x in list(x.children)]) for x in parsed])) print("\n\n") for x in parsed: if x.pos_=="NOUN" and x.dep_=="nsubj": print(u'Noun and noun subject:{0}'.format(try2 =[(x.text,x.pos_,x.dep_,[(x.text,x.pos_)for x in list(x.ancestors)])]) The output to this is: [(u'Photos', u'NOUN', u'nsubj', [(u'are', u'VERB')] Now I wish to print acomp children of: [(u'are', u'VERB')] which is the ancestor of: [(u'Photos', u'NOUN', u'nsubj')] How can I do this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85753731
tagged with: python
has comment: http://stackoverflow.com/comment/85592557
has title: How can I get children of an ancestor using spacy dependency tree in python
accepted answer: http://stackoverflow.com/a/49376516
favorite count: 0

http://stackoverflow.com/q/49332375
tagged with: hotkeys
type: Question
has body: I'm using Python 3.6 on Windows 7 64bit. It worked once but after it's not working. I tried it in several versions, but the result is the same. anyone know how to fix this? import pyautogui pyautogui.hotkey('ctrl', 'c') # ctrl-c to copy pyautogui.hotkey('ctrl', 'v') # ctrl-v to paste
tagged with: python
type: UnansweredQuestion
has title: Second hotkey after the first is not working using pyautogui in Python
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/78084561
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/137662222

http://stackoverflow.com/q/49388628
has answer: http://stackoverflow.com/a/49394426
has answer: http://stackoverflow.com/a/61850514
type: UnansweredQuestion
has title: It is necessary use db.init_app or SQLAlchemy(app) is the same in Flask?
tagged with: flask
downvote count: 1
upvote count: 13
has answer: http://stackoverflow.com/a/61318751
has body: Checking Flask and Flask-SQLAlchemy doc i have a confusion, if i have: models.py: from flask_sqlalchemy import SQLAlchemy #:Use or not db = SQLAlchemy() class User(db.Model): __tablename__ = "USERS" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(25), nullable=False) password = db.Column(db.String(255), nullable=False) config.py: import os class Config(object): DEBUG = True SECRET_KEY = os.urandom(12) SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = "mysql://root:@localhost/example" app.py: from config import Config from models import db from models import User app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) if __name__ == "__main__": db.init_app(app) with app.app_context(): db.create_all() app.run() is necessary use: db = SQLAlchemy(app) after app.config.from_object(Config) or db.init_app(app) is the same? Because i founded some examples of flask with only db = SQLAlchemy() in models.py and have db.init_app(app) before app.run() And so founded examples with db = SQLAlchemy(app) override in app.py with no db.init_app(app) I printed both values and get: with only db in models: &lt;SQLAlchemy engine=None&gt; the problem is: The app create the tables in my database But engine=None with db = SQLAlchemy(app) override &lt;SQLAlchemy engine=mysql://root:***@localhost/hsl_db?charset=utf8&gt; the problem is: The app dont create the tables in my database What is the correct way to assign the database of SQLAlchemy to Flask app?
answer count: 3
tagged with: python
tagged with: sqlalchemy
favorite count: 0
type: Question
score: 12

http://stackoverflow.com/comment/85811929
comment on: http://stackoverflow.com/q/49405240
has text: @Giacomo Catenazzi how do you iterate over all attributes if you only have the attribute itself and not the object (nor even the class) it belongs to?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49418478
has comment: http://stackoverflow.com/comment/85838751
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85838732
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49419331
has comment: http://stackoverflow.com/comment/85838752
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/85838767
has comment: http://stackoverflow.com/comment/85839104
tagged with: matrix
duplicate of: http://stackoverflow.com/q/588004
has body: A = array([[ 1., 0., 0.], [ -9., 28., -9.], [ 0., 0., 1.]]) X = array([-0., -0.125, 0. ]) y = np.linalg.solve(A, X) Is there an explanation for why python keeps giving me the answer: y = array([-1.92747053e-18, -4.46428571e-03, 0.00000000e+00]) When y[0] and y[2] should clearly both be 0?
score: 0
has comment: http://stackoverflow.com/comment/85838790
has comment: http://stackoverflow.com/comment/85838947
tagged with: arrays
answer count: 1
upvote count: 1
downvote count: 1
has title: Python solving matrix simultaneous equation incorrectly

http://stackoverflow.com/comment/85607231
type: AnswerComment
comment on: http://stackoverflow.com/a/49289415
score: 0
has text: What I meant was if I have df2['Field3'], df2['Field4'], etc, etc and df1['Field5'], df1['Field6'], etc, etc. Do I have to list all these out in order to maintain them in the merge?
type: Comment

http://stackoverflow.com/q/49433314
tagged with: file
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/85868450
has comment: http://stackoverflow.com/comment/85868865
has answer: http://stackoverflow.com/a/49433341
accepted answer: http://stackoverflow.com/a/49433341
favorite count: 0
has body: Do you have any suggestions for this script? file.txt: 17 1 11 1 13 15 11 5 7 21 19 17 13 19 11 7 1 3 5 3 11 9 7 15 13 21 19 17 27 25 23 9001 9003 9023 9044 9055 9007 Code: l2=[] with open("file.txt") as f: data = f.read() l1 = list(data.split('\n')) for item in l1: if item&gt;=9000: l2.append(item) else: item = item+9000 l2.append(item) print(l2) Error: if item&gt;=9000: TypeError: '&gt;=' not supported between instances of 'str' and 'int'
type: Question
tagged with: python-3.x
upvote count: 0
answer count: 1
tagged with: python
tagged with: iteration
linked to: http://stackoverflow.com/q/642154
type: AnsweredQuestion
has title: Iteration file with Python 3

http://stackoverflow.com/q/49350307
tagged with: multilabel-classification
answer count: 0
score: 1
has title: multi label classification with bad performance in tensorflow
downvote count: 0
upvote count: 1
tagged with: text-classification
tagged with: tensorflow
favorite count: 0
type: Question
has body: I tried to do multi-label classification on tensorflow, but i got bad performance. Input:[1,0,1, ...,0] (one-hot) and text content def lstm_cell(): return tf.contrib.rnn.BasicLSTMCell(self.config.hidden_dim, state_is_tuple=True) def gru_cell(): return tf.contrib.rnn.GRUCell(self.config.hidden_dim) def dropout(): if (self.config.rnn == 'lstm'): cell = lstm_cell() else: cell = gru_cell() return tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.keep_prob) model: embedding layer with tf.device('/cpu:0'): embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim]) embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x) bi-lstm with tf.name_scope("rnn"): cells = [dropout() for _ in range(self.config.num_layers)] rnn_cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True) _outputs, _ = tf.nn.dynamic_rnn(cell=rnn_cell, inputs=embedding_inputs, dtype=tf.float32) last = _outputs[:, -1, :] active by relu with tf.name_scope("score"): fc = tf.layers.dense(last, self.config.hidden_dim, name='fc1') fc = tf.contrib.layers.dropout(fc, self.keep_prob) fc = tf.nn.relu(fc) self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2') self.y_pred_cls = tf.nn.sigmoid(self.logits, name='pred') use sigmoid cross entropy with tf.name_scope("optimize"): cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.input_y) self.loss = tf.reduce_mean(cross_entropy) self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss) calculate acc with tf.name_scope("accuracy"): threashold=0.5 self.labels = tf.equal(self.input_y, 1) self.preds = tf.greater_equal(self.y_pred_cls,threashold) self.correct_num = tf.divide(tf.size(tf.where(tf.logical_not(tf.logical_xor(self.labels, self.preds)))),2) self.total_num = tf.size(self.input_y) self.correct_pred = tf.divide(tf.cast(self.correct_num, tf.float32),tf.cast(self.total_num, tf.float32)) self.acc = tf.reduce_mean(tf.cast(sel…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85737158
score: 0
has text: @daniel451 I'm already using multiple cores elsewhere, so adding that here wouldn't improve things for me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49367278

http://stackoverflow.com/comment/85752738
has text: try `np.asarray(np.where(fdiff>0)[0])+1`
score: 0
comment on: http://stackoverflow.com/q/49375579
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49309916
has answer: http://stackoverflow.com/a/49310376
score: -2
has title: Python Array out of bounds error
tagged with: python
possible better answer: http://stackoverflow.com/a/49310188
has body: I am getting an array error out of bounds issue. I am trying loop through a multi-dimensional array and add the value from the formula to each element. How do i fix the loop so i jump out of the array bounds. z=int(4.3/7.9) V =51 T =51 r = 1 c = 1 a=[[0]*c for i in range(r)] for r in range(1,51): for c in range(1,51): a[c][r]=35.74 + 0.6215*T - (35.75*V)**0.16 + (0.4275*T*V)**0.16 print() #print to html file down below outfile=open("c:\\data\\pfile.html","w") outfile.write(" ") outfile.write(" ") outfile.write(" ") outfile.write(" Kye Fullwood ") outfile.write(" \r\n") outfile.write(" ") outfile.write(" ") outfile.write(" This is a Windchill table ") outfile.write(" ") for V in range(1,51,1): outfile.write(" ") for TV in range(1,51,1): outfile.write(" "+str(a[r][c])+" \r\n") outfile.write(" ") outfile.write(" ") outfile.write(" ") outfile.write(" ") outfile.close() print("complete")
has comment: http://stackoverflow.com/comment/85621896
type: Question
answer count: 2
upvote count: 0
downvote count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/49310376
has answer: http://stackoverflow.com/a/49310188
has comment: http://stackoverflow.com/comment/85622819
type: AnsweredQuestion

http://stackoverflow.com/comment/85626702
comment on: http://stackoverflow.com/a/49312361
type: Comment
has text: Don't forget parens. `|` has lower precedence than `-`
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85769062
type: AnswerComment
has text: @MihaiAlexandru-Ionut Thanks
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49383951

http://stackoverflow.com/q/49392595
type: Question
tagged with: ajax
tagged with: python
has answer: http://stackoverflow.com/a/49413053
tagged with: cors
type: UnansweredQuestion
score: 0
answer count: 1
has body: I have a flask app running on 127.0.0.1:5000 and another website running on 127.0.0.1:8000. The website has js function making a post request to the flask app, trying to post some dictionary data to the flask app. In the js function i'm using ajax: $.ajax({ url: "http://127.0.0.1:5000/", method: "POST", headers: { 'Access-Control-Allow-Origin':'*',}, data: dict, }); In the flask app: @app.route('/',methods=['POST']) def hello_world(): ok = request.get_json() print(ok['id']) return '', 200 Initially in the ajax call, i didn't put any headers. But it prompted me "Cross-Origin Request Blocked". Then I add the header and the request apparently turns into an OPTIONS request, which after googling, suggests pre-flight check. How can I avoid the check? Or why does this check returns a 200 code and the actual post request does not get through? Please give me some help! I am stuck on this for hours. Thanks! (p.s. i have tried installing flask_cors library and applied it in the flask app but it also does not work)
has title: How to bypass preflight check while setting Access-Control-Allow-Origin header?
has comment: http://stackoverflow.com/comment/85786838
tagged with: flask
tagged with: http

http://stackoverflow.com/a/57041041
answers question: http://stackoverflow.com/q/49435873
has body: You can use below code to maximize the browser driver.maximize.window()
type: Answer
score: 0

http://stackoverflow.com/q/49291427
score: 0
tagged with: insert-update
has title: manually update django model instance in put request. django django rest framework
has answer: http://stackoverflow.com/a/49291847
answer count: 1
has body: The way I am doing my put request by exposing the parent model and then searching through the room_set becasue I need to see if the user has permissions to mess with the parent models related objects. now with that away, I am trying to do a manual put. This put will act more like a patch but the CORS policy doesn't like it when I use PATCH in my local. so I put. So Im a little confused about what to do next. How do I add the new value to my object or ignore the attribute on my model if I don't have any data on it in the request? Here is the model and the put request. class Room(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) online = models.BooleanField(default=False) description = models.CharField(max_length=1000, blank=True, null=True) privateroom = models.BooleanField(default=False) semiprivateroom = models.BooleanField(default=False) seatedcapacity = models.CharField(max_length=10, null=True, blank=True) standingcapacity = models.CharField(max_length=10, null=True, blank=True) minimumspend = models.PositiveSmallIntegerField(blank=True, null=True) surroundsoundamenity = models.BooleanField(default=False) outdoorseatingamenity = models.BooleanField(default=False) stageamenity = models.BooleanField(default=False) televisionamenity = models.BooleanField(default=False) screenprojectoramenity = models.BooleanField(default=False) naturallightamenity = models.BooleanField(default=False) wifiamenity = models.BooleanField(default=False) wheelchairaccessibleamenity = models.BooleanField(default=False) cocktailseatingseatingoption = models.BooleanField(default=False) classroomseatingoption = models.BooleanField(default=False) ushapeseatingoption = models.BooleanField(default=False) sixtyroundseatingoption = models.BooleanField(default=False) boardroomseatingoption = models.BooleanField(default=False) theaterseatingoption = models.BooleanField(default=False) hallowsquareseatingoption = m…
has comment: http://stackoverflow.com/comment/85585785
has comment: http://stackoverflow.com/comment/85585830
type: Question
accepted answer: http://stackoverflow.com/a/49291847
tagged with: django
tagged with: python
tagged with: django-rest-framework
tagged with: put
type: AnsweredQuestion

http://stackoverflow.com/comment/85733307
has text: You can do something such as: `[*range(1, 10), 20, 30, 40, *range(400, 410)]` as well...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49366161
score: 3

http://stackoverflow.com/q/49422473
has answer: http://stackoverflow.com/a/49423533
answer count: 1
has body: I am doing figure extractor from scanned documents. using 1100x850 images. we use 44x34 grids of image. so that last layer will be 1496 fully connected layer. label is 44x34 BINARY array which is 1 for figure rigion and 0 for non figure region. i.e if figure falls within (top right) (x,y)=(0,0) (bottom left) (x,y)=(50,50) then bin array has 1 at (0,0) (0,1) and (1,0) (1,1) these positions and rest 0s. so i have buit a neural network model. following is the structure. conv(5,2,48) maxpool(3,2) conv(5,2,96) maxpool(3,2) conv(5,2,96) maxpool(3,2) FC-1496 The notation conv(k,d, n) denotes a convolutional layer with n filters, each of size k × k, applied with a shift of d pixels; maxpool(k, d) denotes a downsampling operation over k×k windows, applied with a shift of d pixels. FC-1496 refers to the final fully connected layer which connects the hidden units from the previous layers to the 1496 output units (we have 1496 units for a 44x34 grid). So my question is how to feed input ( images and labels (array) ) to this model using keras and tensor flow. here is the model code from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.layers.core import Activation from keras.layers.core import Dense from keras.models import Sequential from keras.layers import Flatten xtrain=#image of 850*1100 for 10 images 10 850*1100 xtest=#binary array of size 1496 for 10 images size is 10*1496 # initialize the model model = Sequential() model.add(Conv2D(48, 5, 2, input_shape=(1100, 850, 1))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3, 3), strides=2)) model.add(Conv2D(96, 5, 2)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3, 3), strides=2)) model.add(Conv2D(96, 5, 2)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(3, 3), strides=2)) model.add(Flatten()) model.add(Dense(1496, activation='sigmoid')) model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['accuracy'])
has title: image input to neural networks
type: Question
has comment: http://stackoverflow.com/comment/85845767
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/85846001
tagged with: keras
has comment: http://stackoverflow.com/comment/85845860
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49423533
score: 0

http://stackoverflow.com/q/49373068
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51953285
type: UnansweredQuestion
tagged with: python
has title: Tensorflow -- Custom Op -- Pass parameter as mutable objects (like pass by reference)
has body: I try to develop a custom op in tensorflow during which I change values belonging to the input-tensor, and which after the op is finished should still reflects these changes. The challenge is, that python passes the function parameters by assignment (== immutable type in our case), and thus blocks me from accessing the data I actually want to access in the op. . Minimal Working Example: test_script.py img = imread("some image path"); img = ((img_gt[:, : , 0:3]).flatten()).astype('float32') img[0] = 50 print "First time (start value): ", img[0] Custom_Loss_Module = tf.load_op_library('some shared library') with tf.Session(''): Custom_Loss_Module.custom_loss(img) print "Fourth time (after custom op): ", img[0] custom_op_main.cpp REGISTER_OP("CustomLoss") .Input("mat: float") class CustomLossOp : public OpKernel { public: explicit CustomLossOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { Tensor &amp; tensor_img = const_cast&lt;Tensor &amp;&gt;(context-&gt;input(0)); float* pointer_img = reinterpret_cast&lt;float*&gt;(const_cast&lt;char*&gt;((tensor_img.tensor_data()).data())); std::cout &lt;&lt; "Second time (in op): " &lt;&lt; pointer_img[0] &lt;&lt; "\n" &lt;&lt; std::flush; pointer_img[0] = 100; std::cout &lt;&lt; "Third time (in op): " &lt;&lt; pointer_img[0] &lt;&lt; "\n" &lt;&lt; std::flush; } }; Output: First time (start value): 50 Second time (in op): 50 Third time (in op): 100 Fourth time (after custom op): 50 &lt;-- I want to see a 100 here :( . Now as mentioned above, I know where this behaviour comes from, and I know that this is to be expected. However, I would like to find a way so that the change from 50 to 100 (done in the custom op) is mutable, and thus is being reflected by the img-tensor once the custom op is finsihed. In C++-terms: I want to pass the function parameter by reference and not by assignment. . What I tried so far: I tried to use the standard python trick and pass the parameter a…
tagged with: c++
has comment: http://stackoverflow.com/comment/90207203
score: 2
upvote count: 2
downvote count: 0
answer count: 1
tagged with: pass-by-reference
tagged with: tensorflow

http://stackoverflow.com/comment/85595390
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49296552
has text: It will answer your question https://stackoverflow.com/a/34325723/7340533

glob
tags question: http://stackoverflow.com/q/49433240
tags question: http://stackoverflow.com/q/49381899
tag name: glob
type: Tag

http://stackoverflow.com/q/49284908
has comment: http://stackoverflow.com/comment/85717044
score: 0
has body: I have recently experimented with reload(). Let us consider the following simple module mother_and_child_in_same_file.py: class mother( object ): def foobar( self ): print "foobar mother" class child( mother ): def foobar( self ): self.__class__ = child # None of the two following methods is correctly working after a reload, # except if we # add the previous line concerning __class__; then both methods work # correctly. mother.foobar( self ) #super( child, self ).foobar() print "foobar child" Used in the script: import mother_and_child_in_same_file a = mother_and_child_in_same_file.child() a.foobar() print "============ RELOAD" reload( mother_and_child_in_same_file ) a.foobar() It results in the expected output $ python mother_and_child_in_same_file_TEST.py foobar mother foobar child ============ RELOAD foobar mother foobar child But only if self.__class__ is forced as explained in the code. The problem is thus that existing objects may "loose" their class when using reload(), making it necessary to reassign self.__class__ at the beginning of every method of these objects, such that no error is obtained when calling the mother (if I understand correctly). This is rather heavy, and I have tried to do this automatically using a class decorator. Here is the mother_and_child_in_same_file_decorator.py module: def my_decorator( cls ): def prepend_cls_instance_method_with_class_update( m ): def prepended_method( self, *args ): self.__class__ = cls print "After: self.__class__ = %s" % self.__class__ m( self, *args ) return prepended_method for method_name in dir( cls ): if method_name[:2] == "__": continue method = getattr( cls, method_name ) if hasattr( method, '__call__' ): prepended_method = prepend_cls_instance_method_with_class_update( method ) print "setattr( %s, '%s', %s )" % ( cls, method_name, prepended_method ) setattr( cls , method_name , prepended_method ) return cls class mother( object ): def foobar( self ): print "foobar mother" @my_decorator class child( mot…
has comment: http://stackoverflow.com/comment/85702100
type: Question
has comment: http://stackoverflow.com/comment/85701802
answer count: 2
has answer: http://stackoverflow.com/a/49331264
has title: reassigning self.__class__ automatically at the beginning of each method using a class decorator?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85664654
has comment: http://stackoverflow.com/comment/85716040
has answer: http://stackoverflow.com/a/49358655

http://stackoverflow.com/q/49418746
tagged with: cs50
has comment: http://stackoverflow.com/comment/85839124
has comment: http://stackoverflow.com/comment/85839180
has answer: http://stackoverflow.com/a/49418987
tagged with: python
has body: This is one of my first programs in Python, so I might be missing something obvious. In this first part of my code that I've posted, I'd like to make sure the user passes a command line argument. If not, I want to show an error and return 1. When I run the code without a command line argument, the program has the expected behavior because the error prints and the program exits. However, when I run a checker on this, I get an error: handles lack of argv[1]. expected exit code 1, not 0. Any ideas on what I may be missing? import sys import cs50 from cs50 import get_string def main(argv): # Check for command line argument if (len(sys.argv) != 2): print("Error: Please input numeric key in command line.") return 1 if __name__ == "__main__": main(sys.argv)
upvote count: 6
type: Question
tagged with: python-3.x
tagged with: return
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/85839570
favorite count: 0
has title: Exiting with 1 in Python

http://stackoverflow.com/comment/85824280
has text: There's no need to have a new line for ***every*** line of code you have. It makes the post excessively long and difficult to read and follow.
comment on: http://stackoverflow.com/q/49410682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49391150
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/115167871
has body: the convolution is the summation of the element-wise product but the first vector goes forward, and the second vector goes backwards. It'll be: 1*0.5 + 2*1 + 1*0 = 2.5 Cheers.
answers question: http://stackoverflow.com/q/49391065
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/49391065

http://stackoverflow.com/q/49335139
score: 1
possible better answer: http://stackoverflow.com/a/50874187
favorite count: 0
type: Question
has title: How can i know that a specific Index template parameter is empty by pywikibot?
has answer: http://stackoverflow.com/a/50874187
tagged with: pywikibot
has answer: http://stackoverflow.com/a/49346978
accepted answer: http://stackoverflow.com/a/49346978
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
has body: I am trying to fill-up page numbers of a Book in its Index Wikisource page. The following code writes well in the specific pageNumber parameter. If the page is empty, it looks fine. But if i run the code another time, due to the concatenation the 67 becomes 6767. How can i know that the pageNumber parameter ('|Number of pages=') is empty? or If the parameter already filled how can i set the skip option in the code. The writing code;- #!/usr/bin/env python # -*- coding: utf-8 -*- import pywikibot indexTitle = 'அட்டவணை:தமிழ் நாடகத் தலைமை ஆசிரியர்-2.pdf' indexPages = '67' site1 = pywikibot.Site('ta', 'wikisource') page = pywikibot.Page(site1, indexTitle) indexTitlePage = page.text.replace('|Number of pages=','|Number of pages='+indexPages) page.save(summary='67')
upvote count: 1

http://stackoverflow.com/q/49409615
has comment: http://stackoverflow.com/comment/85970054
has answer: http://stackoverflow.com/a/53604229
tagged with: arduino
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85970099
favorite count: 0
linked to: http://stackoverflow.com/q/7035526
type: Question
tagged with: raspberry-pi
has body: I am trying to collect data coming in from 3 Arduino nodes (which are connected to some sensors) via XBees. The 3 Arduino nodes are each attached to an XBee Series 1 radio (End Device), while the Coordinator is connected to my PC (but it will later be connected to a Raspberry Pi 2 Model B). I was thinking, is there is a way to implement UART interrupts in Python on the Raspberry Pi? This is because, based on my code below, I am adopting a polling approach to read the data that is coming in from my 3 Arduino sensor nodes. The data the is coming in from the 3 Arduino sensor nodes every second, as seen from the code below. However, my polling approach is causing some issues because I only do "arduino.readline()" at the very beginning of my code and after that, I will proceed on to do other things in the Python code. Hence, I was wondering if there are any ways to implement UART interrupt with Python so that whenever there is incoming data, I will do an arduino.readline() and proceed on to handle the data. My codes are as of below: (The Arduino code is about the same for all of the 3 nodes.) Python code: import threading import logging import time import serial import csv # Arduino; Arduino is now replaced by XBee modules arduino = serial.Serial('COM18', 9600, timeout=1) # Open serial port. By right, should check if it is open def checker(field): if 'b' in field: field = field.replace('b', '') if 't' in field: field = field.replace('t', '') return field def make_backup(finalmatrix, field_send, flag): # Back up the 2 most-recent data. matrix1 = [] # declares a list matrix1.append(flag) # appends the counter 'flag' matrix1.extend(field_send) # attaches the list to the end of current list; doesn't work with int # finalmatrix is a list of list; if len(finalmatrix) == 2 means: finalmatrix == [[1,2], [3,4]] if (len(finalmatrix) == 2): finalmatrix = finalmatrix[1:] # Create a new list, take the 2nd mini-list in the list and put it in the new list finalmatrix.append(matrix1) # …
type: UnansweredQuestion
tagged with: python
has title: Raspberry Pi UART Interrupt in Python
has comment: http://stackoverflow.com/comment/85907338
score: 2
upvote count: 2

http://stackoverflow.com/q/49297291
answer count: 1
has answer: http://stackoverflow.com/a/54393709
tagged with: speech-recognition
favorite count: 0
type: Question
has body: How can we improve the accuracy of speech to text conversion using recognize_sphinx API in Python? Please find the below code, which needs to improve the accuracy base! import speech_recognition as sr # Obtain path to "english.wav" in the same folder as this script from os import path AUDIO_FILE = path.join(path.dirname(path.realpath(file)), "english.wav") AUDIO_FILE = path.join(path.dirname(path.realpath(file)), "french.aiff") AUDIO_FILE = path.join(path.dirname(path.realpath(file)), "chinese.flac") # Use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # Read the entire audio file # Recognize speech using Sphinx try: print("Sphinx thinks you said " + r.recognize_sphinx(audio)) except sr.UnknownValueError: print("Sphinx could not understand audio") except sr.RequestError as e: print("Sphinx error; {0}".format(e))
upvote count: 5
tagged with: speech-to-text
tagged with: google-speech-api
tagged with: python
has comment: http://stackoverflow.com/comment/127370067
has title: How to improve the accuracy for speech-to-text conversion using recognize_sphinx API in Python
tagged with: cmusphinx
score: 5
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49288735
accepted answer of: http://stackoverflow.com/q/49288541
type: Answer
has body: Here's a minimum example to show you how it's done, the change you make is on the render_template line render_template("index.html", friends=friends) from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): friends = [ {'name': 'alice', 'age': '7'}, {'name': 'bob', 'age': '13'}, {'name': 'eve', 'age': '42'} ] return render_template("index.html", friends=friends) if __name__ == "__main__": app.run(debug=True) and the HTML Friends Name: Age: {% for friend in friends %} {{friend['name']}} {{friend['age']}} {% endfor %}
answers question: http://stackoverflow.com/q/49288541
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49421510
has comment: http://stackoverflow.com/comment/85953131
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/49421449
downvote count: 0
has body: Replace all of this: if 'name' in appliance: temp_item['name'] = appliance['name'] if 'type' in appliance: temp_item['type'] = appliance['type'] if 'ping-status' in appliance: temp_item['ping-status'] = appliance['ping-status'] if 'sync-status' in appliance: temp_item['sync-status'] = appliance['sync-status'] if 'services-status' in appliance: temp_item['services-status'] = appliance['services-status'] if 'orgs' in appliance: temp_item['orgs'] = appliance['orgs'] if 'ownerOrg' in appliance: temp_item['ownerOrg'] = appliance['ownerOrg'] if 'softwareVersion' in appliance: temp_item['softwareVersion'] = appliance['softwareVersion'] if 'ipAddress' in appliance: temp_item['ipAddress'] = appliance['ipAddress'] with a loop: for x in ['name', 'type', 'ping-status', 'sync-status', 'services-status', 'orgs', 'ownerOrg', 'softwareVersion', 'ipAddress']: if x in appliance: temp_item[x] = appliance[x]
type: AcceptedAnswer
score: 6
has comment: http://stackoverflow.com/comment/85844136
accepted answer of: http://stackoverflow.com/q/49421449

http://stackoverflow.com/a/49303726
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85637280
accepted answer of: http://stackoverflow.com/q/49303263
score: 0
answers question: http://stackoverflow.com/q/49303263
type: Answer
has comment: http://stackoverflow.com/comment/85610623
has comment: http://stackoverflow.com/comment/85645096
has comment: http://stackoverflow.com/comment/85611788
has body: I suggest you the following update of your original code. I assumed you wanted to display the curve with a going from 0 to 1 by 0.01 step. I also added some comments for readability and for you to better understand the code: import matplotlib.pyplot as plt import numpy as np # Define constants omega_0 = 0.6911 w_0 = -0.77 # Set 'a' values from 0 to 1 by 0.01 step a = np.arange(0, 1, 0.01) # Set 'w' values associated with each 'a' value omega_phi = (omega_0*(a**(-3.0*w_0)))/((omega_0*(a**(-3.0*w_0))) + 1 - omega_0) w = w_0 + (((w_0*(1.0 - w_0**2.0))/(1.0 - 2.0*w_0 + 4.0*w_0**2))*((omega_phi/(1.0 - omega_phi)))) + ((((-1.0)*w_0*(1.0 - w_0**2.0))/(1.0 - 3.0*w_0 + 12.0*w_0**2))*((omega_phi/(1.0 - omega_phi))**2.0)) + ((((1.0)*w_0*(1.0 - w_0**2.0))/(1.0 - 4.0*w_0 + 24.0*w_0**2))*((omega_phi/(1.0 - omega_phi))**3.0)) # Plot the curve with all (a,w) points plt.plot(a,w) plt.xlabel('a') plt.ylabel('w') plt.grid(True) # Show the curve plt.show()

http://stackoverflow.com/comment/86067717
comment on: http://stackoverflow.com/a/49526918
type: Comment
score: 0
type: AnswerComment
has text: `doc` is the default type name used by the library, see here: https://github.com/elastic/elasticsearch-dsl-py/blob/762f0cd5dfed0bd0f1e338bc508f9ac0c226cffe/docs/persistence.rst#class-meta-options You can change that in the `Meta` class. It doesn't matter much as long as you're using the same type everywhere. It could be `foobar` for what it's worth.

http://stackoverflow.com/comment/85654322
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49326143
has text: With this I only get the value `0.0.1.8`. The problem is that my final output should be a list of `len(n)` with items `NA` if no match with the dictionary or the value `0.0.18` if there is a match ...

http://stackoverflow.com/comment/85720371
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49358457
has text: Then, I'm afraid, you will have to take the long road and reduce your original code to the smallest code that still reproduces the issue in order to post that here.
type: Comment

http://stackoverflow.com/q/49312665
answer count: 1
downvote count: 1
has title: Find all tags of multi-attribute class bs4
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I know to find all occurrences of a class with one attribute is the following. soup.find_all('a', class_='className') But this does not get all tags for a class such as below. soup.find_all('a', class_='class Name') How can I find all tags of a beautiful soup object that has a multi-attribute class such as "class_='class Name'"?
tagged with: python
linked to: http://stackoverflow.com/q/29877663
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49313157
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/29877663
has answer: http://stackoverflow.com/a/49313157
upvote count: 1

http://stackoverflow.com/q/49413607
tagged with: python-import
answer count: 0
has comment: http://stackoverflow.com/comment/85832443
score: 0
has comment: http://stackoverflow.com/comment/85831762
has comment: http://stackoverflow.com/comment/85831442
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/85831703
has comment: http://stackoverflow.com/comment/85832507
type: Question
tagged with: qfiledialog
linked to: http://stackoverflow.com/q/46337716
type: UnansweredQuestion
has body: i am trying to create a fileDialog that will display a Window that allow the user to search for files. but the system is displaying this error : [pylint] E0611:No name 'QApplication' in module 'PyQt5.QtWidgets' [pylint] E0611:No name 'QWidget' in module 'PyQt5.QtWidgets' [pylint] E0611:No name 'QInputDialog' in module 'PyQt5.QtWidgets' [pylint] E0611:No name 'QLineEdit' in module 'PyQt5.QtWidgets' [pylint] E0611:No name 'QFileDialog' in module 'PyQt5.QtWidgets' code: import sys from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog from PyQt5.QtGui import QIcon class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 file dialogs - pythonspot.com' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.openFileNameDialog() self.openFileNamesDialog() self.saveFileDialog() self.show() def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options) if fileName: print(fileName) def openFileNamesDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(self,"QFileDialog.getOpenFileNames()", "","All Files (*);;Python Files (*.py)", options=options) if files: print(files) def saveFileDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options) if fileName: print(fileName) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/85828981
tagged with: python
has title: what is the error in the import statements
duplicate of: http://stackoverflow.com/q/46337716
has comment: http://stackoverflow.com/comment/85831487

http://stackoverflow.com/comment/85649896
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49324209
has text: you *could* set `my_min` to `sample_list[valid_index]` or `sample_list[0:1]` or any other single value from the list, since you check all the values
score: 0

http://stackoverflow.com/comment/85796808
score: 0
type: AnswerComment
has text: print(dir(numpy))
type: Comment
comment on: http://stackoverflow.com/a/49397511

http://stackoverflow.com/comment/85686675
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49330273
score: 0
has text: Fantastic solution! On extreme cases where there is more than one entry with the same `air_id` or `hpg_id` and both occurrences have different latitude/longitude coordinates (for some weird reason), is add all the occurrences of that id (with different lat/lon coordinates) to the result table, which is absolutely great! In terms of performance, it took only 16s to process `df1` with **2343828** rows and `df2` with 10 rows. It's pretty incredible, congratulations!

http://stackoverflow.com/comment/85750080
has text: Not many algorithms are cubic. What are you trying to implement?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49374427
type: QuestionComment

del
tag name: del
tags question: http://stackoverflow.com/q/49290736
type: Tag

http://stackoverflow.com/a/49319065
downvote count: 0
has body: Using BeautifulSoup import requests from bs4 import BeautifulSoup r = requests.get('http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&amp;Sect2=HITOFF&amp;d=PALL&amp;p=1&amp;u=%2Fnetahtml%2FPTO%2Fsrchnum.htm&amp;r=1&amp;f=G&amp;l=50&amp;s1=3944788.PN.&amp;OS=PN/3944788&amp;RS=PN/3944788') soup = BeautifulSoup(r.text, 'lxml') table = soup.find_all('table')[4] result = table.find('tr').text print(result) # Current U.S. Class: 235/54F Explanation The table you are after, is the 5th table in the page. find_all('table') returns a list of all the tables. So, find_all('table')[4] will give the 5th table. The text you want, is located in the first row, or the first tr tag. table.find('tr') returns the first tr tag found inside the table. Finally, .text gives you the text inside the tag.
accepted answer of: http://stackoverflow.com/q/49318015
answers question: http://stackoverflow.com/q/49318015
type: Answer
has comment: http://stackoverflow.com/comment/85670911
score: 2
has comment: http://stackoverflow.com/comment/85670484
has comment: http://stackoverflow.com/comment/85670517
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85563058
score: 0
has text: Oh yeah, you're right, Chris. `gen` is a generator in the docs, not a function returning a generator.
type: Comment
comment on: http://stackoverflow.com/a/49280127
type: AnswerComment

http://stackoverflow.com/a/49327398
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/85656537
answers question: http://stackoverflow.com/q/49327344
downvote count: 0
score: 4
has body: Does this do what you want? sorted_points = sorted(points, key=lambda p: p[0]*p[0] + p[1]*p[1]) Another thing to watch out for in your original code is that sorted does not sort the list in place, it creates a new list that is sorted. So when you do points = [3,2,1] sorted(points) print(points) It will appear that your code hasn't sorted anything because you are printing the original list not the newly created sorted one. You can perform a sort in place like so. points = [3,2,1] points.sort() print(points)

http://stackoverflow.com/a/49336096
upvote count: 4
has comment: http://stackoverflow.com/comment/85677821
has comment: http://stackoverflow.com/comment/85673945
has comment: http://stackoverflow.com/comment/85673770
has comment: http://stackoverflow.com/comment/85673556
has comment: http://stackoverflow.com/comment/85677861
has comment: http://stackoverflow.com/comment/85678441
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85678059
has comment: http://stackoverflow.com/comment/85678028
has comment: http://stackoverflow.com/comment/85673636
score: 4
has comment: http://stackoverflow.com/comment/85677690
has comment: http://stackoverflow.com/comment/85680083
answers question: http://stackoverflow.com/q/49332606
has comment: http://stackoverflow.com/comment/85679929
has comment: http://stackoverflow.com/comment/85673530
has comment: http://stackoverflow.com/comment/85673610
has body: As described in NetworkX documentation, simple_cycles uses Johnson's algorithm to find elementary cycles. The complexity of the algorithm is O((V+E).(1+C)) where V is the number of vertices; E is the number of edges; C the number of cycles. In your case V+E ~= 150,000, so assuming the python process is not overloaded, we could expect the running time to be 150,000.K.C. To try to find an estimate of K, you can run the algorithm on smaller graphs, using power of 10 (V+E = 10, 100, 1000 ...) to ensure the running time of the simple_cycles remain proportional to (V+E)(1+C), get a rough value of K and estimate the running time for your graph based on the number of cycles you expect to find. More precisely, if we note R(V+E,C) the actual running time for each of the experimental smaller graph, and C0, C1, ...Cn their respective number of cycles, then we would expect to have R(100,C1) / R(10,C0) ~= 10.K.[(1+C1) / (1+C0)] R(1000,C1) / R(100,C0) ~= 10.K.[(1+C2) / (1+C1)] ... If the simple_cycles running time does not exhibit the complexity of Johnson's algorithm, then there is a non-algorithmic factor which is slowing down/preventing the computation - this would then need to be investigated. Follow-up These are the results of some investigation with the graph you provided. I tried to compute the number of cycles with the NetworkX library for smaller subgraphs and reproduced below some interesting results. There are the number of nodes and edges for each subgraph along with the number of cycles computed. \#Nodes | \#Edges | \#Cycles (computed) ---------------------------------------- 1,000 | 186 | 17 2,000 | 675 | 37 3,000 | 1,460 | 72 4,000 | 2,538 | 2,147 4,250 | 2,881 | 2,351,883 I stopped at #Nodes = 4000 for which I could not get any result within minutes. Let's calculate, for each of these values, the value log10(C)/E with C = \#Cycles and E = \#Edges. E = \#Edges | C = \#Cycles (computed) | log(C)/E | ---------------------------------------------------- 186 | 17 | 0.00…
accepted answer of: http://stackoverflow.com/q/49332606
has comment: http://stackoverflow.com/comment/85678160
has comment: http://stackoverflow.com/comment/85678289
has comment: http://stackoverflow.com/comment/85677911
type: Answer
has comment: http://stackoverflow.com/comment/85673585
has comment: http://stackoverflow.com/comment/85674004
has comment: http://stackoverflow.com/comment/85673748
has comment: http://stackoverflow.com/comment/85678566

http://stackoverflow.com/q/49399198
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49407060
tagged with: tensorflow
favorite count: 0
has title: Sort a tensor based on two columns in tensorflow
tagged with: python
type: Question
upvote count: 2
has body: Is it possible to sort a tensor based on values in two columns in Tensorflow? For example, let's say I have the following tensor. [[1,2,3] [2,3,5] [1,4,6] [2,2,1] [0,4,2]] I would lik it to be sorted first based on the first column and then the second column. After sorting it would look like following. [[0,4,2] [1,2,3] [1,4,6] [2,2,1] [2,3,5]] Is there any way to achieve this using tensorflow? I am able to sort according to a single column. But sorting based on two columns is a problem for me. Please can anyone help?

http://stackoverflow.com/a/49423869
has comment: http://stackoverflow.com/comment/85884482
answers question: http://stackoverflow.com/q/49419621
type: Answer
score: 0
has body: Amend your Regular Expression Extractor configuration as follows: Switch "Field to check" to Request Headers Change your Regular Expression to fundraiserPageID=(\d+) as I see neither quotation marks nor trailing &gt; in your original Referer header References: JMeter: Regular Expressions Using RegEx (Regular Expression Extractor) with JMeter Perl 5 Regex Cheat sheet

http://stackoverflow.com/a/51939526
has comment: http://stackoverflow.com/comment/99521668
accepted answer of: http://stackoverflow.com/q/49413504
has comment: http://stackoverflow.com/comment/109039326
downvote count: 0
has body: TL;DR Add the following to your .bash_profile (or equivalent): export PATH="/usr/local/opt/python/libexec/bin:$PATH" Explanation It seems python via homebrew is now handled differently (see https://docs.brew.sh/Homebrew-and-Python). python3 points to Homebrew’s Python 3.x (if installed) python2 points to Homebrew’s Python 2.7.x (if installed) python points to Homebrew’s Python 2.7.x (if installed) otherwise the macOS system Python. Check out brew info python if you wish to add Homebrew’s 3.x python to your PATH. Checking out brew info python hints at what you need to do: Unversioned symlinks python, python-config, pip etc. pointing to python3, python3-config, pip3 etc., respectively, have been installed into /usr/local/opt/python/libexec/bin The hint being that you therefore have to add /usr/local/opt/python/libexec/bin before /usr/bin in your path (not /usr/local/bin as stated in some sources e.g. https://docs.python-guide.org/starting/install3/osx/) See also https://github.com/Homebrew/homebrew-core/issues/15746
score: 40
answers question: http://stackoverflow.com/q/49413504
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/109039869
type: Answer
has comment: http://stackoverflow.com/comment/109008903
upvote count: 40

http://stackoverflow.com/comment/85654353
comment on: http://stackoverflow.com/a/49325012
has text: It sets `c.var1 = 1` and `c.var2 = 2`. But then you call `B.__init__(self, var3)`, which sets `c.var1 = 3`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49361952
tagged with: python
has body: How to not allowing some users from seeing draft record and create record which by default be in draft state, can anyone help please , I have try this : Shipping Policy multi-company [('state','!=','draft')] Shipping Policy multi-company [(1,'=',1)] The Image Here
has comment: http://stackoverflow.com/comment/86058038
has comment: http://stackoverflow.com/comment/86072861
has answer: http://stackoverflow.com/a/49532117
accepted answer: http://stackoverflow.com/a/49532117
answer count: 1
has title: How to make a user create a record in draft state but not be able to view the created records?
has comment: http://stackoverflow.com/comment/86069985
has comment: http://stackoverflow.com/comment/86070207
type: Question
has comment: http://stackoverflow.com/comment/86037024
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86031213
score: 0
tagged with: odoo-10
tagged with: odoo

http://stackoverflow.com/comment/85778964
comment on: http://stackoverflow.com/a/49377135
score: 0
has text: Anyway, if everyone cites “numpy version x.y.z with the RNG seeded by 72” as their source of randomness so others can reproduce their work, then the problem you’re imagining would affect everyone, even in sequential code. So we can assume it doesn’t exist.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85719653
has text: At first you should check that you have the latest version of `pip` installed. And also be aware that Python 3.7 is not released yet. You should use 3.6 for now.
type: Comment
comment on: http://stackoverflow.com/q/49359744
score: 0
type: QuestionComment

http://stackoverflow.com/q/49386920
has answer: http://stackoverflow.com/a/54869077
has answer: http://stackoverflow.com/a/51932773
has body: I have trying to download the kaggle dataset by using python. However i was facing issues by using the request method and the downloaded output .csv files is a corrupted html files. import requests # The direct link to the Kaggle data set data_url = 'https://www.kaggle.com/crawford/gene-expression/downloads/actual.csv' # The local path where the data set is saved. local_filename = "actsual.csv" # Kaggle Username and Password kaggle_info = {'UserName': "myUsername", 'Password': "myPassword"} # Attempts to download the CSV file. Gets rejected because we are not logged in. r = requests.get(data_url) # Login to Kaggle and retrieve the data. r = requests.post(r.url, data = kaggle_info) # Writes the data to a local file one chunk at a time. f = open(local_filename, 'wb') for chunk in r.iter_content(chunk_size = 512 * 1024): # Reads 512KB at a time into memory if chunk: # filter out keep-alive new chunks f.write(chunk) f.close() Output file Gene expression dataset (Golub et al.) | Kaggle
favorite count: 0
type: Question
upvote count: 20
linked to: http://stackoverflow.com/q/50863516
tagged with: download
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49387122
has answer: http://stackoverflow.com/a/61563277
tagged with: kaggle
answer count: 10
tagged with: python
tagged with: request
has answer: http://stackoverflow.com/a/60690087
has answer: http://stackoverflow.com/a/55156772
has comment: http://stackoverflow.com/comment/90682211
score: 20
has comment: http://stackoverflow.com/comment/85870520
has answer: http://stackoverflow.com/a/79033971
has comment: http://stackoverflow.com/comment/85774892
has title: Download Kaggle Dataset by using Python
downvote count: 0
linked to: http://stackoverflow.com/q/51958553
has answer: http://stackoverflow.com/a/77709393
has comment: http://stackoverflow.com/comment/90681085
tagged with: dataset
has answer: http://stackoverflow.com/a/75813238
has answer: http://stackoverflow.com/a/68191395

http://stackoverflow.com/comment/85850158
type: Comment
type: AnswerComment
has text: Yes, the data was stored as string by default. I didnt know this. If I use np array when saving the data, all is fixed and all solutions given here work. i.e. `np.savetxt("vels.txt", np.array(velocities))`
comment on: http://stackoverflow.com/a/49396877
score: 1

http://stackoverflow.com/comment/85833871
type: Comment
score: 0
type: AnswerComment
has text: I'm not sure about `tflearn` specifically. For `tensorflow` in general, you can find the specific line of code performing the copy in a good DQN implementation [here](https://github.com/dennybritz/reinforcement-learning/blob/master/DQN/dqn.py#L326) (where the `copy_model_parameters()` function is implemented starting at line 150).
comment on: http://stackoverflow.com/a/49415368

http://stackoverflow.com/comment/85665749
comment on: http://stackoverflow.com/q/49331834
type: QuestionComment
type: Comment
has text: What do you want `find` to return if the key is *not* found in the dictionary?
score: 0

http://stackoverflow.com/q/49381439
answer count: 1
tagged with: pymongo
has answer: http://stackoverflow.com/a/49381588
accepted answer: http://stackoverflow.com/a/49381588
favorite count: 0
has title: Try/Except in Python does not run correctly
type: Question
tagged with: mongodb
tagged with: exception
tagged with: python
has comment: http://stackoverflow.com/comment/85763575
has body: I am developing next code to implement pymongo. I want to catch every error, for example, during connection with DB. However, if I write a random IP (which does not exists), try/cath does not runs correctly. 'OK' is printed despite the fact that the IP does not exists. from pymongo import MongoClient from pymongo import errors class Mongo: def __init__(self): db = 'random ip' port = 27017 mps = 50 user = 'admin' pw = 'pw' to=100 print('Creating MongoClient ......') print 'Establishing connection with MongoDB ...... ', try: self.client = MongoClient(db, port, maxPoolSize=mps, username=user, password=pw, connectTimeoutMS=to) print 'OK' except pymongo.errors.ConnectionFailure, e: print 'ERROR' logging.error("Connection problem: %s", e) # Search checks in MongoDB def search(self): collections = ['new', 'old'] try: for data_type in collections: db = self.client.get_database('db') collection = db[data_type + '_data'] print 'Opening ' + data_type + '_data DB ...... ', cursor = collection.find({}) print 'OK' writeTempData(cursor, data_type) except Exception as e: print 'ERROR' logging.error("Unable find data in DB: %s", e) if __name__ == '__main__': # Get json from MongoDB mongo = Mongo() mongo.search() Output: root@pc:/etc/checkPlantillas# python getPlantillas.py Creating MongoClient... Establishing connection with MongoDB ...... OK Opening new_data DB ...... OK What am I doing wrong? Thanks beforehand, mike.
has comment: http://stackoverflow.com/comment/85763712
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85763648
upvote count: 1
score: 1

http://stackoverflow.com/a/49396539
accepted answer of: http://stackoverflow.com/q/49396415
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49396415
downvote count: 0
type: AcceptedAnswer
has body: By defining a height and a width for the canvas and using pack() instead of grid() (like so) from tkinter import * import random class draw(): def __init__(self, can, start_x, start_y, size): self.can = can self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red") self.can.tag_bind(self.id, "&lt;ButtonPress-1&gt;", self.set_color) self.color_change = True def set_color(self,event = None): self.color_change = not self.color_change colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"] self.can.itemconfigure(self.id, fill = random.choice(colors)) WIDTH = 400 #change as needed HEIGHT = 500 #change as needed root = Tk() canvas = Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() square = draw(canvas,WIDTH/2,HEIGHT/2,10) root.mainloop() You can center the rectangle
type: Answer

http://stackoverflow.com/a/49293872
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85592443
has comment: http://stackoverflow.com/comment/127300227
accepted answer of: http://stackoverflow.com/q/49283435
upvote count: 3
has body: You are not missing anything. I can help you since I have worked on several sequence-to-sequence application using PyTorch. I am giving you a simple example below. class Seq2Seq(nn.Module): """A Seq2seq network trained on predicting the next query.""" def __init__(self, dictionary, embedding_index, args): super(Seq2Seq, self).__init__() self.config = args self.num_directions = 2 if self.config.bidirection else 1 self.embedding = EmbeddingLayer(len(dictionary), self.config) self.embedding.init_embedding_weights(dictionary, embedding_index, self.config.emsize) self.encoder = Encoder(self.config.emsize, self.config.nhid_enc, self.config.bidirection, self.config) self.decoder = Decoder(self.config.emsize, self.config.nhid_enc * self.num_directions, len(dictionary), self.config) @staticmethod def compute_decoding_loss(logits, target, seq_idx, length): losses = -torch.gather(logits, dim=1, index=target.unsqueeze(1)).squeeze() mask = helper.mask(length, seq_idx) # mask: batch x 1 losses = losses * mask.float() num_non_zero_elem = torch.nonzero(mask.data).size() if not num_non_zero_elem: return losses.sum(), 0 if not num_non_zero_elem else losses.sum(), num_non_zero_elem[0] def forward(self, q1_var, q1_len, q2_var, q2_len): # encode the query embedded_q1 = self.embedding(q1_var) encoded_q1, hidden = self.encoder(embedded_q1, q1_len) if self.config.bidirection: if self.config.model == 'LSTM': h_t, c_t = hidden[0][-2:], hidden[1][-2:] decoder_hidden = torch.cat((h_t[0].unsqueeze(0), h_t[1].unsqueeze(0)), 2), torch.cat( (c_t[0].unsqueeze(0), c_t[1].unsqueeze(0)), 2) else: h_t = hidden[0][-2:] decoder_hidden = torch.cat((h_t[0].unsqueeze(0), h_t[1].unsqueeze(0)), 2) else: if self.config.model == 'LSTM': decoder_hidden = hidden[0][-1], hidden[1][-1] else: decoder_hidden = hidden[-1] decoding_loss, total_local_decoding_loss_element = 0, 0 for idx in range(q2_var.size(1) - 1): input_variable = q2_var[:, idx] embedded_decoder_input = self.embedding(input_variable).unsqueeze(1) deco…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49283435

http://stackoverflow.com/a/49407292
type: Answer
accepted answer of: http://stackoverflow.com/q/49405831
type: AcceptedAnswer
has body: Another way of doing it would be to utilize csv module. (Note that in your dictionary you have an upper case C which I corrected in my code below): import csv lookup = {'ge60le90': 'confidence&lt;90','gt90': 'confidence&gt;90', 'lt60': 'confidence&lt;60'} count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} } # Getting keys from dictionary that match them with titles below. rowKeys = [k for k in count['lt60'].keys()] titles = [['relation type'] + list(lookup[k] for k in count.keys())] # Getting all row variable values for every title. rows = [[count[k][i] for k in count.keys()] for i in rowKeys] # Concatenating variables and values. fields = [[rowKeys[i]] + rows[i] for i in range(len(rowKeys))] # Concatenating final output to be written to file. result = titles + fields print("Final result to be written: ") for r in result: print(r) # Writing to file. with open("output.csv", "w", newline="") as outFile: writer = csv.writer(outFile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerows(result) Note that the ; delimiter works for European Windows and might not work for you. In this case, use , instead.
score: 0
has comment: http://stackoverflow.com/comment/85817639
answers question: http://stackoverflow.com/q/49405831

http://stackoverflow.com/comment/85835679
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49403839
score: 0
has text: Maybe a stupid question..: Do you have the 64 bit or 32bit Python version installed?

http://stackoverflow.com/comment/85849477
type: QuestionComment
has text: I ran it in terminal, with htop running in second terminal with filter on python turned on (you can turn it on with F4). As soon as threads joined, they disappeared from htop. I am on Linux.
comment on: http://stackoverflow.com/q/49409828
score: 0
type: Comment

http://stackoverflow.com/comment/85661754
score: 0
type: Comment
has text: @CharlesChen now I'm getting "Using fallback coder for typehint: Dict[unicode, Any]." Any example of my dictionary is {'a': 'a', 'b': 5.0}. I'll try changing the Dict[unicode, Any] to Dict[str, Any] and Dict[Any, Any]
type: QuestionComment
comment on: http://stackoverflow.com/q/49324635

http://stackoverflow.com/q/49424455
has title: Dask assigning to dataframe column by index throws ValueError
tagged with: dask-distributed
has comment: http://stackoverflow.com/comment/127919854
favorite count: 0
type: Question
tagged with: dask
upvote count: 5
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have a pipeline of trasnformations on a grouped by dataframe. All functions get a DataframeGroupBy and compute some features. Those features are then stored in a Dataframe. The index of the dataframe is the same since all features are derived by the same DataFrameGroupBy object. Function looks like this: def function(group_by_df, features_df=None): # actions to perform to group_by_df e.g feature_max = group_by_df.column.max() # This is a series object with index the same as group_by_df if features_df is not None: features_df['feature_name'] = feature_max else: features_df = feature_max.to_frame(name='feature_name') return features_df So since this is itterative, the first time features_df is none so the dataframe is created. Then when all the other iterations are executed feature_df has the columns with all the previous features. In one step when trying to assign a series produced by group_by_df to the feature_df I get the following error: ValueError: Not all divisions are known, can't align partitions. Please use `set_index` to set the index. The strange part is that running the following code: featues_pandas = features_df.compute() feature_series_with_issue_pandas = feature_series_with_issue_pandas.compute() features_pandas['feature_name'] = feature_series_with_issue_pandas works. That is isolating the failing feature and trying to assign it to the so far created dataframe but in the pandas side, it works. Could I be doing something wrong? Adding a MCVE: raw_data = pd.DataFrame({'username':list('ab')*10, 'user_agent': list('cdef')*5, 'method':['POST'] * 20, 'dst_port':[80]*20, 'dst':['1.1.1.1']*20}) past = pd.DataFrame({'user_agent':list('cde'), 'percent':[0,3, 0.3, 0.4]}) dask_raw = dd.from_pandas(raw_data, npartitions=4) dask_past = dd.from_pandas(past, npartitions=4) dask_past = dask_past.set_index('user_agent') merged_raw = dask_raw.merge(dask_past, how='left', left_on='user_agent', right_index=True) grouped_by_df = merged_raw.groupby(['username', 'dst', 'ds…
score: 5
downvote count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49437868
downvote count: 1
has comment: http://stackoverflow.com/comment/85877953
has answer: http://stackoverflow.com/a/49437937
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85878306
possible better answer: http://stackoverflow.com/a/49479349
tagged with: bioinformatics
has answer: http://stackoverflow.com/a/49479349
tagged with: python
has comment: http://stackoverflow.com/comment/85878330
favorite count: 0
has comment: http://stackoverflow.com/comment/85877765
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85877811
has title: use dictionary comprehension to iterate over a list of list
upvote count: 1
accepted answer: http://stackoverflow.com/a/49437937
has body: what is the correct syntax for doing a list comprehension over a list of list? I am using a dict. comprehensions to convert one value to another in a list of list, but I cant get it to do the entire list of lists. Here is what I have: v_list = [['A'], ['V']] test = {codon for (codon,AA) in translation.items() for aa in v_list if AA == aa} This line of code works if v_list is just a normal list, but I need to keep the letters in separate lists within the list. Using v_list[0][0] works, but I need a solution that automatically iterates over all lists in list and not just ones I hard-code into the program. Thanks! EDIT Sorry for the confusion with this question. my dictionary looks something like this: translation = {'TTT': 'F', 'TCT': 'S', 'TAT': 'Y', 'TGT': 'C', 'TTC': 'F', 'TCC': 'S', 'TAC': 'Y', 'TGC': 'C', 'TTA': 'L'} and my inputs look like this: in = [['S'],['F']] so I wanted to pull all the 'S' into in[0][0] and all the 'F's into in[1][1]. But 'in' is of unknown length, something the user enters as a parsed object. So my output would hopefully look like this: out = [['TCT', 'TCC'], ['TTT', 'TTC']] Thanks for the help.

http://stackoverflow.com/comment/86277183
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49631900
score: 0
has text: @Jean-FrançoisFabre - i add second variant of code (with event completion). may be it will be even more simply for you. however this not change main idea. only bit different thin implementation details. anyway both variants will be ok, of fail at the same place

http://stackoverflow.com/q/49298254
has body: I wrote a simple python script to make a request to this website http://www.lagado.com/proxy-test using the requests module. This website essentially tells you whether the request is using a proxy or not. According to the website, the request is not going through a proxy and is in fact going through my IP address. Here is the code: proxiesLocal = { 'https': proxy } headers = RandomHeaders.LoadHeader() url = "http://www.lagado.com/proxy-test" res = '' while (res == ''): try: res = requests.get(url, headers=headers, proxies=proxiesLocal) proxyTest = bs4.BeautifulSoup(res.text, "lxml") items = proxyTest.find_all("p") print(len(items)) for item in items: print(item.text) quit() except: print('sleeping') time.sleep(5) continue Assuming that proxy is a variable of type string that stores the address of the proxy, what am I doing wrong?
score: 1
tagged with: python
type: Question
answer count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85599340
downvote count: 0
tagged with: python-requests
has title: Python request not using proxy
favorite count: 0
tagged with: proxy
has comment: http://stackoverflow.com/comment/85599134

http://stackoverflow.com/comment/85731001
comment on: http://stackoverflow.com/q/49352731
score: 0
has text: what is your os, windows?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/114753081
has text: Should probably select an answer...
comment on: http://stackoverflow.com/q/49380572
type: Comment
type: QuestionComment
score: 1

eval
tag name: eval
tags question: http://stackoverflow.com/q/49415176
type: Tag
tags question: http://stackoverflow.com/q/49393692

http://stackoverflow.com/comment/85794802
score: 0
has text: Usually, no. For changes to take effect in a typical production deployment, you usually have to restart the webserver service or WSGI server (depending on the deploymnet methods). Files should only get automatically reloaded in a development environment when the DEBUG flag is set to true.
type: QuestionComment
comment on: http://stackoverflow.com/q/49396485
type: Comment

http://stackoverflow.com/q/49285718
downvote count: 0
has comment: http://stackoverflow.com/comment/85574280
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85574901
type: Question
type: UnansweredQuestion
tagged with: python
has title: Bucket Multiple Columns in Pandas Based on Top N Values
tagged with: pandas
has answer: http://stackoverflow.com/a/49286300
score: 1
has body: I would like to iterate through multiple dataframe columns looking for the top n values in each column. If the value in the column is in the top n values then keep that value, otherwise bucket in "other". Also, I would like to create new columns from this. However, I'm not sure how to use .apply in this case as it seems like I need to reference both columns and rows. np.random.seed(0) example_df = pd.DataFrame(np.random.randint(low=0, high=10, size=(15, 5)),columns=['a', 'b', 'c', 'd', 'e']) cols_to_group = ['a','b','c'] top = 2 So for the example below, here's my pseudo code that I'm not sure how to execute: Pseudo Code: #loop through each column for column in example_df[cols_to_group]: #loop through each value in column and check if it's in top values for the column. for single_value in column: if single_value.isin(column.value_counts()[:top].values): #return value if it is in top values return single_value else: return "other" #create new column in your df that has bucketed values example_df[column.name + str("bucketed")+ str(top)]=column Expected output: Crude example where top = 2. a b c d e a_bucketed b_bucketed 0 4 6 4 3 1 4 6 1 8 8 1 5 7 8 8 2 8 6 0 0 2 8 6 3 4 1 0 7 4 4 Other 4 7 8 7 7 7 Other 8
has comment: http://stackoverflow.com/comment/85575121
answer count: 1

http://stackoverflow.com/q/49412465
tagged with: python-3.x
has body: How can I get the value of list code elements? def test(argu): print(argu) code = [5,10,15] length =len(code) for i in range(0,length): test("code[%d]" %i) Expected output: 5 10 15 Acutal output: code[0] code[1] code[2]
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/49412541
tagged with: python
has comment: http://stackoverflow.com/comment/85826760
has comment: http://stackoverflow.com/comment/85826943
score: -3
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49412541
has title: Passing variable value as function argument
accepted answer: http://stackoverflow.com/a/49412538
downvote count: 3
duplicate of: http://stackoverflow.com/q/3019909
has answer: http://stackoverflow.com/a/49412538
favorite count: 0
linked to: http://stackoverflow.com/q/3019909
type: Question

http://stackoverflow.com/q/49378851
linked to: http://stackoverflow.com/q/9189172
has comment: http://stackoverflow.com/comment/85758403
answer count: 2
upvote count: 1
type: UnansweredQuestion
score: -3
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49378858
has title: Facing issue while replacing string of a file in Python
has comment: http://stackoverflow.com/comment/85801464
tagged with: python
has answer: http://stackoverflow.com/a/49378874
has body: Here is my code snippet. What am I doing wrong? Not able to replace the string. f = open("template.html", "r") lines = f.read() string = ''' High ''' if string in lines: print lines lines.replace(" ", " ") print lines
downvote count: 4
has comment: http://stackoverflow.com/comment/85758274

http://stackoverflow.com/a/49330233
accepted answer of: http://stackoverflow.com/q/49330219
upvote count: 4
has comment: http://stackoverflow.com/comment/85666044
type: AcceptedAnswer
downvote count: 0
has body: Your code should be removing two existing elements and adding a new one to your list. Or at least, remove the first element. I don't see you removing anything... just re-assigning. Option 1 You can do this quite succinctly using pop + append: while len(d) &gt; 1: d.append(d.pop() + d.pop(0)) print(d) [1, 1, 2] [1, 3] [4] Option 2 Alternatively, with a single pop operation. This should be pretty efficient. while len(d) &gt; 1: d[-1] += d.pop(0) print(d) [1, 1, 2] [1, 3] [4]
type: Answer
answers question: http://stackoverflow.com/q/49330219
score: 4

http://stackoverflow.com/q/49303319
has answer: http://stackoverflow.com/a/49303701
score: 1
has comment: http://stackoverflow.com/comment/85608945
has comment: http://stackoverflow.com/comment/85608985
has comment: http://stackoverflow.com/comment/85610047
has title: Getting empty list after initialization
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85608684
has comment: http://stackoverflow.com/comment/85609924
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85610381
has body: I am a beginner with Python and I have a problem with the classes of my project. So the structure is as follows: main.py (Firstly, main creates world instance) from world import World world = World() World knows everything about all other classes (imports everything as needed) and initializes previously empty lists from inherited class PersonAttributes (where "global" variables are stored so that all classes can access them) with content. PersonAttributes class PersonAttributes: MALE_NAMES = [] FEMALE_NAMES = [] SURNAMES = [] PROFESSIONS = [] BABY = None CHILD = None TEEN = None YOUNGADULT = None ADULT = None SENIOR = None LIFESTAGES = (BABY, CHILD, TEEN, YOUNGADULT, ADULT, SENIOR) World from utilities.person_attributes import PersonAttributes from life_stage import Baby, Child, Teen, YoungAdult, Adult, Senior class World(PersonAttributes): def __init__(self): # Initialize names from files self.MALE_NAMES = self.get_male_names() self.FEMALE_NAMES = self.get_female_names() self.SURNAMES = self.get_surnames() self.PROFESSIONS = self.get_professions() # Initialize life stages self.BABY = Baby(None, None, None, None) self.CHILD = Child(None, None, None, None) self.TEEN = Teen(None, None, None, None) self.YOUNGADULT = YoungAdult(None, None, None, None) self.ADULT = Adult(None, None, None, None) self.SENIOR = Senior(None, None, None, None) self.population = [] self.populate_world() World also imports LifeStage class which contain different classes that inherit from Person. Example of YoungAdult (where the problem is) class YoungAdult(Person): def __init__() self.occupation = Randomizer().get_random_list_item(self.PROFESSIONS) person from utilities.person_attributes import PersonAttributes class Person(PersonAttributes): def __init__(): super(Person, self).__init__() So the problem is self.PROFESSIONS. I have initialized it in world, but then when I instantiate YoungAdult, (self.YOUNGADULT = YoungAdult(None, None, None, None)), the PROFESSIONS list from PersonAttributes is…
has comment: http://stackoverflow.com/comment/85611253
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85609936
favorite count: 0
accepted answer: http://stackoverflow.com/a/49303701
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85609940

http://stackoverflow.com/q/49377662
has comment: http://stackoverflow.com/comment/85756043
score: -1
has answer: http://stackoverflow.com/a/49377907
has comment: http://stackoverflow.com/comment/85756399
has comment: http://stackoverflow.com/comment/85756299
has comment: http://stackoverflow.com/comment/85756453
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85756046
answer count: 2
has comment: http://stackoverflow.com/comment/85756486
has comment: http://stackoverflow.com/comment/85756134
upvote count: 0
type: UnansweredQuestion
has body: I am new to Python. Working with 2.7 for class. The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console. The issue I am running into is in my third function replace_name, the parameters are the list of lists, old name, new name. However, I am getting NameError:'word_list' is not defined I understand that if a variable is not defined in the Main then it is local to its function. I thought though, that by using return in the function that that information is stored to be used by subsequent functions. Am I wrong? def new_name(): #prompts for user's name. checks if input is valid while True: name = raw_input("Please enter your name.\n") if len(name) &lt; 1: print "Invalid, please enter your name.\n" else: return name def orig_script():#reads in script, splits into list of lists word_list = [] script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n") if len(script) &lt; 1: print "Empty text field. Please try again.\n" while script != 'done':#splits string input,adds to list words = script.split() word_list.append(words) script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ") if len(script) &lt; 1: print "Empty text field. Please try again.\n" return word_list def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes. new_list = [] for sentences in range(word_list): sentence = word_list[sentences] for words in range(sentece): word = sentence[words] if word == old_name: sentence[words] == new_name new_list.append(sentence) print new_list#debugging-change to return new_name() orig_script() replace_name(word_list, Robin, new_name) If my indentation is a bit off here, I apologize. I tried to correct it from the copy/paste. There are no indentation errors given…
tagged with: python
has comment: http://stackoverflow.com/comment/85756226
downvote count: 1
has title: List as function parameter returning NameError: not defined
has comment: http://stackoverflow.com/comment/85756206
has comment: http://stackoverflow.com/comment/85756275
has answer: http://stackoverflow.com/a/49377834
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85756208

http://stackoverflow.com/a/49433343
upvote count: 10
score: 10
has comment: http://stackoverflow.com/comment/121170299
has comment: http://stackoverflow.com/comment/85897106
type: AcceptedAnswer
has body: There are various ways to select nodes based on their attributes. Here is how to do it with get_node_attributes and a list comprehension to take the subset. The drawing functions then accept a nodelist argument. It should be easy enough to extend to a broader set of conditions or modify the appearance of each subset as suits your needs based on this approach import networkx as nx # define a graph, some nodes with a "Type" attribute, some without. G = nx.Graph() G.add_nodes_from([1,2,3], Type='MASTER') G.add_nodes_from([4,5], Type='DOC') G.add_nodes_from([6]) # extract nodes with specific setting of the attribute master_nodes = [n for (n,ty) in \ nx.get_node_attributes(G,'Type').iteritems() if ty == 'MASTER'] doc_nodes = [n for (n,ty) in \ nx.get_node_attributes(G,'Type').iteritems() if ty == 'DOC'] # and find all the remaining nodes. other_nodes = list(set(G.nodes()) - set(master_nodes) - set(doc_nodes)) # now draw them in subsets using the `nodelist` arg pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \ node_color='red', node_shape='o') nx.draw_networkx_nodes(G, pos, nodelist=doc_nodes, \ node_color='blue', node_shape='o') nx.draw_networkx_nodes(G, pos, nodelist=other_nodes, \ node_color='purple', node_shape='s')
type: Answer
answers question: http://stackoverflow.com/q/49428588
accepted answer of: http://stackoverflow.com/q/49428588
downvote count: 0

http://stackoverflow.com/comment/85709686
type: Comment
type: QuestionComment
has text: How do you exit your application?
score: 0
comment on: http://stackoverflow.com/q/49353923

http://stackoverflow.com/comment/85795143
comment on: http://stackoverflow.com/a/49378077
has text: @desertnaut Seems like this is an answer to the question.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49396670
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85796329
has title: Hyperlink embedded in http request
has answer: http://stackoverflow.com/a/49397268
tagged with: python-jira
has comment: http://stackoverflow.com/comment/85795414
score: 0
answer count: 1
type: Question
has body: I'm using the jira-python client to add a comment to an issue: issue_id = 'SB-196' comment = 'A Slack channel has been created for discussing this escalation: slack://channel?id={}&amp;team={}'.format(new_channel_id, SLACK_TEAM_ID) jira.comment(issue_id, comment) The jira-python client is just a wrapper around the JIRA rest api. When I execute the code, I get a 404 error from JIRA which is recieving the following URL: https://jira.mycompany.com/rest/api/2/issue/SB-196/comment/A%20Slack%20channel%20has%20been%20created%20for%20discussing%20this%20escalation:%0Aslack://channel?id=C123456&amp;team=T123456 I'm assuming this is happening because it's trying to encode the Slack URL in the REST URL and getting confused. What's the correct way to encode the including URL so it doesn't get confused? Thanks!
tagged with: rest

http://stackoverflow.com/comment/85604769
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49301479
has text: As far as I can tell, the nth() condition

http://stackoverflow.com/q/49397761
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85853083
has title: Python - loop over intersection between shapefiles
tagged with: arcpy
tagged with: intersection
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49671850
upvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I need to write a loop (in arcpy) for 10 climate files with respect to 1 census area file. Thus, I need 10 intersections. I have problems with the syntax when it comes to naming the output files: I get ERROR 00800. I know this is related to concatenation, and might be easy for many of you. It's been a while since I coded in Python. Find my code below, I appreciate your help output2 = "" shapes_input =["RCP4_2040_1", "RCP4_2040_2"] for shapes in shapes_input: output = shapes + "_AU" output2 = '"' + output + '"' arcpy.Intersect_analysis(shapes, "AKLmbAU2013", output2)

http://stackoverflow.com/comment/85726440
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167088/discussion-between-sangeetha-sivakumar-and-jezrael).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49359884

http://stackoverflow.com/a/49414987
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85834531
answers question: http://stackoverflow.com/q/49414693
type: Answer
has comment: http://stackoverflow.com/comment/85831687
accepted answer of: http://stackoverflow.com/q/49414693
has body: The answer is "No" - a different workbook means a different file. Create a new writer object, which you define via pandas.ExcelWriter. Point it to another Excel file and apply df.to_excel(writer2, sheetname='X') to that one, with a sheetname of your choice. This is a useful tutorial: Working with Python Pandas and XlsxWriter
has comment: http://stackoverflow.com/comment/85831653

http://stackoverflow.com/comment/85628938
type: QuestionComment
has text: hahaha, so weird way to show that the drag works, my screen is small so I can not see that item 3, 3 changed text, the most natural thing would be if I drag the item i, j to p, q copy the text, and to prove that in your code did not work so I concluded that.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49306741

http://stackoverflow.com/comment/85680612
type: Comment
type: QuestionComment
score: 1
has text: @PeterWood: sure, but that'll not help them know why this attempt didn't work. There is value in creating your own.
comment on: http://stackoverflow.com/q/49340174

wand
tags question: http://stackoverflow.com/q/49380884
type: Tag
tag name: wand

http://stackoverflow.com/comment/85870161
type: QuestionComment
comment on: http://stackoverflow.com/q/49433979
score: 2
has text: Note, **all** objects have exactly the same behavior in Python, what you are referring to as being "only a pointer". You should read https://nedbatchelder.com/text/names.html. Note, Python does not support truly global variables, only module global variables. but you can import the module and modify the module namespace and this can simulate real global variables.
type: Comment

http://stackoverflow.com/comment/85894044
type: AnswerComment
has text: I'm sorry, I'm confused. So now I have a data set from MySQL in Python memory and can compare it? Is it possible to compare the items without extraction to Python? this is too big...
type: Comment
comment on: http://stackoverflow.com/a/49438113
score: 0

http://stackoverflow.com/comment/85913611
type: Comment
comment on: http://stackoverflow.com/q/49286741
score: 0
type: QuestionComment
has text: I have the same problem with python 3.6.

http://stackoverflow.com/comment/85755885
comment on: http://stackoverflow.com/a/49377321
type: Comment
score: 0
type: AnswerComment
has text: Yes, I posted them. I think cloud speech might only be able to transcribe audio that is encoded as LINEAR16 because that is the encoding specified in function.

http://stackoverflow.com/a/49417252
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49417191
has body: First thing first, don't override python's globals. Python provides a max function by default. def max_number(list): max_element = list[0] for i in range(1, len(list)): if list[i] &gt; max_element: max_element = list[i] return max_element print(max_number([1, 2, 8, 4])) You can't just use a variable not in your scope, max_element variable is only available in your max_element function's scope, to actually retrieve the value, you need to return it.
answers question: http://stackoverflow.com/q/49417191
has comment: http://stackoverflow.com/comment/85836415
type: Answer
has comment: http://stackoverflow.com/comment/85836369
score: 0
upvote count: 1

http://stackoverflow.com/comment/96346718
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49358682
type: AnswerComment
has text: @voidvector thanks so much! I'm glad to learn this is documented behaviour - I added this to the answer.

youtube
tags question: http://stackoverflow.com/q/49354232
type: Tag
tag name: youtube

http://stackoverflow.com/comment/85702062
type: QuestionComment
comment on: http://stackoverflow.com/q/49350988
has text: Possible duplicate of [I can "pickle local objects" if I use a derived class?](https://stackoverflow.com/questions/36994839/i-can-pickle-local-objects-if-i-use-a-derived-class)
score: 0
type: Comment

http://stackoverflow.com/q/49417041
has answer: http://stackoverflow.com/a/49419451
accepted answer: http://stackoverflow.com/a/49419451
tagged with: sockets
has body: I'm working on a program that receives data from a socket, and when a signal is sent, I want to be able to break from the receive. What I have now: class Killer: die = False def __init__(self): signal.signal(signal.SIGINT, self.terminate) signal.signal(signal.SIGTERM, self.terminate) def terminate(self, signum, frame): print ("caught " + str(signum)) self.die = True; sock = socket.socket() # Generic socket setup while (~killer.die): #generic data setup sock.receive(data) sock.shutdown(socket.SHUT_RDWR) When the interrupt is caught, it prints and then goes back into waiting. Is there a way to break from the receive on receiving a signal?
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
has title: Python break from socket receive on SIGINT
tagged with: signal-handling
favorite count: 0
type: Question

http://stackoverflow.com/a/49360991
has comment: http://stackoverflow.com/comment/85722054
has comment: http://stackoverflow.com/comment/85722111
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49360921
has body: That is perfectly normal. c is a generator that will iterate over all elements of b, so it will iterate over b only once. That is when you call writer.writerows(c). After that, the generator is depleted so making a list out of it will return an empty list.
type: Answer

http://stackoverflow.com/a/49304885
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/49303997
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49303997
has body: I determined there were 2 issues. As BDL mentioned the glEnableVertexAttribArray was not setup appropriately. It needed an index and not a vertex array object. The glBufferData size was incorrect as the size needed to be provided in bytes. A quick search online revealed that (numpy.size * numpy.itemsize) returns the size of the array. With these 2 things done... I have a triangle.
type: AcceptedAnswer

http://stackoverflow.com/comment/85579980
score: 0
type: QuestionComment
has text: yes I do both of them, but I have to restart the program to see the optionmenu updated with the new data, I need to refresh its display, it is already being updated when i add data to db , but need to restart the GUI to see it changed for user
type: Comment
comment on: http://stackoverflow.com/q/49288164

gpu
tags question: http://stackoverflow.com/q/49374427
tags question: http://stackoverflow.com/q/49391386
tag name: gpu
tags question: http://stackoverflow.com/q/49386650
type: Tag
tags question: http://stackoverflow.com/q/49352528
tags question: http://stackoverflow.com/q/49282546
tags question: http://stackoverflow.com/q/49427766

http://stackoverflow.com/q/49398152
has body: We are trying our luck with robot framework for tests. Automation. I am stuck at database connection at this point. A DB connection using cx_Oracle is displaying an error saying “ No keyword withy the name cx_Oracle’ . If you have any idea please help . It will be helpful if you could put out an example of the Oracle dB connection sample.
has comment: http://stackoverflow.com/comment/85799056
downvote count: 1
favorite count: 0
type: Question
tagged with: robotframework
answer count: 5
type: UnansweredQuestion
tagged with: oracle-database
has answer: http://stackoverflow.com/a/49413090
tagged with: python
has comment: http://stackoverflow.com/comment/85843457
has answer: http://stackoverflow.com/a/49454835
has title: Robot Framework : how to connect to Oracle database
has comment: http://stackoverflow.com/comment/85812477
has answer: http://stackoverflow.com/a/71362775
score: 0
has answer: http://stackoverflow.com/a/49469043
has answer: http://stackoverflow.com/a/54253203
upvote count: 1

cross-entropy
tags question: http://stackoverflow.com/q/49377483
tag name: cross-entropy
type: Tag
tags question: http://stackoverflow.com/q/49332994

http://stackoverflow.com/a/49419267
has body: You're seeing this behavior because of the two infinite while loops enclosing to your isQuit variable. breaking out of a loop only stops the immediately enclosing loop. One possible solution is to immediately return when isQuit is "yes", which will exit the entire order() function. # ... isQuit = input("Do you want to quit: yes / no:") if isQuit == "yes": return Another possible solution is to remove the outer infinite while loop since it does not seem to serve any function.
accepted answer of: http://stackoverflow.com/q/49419243
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85840093
answers question: http://stackoverflow.com/q/49419243
has comment: http://stackoverflow.com/comment/85840175
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85840075
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85840185

http://stackoverflow.com/q/49329079
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85660945
answer count: 1
has body: I was trying to upload a library of mine to pypi when this error occured: Traceback (most recent call last): File "setup.py", line 44, in <module> keywords=['producti-gestio', 'python', 'api', 'rest'], File "/usr/lib/python3.6/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.6/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/lib/python3.6/distutils/command/upload.py", line 64, in run self.upload_file(command, pyversion, filename) File "/usr/lib/python3.6/distutils/command/upload.py", line 158, in upload_file value = valve[1] IndexError: tuple index out of range I don't know what went wrong and what value the IndexError is referring to. setup.py: from distutils.core import setup url = '.../producti-gestio/archive/v0.3.0.tar.gz', setup( name='producti_gestio', packages=['producti_gestio', 'producti_gestio.core', 'producti_gestio.decorator', 'producti_gestio.project', 'producti_gestio.server', 'producti_gestio.utils'], version='0.3.0', description='A new simple web server', url='.../producti-gestio', download_url=url, scripts=['bin/producti-gestio'], keywords=['producti-gestio', 'python', 'api', 'rest'], ) Can you help me? Thank you.
has answer: http://stackoverflow.com/a/49329774
favorite count: 0
has comment: http://stackoverflow.com/comment/85660614
type: Question
tagged with: setup.py
tagged with: pip
tagged with: python
accepted answer: http://stackoverflow.com/a/49329774
type: AnsweredQuestion
tagged with: installation
has title: distutils IndexError: tuple index out of range
downvote count: 0

http://stackoverflow.com/a/49390077
accepted answer of: http://stackoverflow.com/q/49389930
answers question: http://stackoverflow.com/q/49389930
downvote count: 0
score: 1
type: Answer
has body: As the documentation says, the API key needs to go in your URL, not in the body of the request. E.g. url = 'https://url.api-us1.com/admin/api.php?api_action=address_list&amp;api_key' + api_key
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49393131
has comment: http://stackoverflow.com/comment/85788438
upvote count: 5
has comment: http://stackoverflow.com/comment/85787967
type: Answer
accepted answer of: http://stackoverflow.com/q/49393057
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85788564
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85788515
has body: The error handler should be a callable. It will be called with one argument, the exception instance. def walk_error_handler(exception_instance): print("uh-oh!") # you probably want to do something more substantial here.. for root, dirs, files in os.walk(dirname, onerror=walk_error_handler): ... os.walk ignoring errors by default is by design. This allows the walk to continue to traverse other directories even after, for example, one subdirectory encountered in the walk could not be listed due to insufficient permissions. When handling the exception instance, all the information you are interested in is likely contained in the exception_instance.args and the type(exception_instance). Since it's an OSError (or a subtype), the errno will be a useful attribute. You can make comparisons against the constants of the stdlib errno module. For example, permission denied is errno.EACCES (13). That's the error you'd get if you tried to list /root as a normal user.
answers question: http://stackoverflow.com/q/49393057

http://stackoverflow.com/a/49312700
type: Answer
has comment: http://stackoverflow.com/comment/85627320
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49312650
has body: Seems like you need df_dummy.set_index('day_of_week').births.sum(level=0).to_dict() Out[30]: {1: 45121, 2: 324, 3: 3498, 4: 84804, 5: 34885, 6: 30827, 7: 8923}
downvote count: 0
answers question: http://stackoverflow.com/q/49312650
type: AcceptedAnswer

http://stackoverflow.com/comment/85611241
comment on: http://stackoverflow.com/q/49304496
has text: Have you tried just normalizing the values to be within the range for 0 to 0.05, etc. ? x' = 0 + ((x - xmin)(0.05 - 0))/(xmax - xmin)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49401795
has title: how to make this code to become module
has comment: http://stackoverflow.com/comment/85805309
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85808244
upvote count: 0
answer count: 1
score: -7
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85805144
accepted answer: http://stackoverflow.com/a/49633823
linked to: http://stackoverflow.com/q/15746675
has comment: http://stackoverflow.com/comment/85814656
has comment: http://stackoverflow.com/comment/85805903
has comment: http://stackoverflow.com/comment/85805314
tagged with: python-module
has body: This is the Python code code import os import base64 from io import BytesIO from flask import Flask, render_template, redirect, url_for, flash, session, \ abort from werkzeug.security import generate_password_hash, check_password_hash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, logout_user, \ current_user from flask_bootstrap import Bootstrap from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import Required, Length, EqualTo import onetimepass import pyqrcode # create application instance app = Flask(__name__) app.config.from_object('config') # initialize extensions bootstrap = Bootstrap(app) db = SQLAlchemy(app) lm = LoginManager(app) class User(UserMixin, db.Model): """User model.""" __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True) password_hash = db.Column(db.String(128)) otp_secret = db.Column(db.String(16)) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.otp_secret is None: # generate a random secret self.otp_secret = base64.b32encode(os.urandom(10)).decode('utf-8') @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def get_totp_uri(self): return 'otpauth://totp/2FA-Demo:{0}?secret={1}&amp;issuer=2FA-Demo' \ .format(self.username, self.otp_secret) def verify_totp(self, token): return onetimepass.valid_totp(token, self.otp_secret) @lm.user_loader def load_user(user_id): """User loader callback for Flask-Login.""" return User.query.get(int(user_id)) class RegisterForm(FlaskForm): """Registration form.""" username = StringField('Username', validators=[Required(), Length(1, 64)]) password = PasswordField('Password', valid…
tagged with: python
has answer: http://stackoverflow.com/a/49633823
has comment: http://stackoverflow.com/comment/85804826
has comment: http://stackoverflow.com/comment/85806316

http://stackoverflow.com/comment/85729488
has text: Or even `np.array(arr).astype(float)`.
comment on: http://stackoverflow.com/q/49364432
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49386293
upvote count: 1
has title: Python. Graphics.
answer count: 1
has answer: http://stackoverflow.com/a/49386542
score: -1
has body: I want to know about the option of the values for the "yview" command of GraphWin and a complete documentation of this package. I'm using Python 3.6.4 version. Thanks and regards Gonzalo
favorite count: 0
type: Question
tagged with: graphics
type: UnansweredQuestion
tagged with: package
linked to: http://stackoverflow.com/q/39084403
tagged with: python
downvote count: 2
has comment: http://stackoverflow.com/comment/96563198

http://stackoverflow.com/comment/86007554
type: AnswerComment
type: Comment
has text: Sorry, I don't know about the insert speed. It was a suggestion for the reading side mostly :(
score: 0
comment on: http://stackoverflow.com/a/49472227

http://stackoverflow.com/a/49301581
has body: model.compile does not take an epochs parameter. Only fit and fit_generator do.
has comment: http://stackoverflow.com/comment/108714758
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49301203
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49301203
score: 2

http://stackoverflow.com/comment/85877455
type: Comment
has text: –1 You have *very* old version of Python!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49437755

http://stackoverflow.com/comment/85747028
has text: ok I'll try to remove a lot of it to get to a point where it can be reproduced
comment on: http://stackoverflow.com/q/49372825
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85614287
type: QuestionComment
comment on: http://stackoverflow.com/q/49301563
has text: First guess: look into `read_group()`
score: 0
type: Comment

http://stackoverflow.com/comment/85623819
comment on: http://stackoverflow.com/a/49287082
score: 0
has text: @StrikeX I would definitely be happy to answer, but please ask this in another question. This is going well beyond what you originally intended.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49359474
has comment: http://stackoverflow.com/comment/85719281
tagged with: list
downvote count: 0
linked to: http://stackoverflow.com/q/14313510
has answer: http://stackoverflow.com/a/49360136
type: UnansweredQuestion
score: 4
has comment: http://stackoverflow.com/comment/85719050
has answer: http://stackoverflow.com/a/49359731
favorite count: 0
type: Question
has body: Is there any easy way to find out what's the trend of the list? For example: [5.0, 6.0, 9.0, 4.0, 10.0]. On the whole, its elements are increasing over time. [6.0, 4.0, 5.0, 4.0, 3.0]. Its elements are decreasing over time. Ideally, I want a Boolean result from these kinds of lists. Actually, I'd like to know the trend of a collection of data. not linear increasing or exactly increasing one by one. In the real world, some data not always good, Perhaps there are one or two quarters of data not as good as it used to be(but not too bad, also not too much), but as long as Its trend is good, It is good.
has answer: http://stackoverflow.com/a/71806704
linked to: http://stackoverflow.com/q/10048571
has comment: http://stackoverflow.com/comment/85719148
tagged with: moving-average
has title: How to determine the trend of a numeric list in Python
answer count: 3
tagged with: algorithm
tagged with: python
upvote count: 4

http://stackoverflow.com/q/49376963
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85754792
tagged with: python
score: -1
has body: Can someone explain to me why the output would be: [[8, 0]] [[8, 0], [8, 0], [8, 0]] This is the function that is confusing me x = [[0,0]] y = x * 3 i = 10 for inner in y: inner[0] = i i -= 1 print(x) print(y)
has answer: http://stackoverflow.com/a/49377723
has title: Where does the 8 come from as the output to this function?
has comment: http://stackoverflow.com/comment/85754869
answer count: 2
has comment: http://stackoverflow.com/comment/85754791
upvote count: 0
linked to: http://stackoverflow.com/q/2612802
downvote count: 1
has answer: http://stackoverflow.com/a/49377072
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/6688223

http://stackoverflow.com/q/49318402
type: AnsweredQuestion
score: 20
answer count: 2
downvote count: 0
has title: Read/Write single file in DataBricks
tagged with: databricks
has answer: http://stackoverflow.com/a/49530874
accepted answer: http://stackoverflow.com/a/49530874
favorite count: 0
type: Question
upvote count: 20
has body: I have a file which contains a list of names stored in a simple text file. Each row contains one name. Now I need to pro grammatically append a new name to this file based on a users input. For the input itself I use DataBricks widgets - this is working just fine and I have the new name stored in a string object. Now I need to append this name to my file. the file is mounted in the DataBricks File System (DBFS) under /mnt/blob/myNames.txt when trying to read the file like this: f = open("/mnt/blob/myNames.txt", "r") print f it returns an error "No such file or directory" So I tried to wrap my new name into a dataframe and append it to the existing file but this also did not work as dataframe.write.save is designed to write into folders what would be the most simple python could that I could use to append this new name to my file?
has answer: http://stackoverflow.com/a/64206831
possible better answer: http://stackoverflow.com/a/64206831
tagged with: pyspark
tagged with: python

http://stackoverflow.com/a/51449711
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49333254
has body: I have similar problems, and I got this resolved by running the code through sudo. Here is my case: sudo /Users/edamame/workspace/git/chinese_nlp/venv/bin/python3 chinese_segmenter.py So you will be doing: sudo /Your_python_location/python3 /Users/xiehang/PycharmProjects/Autism/NER.py Hope this works for you as well.
downvote count: 0

http://stackoverflow.com/q/49439352
accepted answer: http://stackoverflow.com/a/49439685
has answer: http://stackoverflow.com/a/49439685
type: Question
score: 0
tagged with: python
tagged with: data-fitting
type: AnsweredQuestion
has body: I am trying to fit my data with the sum of two exponentials. However, I always get some error. When i try to run this code i get an error that operands could not be broadcast together... Can anyone pls review this code? I am a python newbie. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit old_settings = np.seterr(all='ignore') x=[0.21, 0.43, 0.50, 0.65, 0.86, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0] y=[43, 33, 30, 24, 18, 16, 14, 13, 14, 13, 13] yerr= [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] xerr=[0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01, 0.01,0.01,0.01] def func(x, a, b, c, d): return a * np.exp(b * x) + c * np.exp(d * x) # Here you give the initial parameters for a,b,c which Python then iterates over # to find the best fit popt, pcov = curve_fit(func,x,y,p0=(2.0, -7.0, 2.0, 0.1)) print(popt) # This contains your three best fit parameters p1 = popt[0] # This is your a p2 = popt[1] # This is your b p3 = popt[2] # This is your c p4 = popt[3] # This is your d residuals = y - func(x,p1,p2,p3,p4) fres = sum( (residuals**2)/func(x,p1,p2,p3,p4) ) # The chi-sqaure of your fit print(fres) """ Now if you need to plot, perform the code below """ curvey = func(x,p1,p2,p3,p4) # This is your y axis fit-line plt.plot(x, curvey, 'red', label='The best-fit line') plt.scatter(x,y, c='b',label='The data points') plt.legend(loc='best') plt.xlabel('x') plt.ylabel('y') plt.show() and the error is: Warning (from warnings module): File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 13 return a * np.exp(b * x) + c * np.exp(d * x) VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future Traceback (most recent call last): File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 27, in &lt;module&gt; residuals = y - func(x,p1,p2,p3,p4) ValueError: operands could not be broadcast together with shapes (11,) (0,) Thank you for any inputs.
has title: fitting the sum of exponentials in python.. error: operands could not be broadcast together with shapes (11,) (0,)
answer count: 1

http://stackoverflow.com/a/49367923
has comment: http://stackoverflow.com/comment/85765935
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49367296
type: AcceptedAnswer
has body: Use DataFrame.duplicated() to check if your data-frame contains any duplicate or not. If yes then you can try DataFrame.drop_duplicate() .
has comment: http://stackoverflow.com/comment/85758529
answers question: http://stackoverflow.com/q/49367296
has comment: http://stackoverflow.com/comment/85927203

http://stackoverflow.com/comment/86017202
type: Comment
type: AnswerComment
has text: You might not need to suffer the disk IO if you can fit your data in memory twice. I had exactly this problem with a large DataFrame (stored in self.big_df), but I was able to get away with an easier solution: just chunk the DataFrame. I had a quick loop build a list of parameters with chunks of the df, (so now memory is 2x self.big_df - one for original and one for the chunks) and then I explicitly assigned self.big_df={}. I subsequently created the pool and no longer had memory issues, each thread only had memory demands equal to a small percentage of the original df.
score: 0
comment on: http://stackoverflow.com/a/49502189

http://stackoverflow.com/q/49420605
tagged with: inheritance
has title: How can I reduce code duplication when using inheritance in relation to exceptions?
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49420821
possible better answer: http://stackoverflow.com/a/49420821
has comment: http://stackoverflow.com/comment/85842529
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49420816
favorite count: 0
type: Question
score: 3
tagged with: exception
has comment: http://stackoverflow.com/comment/85842308
tagged with: python
has body: I have a class. class IncorrectOfferDetailsOfferException(Exception): def __init__(self, offer): self.offerName = offer[0] self.offerType = offer[1] self.message = "Offer \"" + self.offerName + "\" could not be completed. It appears to be of type \"" + self.offerType + "\", but this may be what is wrong and causing the exception." super(IncorrectOfferDetailsOfferException, self).__init__(self.message) I want to write a more general class to expand it. class BadOfferException(Exception): def __init__(self, offer): self.offerName = offer[0] self.offerType = offer[1] self.message = "Offer \"" + self.offerName + "\" caused a problem." How can I relate those two together to remove the redundant code and override the more general message text with the more specific one? You know, class inheritance. I'm having a lot of trouble understanding how to use super the right way to do this.
accepted answer: http://stackoverflow.com/a/49420816

http://stackoverflow.com/q/49397385
answer count: 3
has comment: http://stackoverflow.com/comment/85796565
accepted answer: http://stackoverflow.com/a/49397981
tagged with: python
has comment: http://stackoverflow.com/comment/85796951
has answer: http://stackoverflow.com/a/49397981
has answer: http://stackoverflow.com/a/49397470
type: Question
score: 0
has answer: http://stackoverflow.com/a/49397502
possible better answer: http://stackoverflow.com/a/49397470
has comment: http://stackoverflow.com/comment/85796578
has title: Call a Python script from another Python script with list as argument?
type: AnsweredQuestion
has body: I am trying to run a Python script a.py from another Python script scheduler.py and I want to pass a list as argument something like: Scheduler.py: t = {"code": 161123134, "name": "task2", "domain": "www.google.com", "type": "Type1", "keywords": ["bai2", "yin4", "jiao3", "yi8", "ping1", "tai3"]} hourTasks = json.dumps(t) os.system("python a.py " + hourTasks) a.py task = sys.argv[1:] task = json.loads(task) However It gives me an error the JSON object must be str, bytes or bytearray, not 'list'. Anyone know what the problem is?

http://stackoverflow.com/q/49418227
tagged with: global
favorite count: 0
type: Question
tagged with: local
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85838420
downvote count: 0
has comment: http://stackoverflow.com/comment/85838624
upvote count: 1
has comment: http://stackoverflow.com/comment/85838541
has body: I got a local error at first, and when I applied global to my code, I got a syntax error. def get_data(): try: source = someURL data = requests.get(source) try: with open('data_file.csv', 'a') as file: writer = csv.DictWriter(file, fieldnames=['Column']) writer.writerow({'Column':data}) except: pass except: pass First, I got an error of UnboundLocalError: local variable 'data' referenced before assignment, then I added global data above the 2nd try. And now I got SyntaxError: name 'data' is assigned to before global declaration I tried to solve it by applying other people's solutions but with no luck. How would you fix it? Thanks. Update: data may have issue getting the value. When there's no value, an error will occur on the writerow line. But if I added except: None after the first try for the intention of returning None instead, as shown below: def get_data(): try: source = someURL data = requests.get(source) except: None It will generate a local variable error: local variable 'data' referenced before assignment. And the only way I have to do is to define data as global. I'm confused if I'm even on the right path. Or should there be any way to do rather than using except: None? Thanks.
score: 1
has answer: http://stackoverflow.com/a/49418662
has title: UnboundLocalError: local variable 'data' referenced before assignment
answer count: 1
tagged with: python

http://stackoverflow.com/a/49389997
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85791097
has body: Use a dictionary dispatcher: from footballAdults import footballAdults from footballTeens import footballTeens from footballKids import footballKids from tennisAdults import tennisAdults x = input("Pick a sport:") y = input ("Pick an age group:") d = {('football', 'adults'): footballAdults, ('football', 'teens'): footballTeens, ('football', 'kids'): footballKids, ('tennis', 'adults'): tennisAdults} d[(x, y)]() Explanation Store your tuple keys (matching values of x and y) together with function values in a dictionary. Call your function via the dictionary.
accepted answer of: http://stackoverflow.com/q/49389920
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/85793514
answers question: http://stackoverflow.com/q/49389920
type: Answer
has comment: http://stackoverflow.com/comment/85811959

http://stackoverflow.com/a/49301186
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49300960
has body: If 'ID' is in the index, then you can use index=False: csvdf.to_csv('./en_final_table_2.csv', sep='\t', encoding='utf-32', index=False)
type: Answer
accepted answer of: http://stackoverflow.com/q/49300960
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85747392
has text: But this doesn't preserve the order of the existing lines, and it's not that much simpler than just checking each line before appending it.
comment on: http://stackoverflow.com/a/49372979
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49322894
downvote count: 0
has title: Check if Pandas column values are not in list
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85647366
tagged with: python
has comment: http://stackoverflow.com/comment/85647461
possible better answer: http://stackoverflow.com/a/49323178
has body: I have a dataframe consisting of counts within 10 minute time intervals, how would I set count = 0 if the time interval doesn't exist? DF1 import pandas as pd import numpy as np df = pd.DataFrame({ 'City' : np.random.choice(['PHOENIX','ATLANTA','CHICAGO', 'MIAMI', 'DENVER'], 10000), 'Day': np.random.choice(['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 10000), 'Time': np.random.randint(1, 86400, size=10000), 'COUNT': np.random.randint(1, 700, size=10000)}) df['Time'] = pd.to_datetime(df['Time'], unit='s').dt.round('10min').dt.strftime('%H:%M:%S') print(df) COUNT City Day Time 0 441 PHOENIX Thursday 10:20:00 1 641 ATLANTA Monday 14:30:00 2 661 PHOENIX Saturday 03:50:00 3 570 MIAMI Tuesday 21:00:00 4 222 CHICAGO Friday 15:00:00 DF2 - My approach is to create all the 10 minute time slots in a day (6*24 = 144 entries) and then use "not in" df2 = pd.DataFrame({'TIME_BIN': np.arange(0, 86401, 600), }) df2['TIME_BIN'] = pd.to_datetime(df2['TIME_BIN'], unit='s').dt.round('10min').dt.strftime('%H:%M:%S') TIME_BIN 0 00:00:00 1 00:10:00 2 00:20:00 3 00:30:00 4 00:40:00 5 00:50:00 6 01:00:00 7 01:10:00 8 01:20:00 How do I check if the timeslots in DF2 do not exist in DF1 for each city and day and if so, set count = 0? I basically just need to fill in all the missing time slots in DF1. Attempt: for each_city in df.City.unique(): for each_day in df.Day.unique(): df['Time'] = df.apply(lambda row: df2['TIME_BIN'] if row['Time'] not in (df2['TIME_BIN'].tolist()) else None)
score: 2
has answer: http://stackoverflow.com/a/49323178
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49323260
accepted answer: http://stackoverflow.com/a/49323139
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/85647404
has answer: http://stackoverflow.com/a/49323139

http://stackoverflow.com/comment/85656135
type: AnswerComment
has text: Thank you. I also just found this link about 30 minutes ago. It's exactly the problem. I then try to catch WebDrierException and add a sleep(1) and retry the wait.until(expected_conditions.alert_is_present()), and it works.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49326687

http://stackoverflow.com/a/49361056
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49359341
has body: When you are using zip(), you are working with lists. List contains arrays, your function and random number are just number without [] which demonstrats an array. so you can use without its for loop containing zip(). f.write("{0}\t{1}\n".format(c(),R1)) The other point: Bring functions out of the with open order.

http://stackoverflow.com/comment/85838124
has text: If my post answered your question, could you please select it as the answer? [This page] (https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) explains how accepting an answer works. If not, what else is wrong?
comment on: http://stackoverflow.com/a/49417382
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85863206
type: Comment
type: AnswerComment
score: 0
has text: @Liwellyen Do you really want to replace it with the boolean values or do you want to repeat the original slice? For the latter just do: `array[:]=array[zIndex]`. For the former: would you also want to change the `dtype` of the array to bool then?
comment on: http://stackoverflow.com/a/49428927

http://stackoverflow.com/comment/85612891
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49286313
has text: The point is to show the influence of the parameters on the outcome.
score: 0

http://stackoverflow.com/comment/85747039
has text: Thank you for your response, and my apologies for the bad copy-paste. I copy-pasted from a `redo`, but was one `redo` too early. It is `choice[0]`. I updated my question.
comment on: http://stackoverflow.com/a/49372171
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85628282
score: 1
comment on: http://stackoverflow.com/q/49313012
type: Comment
type: QuestionComment
has text: See [this](https://brilliant.org/wiki/recursive-backtracking/) article.

http://stackoverflow.com/comment/131536886
has text: @jezrael, no I have only two columns, actually, have posted a question, could you please have a look will be immense help, this is the link. https://stackoverflow.com/questions/74513906/zip-dict-converts-a-integer-list-to-a-string-while-creating-a-json-file
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49358537
type: AnswerComment

http://stackoverflow.com/a/49380485
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: I finally managed to do it using the iterative level order traversal pattern (BFS), I was missing just a couple of details. This approach works because the depth iteration order is guaranteed, so once we are getting to a node wich has children, all its sub-level children are already calculated. The solution: def reverseTraversal(obj): def parentOperation(node): out = 0 for child in node['children']: out = out + child['value'] return out if obj is None: return queue = [] stack = [] queue.append(obj) while len(queue) &gt; 0: temp = queue.pop(0) stack.append(temp) if 'children' in temp and len(temp['children']) &gt; 0: for child in temp['children']: queue.append(child) while len(stack)&gt;0: node = stack.pop() if 'children' in node and len(node['children']) &gt; 0: node['value'] = parentOperation(node) # obj is the original dict obj = reverseTraversal(obj) print(obj) Results in: { "name": "root", "value": 80, "children": [ { "name": "a", "value": 30, "children": [ {"name": "a.1","value": 10}, {"name": "a.2","value": 20} ] }, { "name": "b", "value": 50, "children": [ {"name": "b.1","value": 25}, { "name": "b.2", "value": 25, "children": [ {"name": "b.2.1","value": 5}, {"name": "b.2.2","value": 5}, {"name": "b.2.3","value": 5}, {"name": "b.2.4","value": 5}, {"name": "b.2.5","value": 5} ] } ] } ] }
accepted answer of: http://stackoverflow.com/q/49369594
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49369594

http://stackoverflow.com/comment/94102816
has text: **Update,** wanted to add that I was eventually able to get the demo/ tutorial poky bitbake to compile, after struggling with permission issues [see this wsl issues list on github](https://github.com/Microsoft/WSL/issues?utf8=%E2%9C%93&q=+Errno+13+) and [python manual page about os paths](https://docs.python.org/3/library/os.html). The **bake took 9 hours!!** --> I **love** what the wsl team is doing and think it is incredible, but (baring a complete failure of setup on my end) it doesn't seem ready for Linux production tasks. The build on the same machine (in Linux dual boot) 47 minutes!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53326852
type: Comment

http://stackoverflow.com/q/49350942
has answer: http://stackoverflow.com/a/49351093
tagged with: gradient-descent
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/85701886
has body: I don't know how in detail Stochastic Gradient Descent algorithm works and I don't need to know this at the moment. What I know is that it minimizes loss function by calculating gradients and going into direction of the local minimum. But I'm using Stochastic Gradient Descent as a optimizer in my project using Keras and I don't know what the parameters of this optimizer mean. Obviously, those parameters are shortly described in documentation, but it's not specific enough and I still don't understand what they mean. So could you explain those 4 parameters: lr: float &gt;= 0. Learning rate. momentum: float &gt;= 0. Parameter that accelerates SGD in the relevant direction and dampens oscillations. decay: float &gt;= 0. Learning rate decay over each update. nesterov: boolean. Whether to apply Nesterov momentum. And how can I know how I should set them?
tagged with: parameters
has comment: http://stackoverflow.com/comment/85701944
has title: Keras, Stochastic Gradient Descent - what do parameters mean
downvote count: 3
tagged with: deep-learning
upvote count: 1
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49370286
upvote count: 1
answers question: http://stackoverflow.com/q/49363360
score: 1
has body: Try it: from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QStatusBar class AutoTestWindow(QMainWindow): def __init__(self): super().__init__() self.driver = None # +++ self.query = "Тензор" # +++ self.initUI() def initUI(self): btn1 = QPushButton("Test № 1 ", self) btn1.move(30, 50) btn2 = QPushButton("Test № 2", self) btn2.move(150, 50) #btn1.clicked.connect(self.buttonClicked) # --- #btn2.clicked.connect(self.buttonClicked) # --- btn1.clicked.connect(self.init_driver) # +++ btn2.clicked.connect(lambda checked : self.findelem(self.driver, self.query)) # +++ self.statusBar().showMessage('Запуск тестов', 5000) self.setGeometry(300, 300, 290, 150) self.setWindowTitle('Запуск тестов') self.show() # --- #def buttonClicked(self): # sender = self.sender() # self.statusBar().showMessage(sender.text() + ' test started') # +++ def init_driver(self): self.statusBar().showMessage('Test № 1 test started') #driver = webdriver.Chrome("/Users/alexeynikitin/Desktop/chromedriver") self.driver = webdriver.Chrome() self.driver.wait = WebDriverWait(self.driver, 10) #return self.driver # +++ def findelem(self, driver, query): print("\ndriver=`{}`, \nquery=`{}`\n".format(driver, query)) self.statusBar().showMessage('Test № 2 test started') if driver is not None: driver.get("https://www.yandex.ru/") try: box = driver.wait.until(ec.presence_of_element_located( (By.ID, "text"))) button = driver.wait.until(ec.visibility_of_element_located( (By.CLASS_NAME, "search2__button"))) box.send_keys(query) suggestion_box = driver.wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "body &gt; div.i-bem.popup.suggest2.suggest2_theme_flat.suggest2_size_m.suggest2_adaptive_yes.suggest2_type_advanced.suggest2_ahead_yes.popup_adaptive_yes.popup_animate_no.popup_autoclosable_yes.popup_theme_ffffff.suggest2-detect_js_inited.suggest2_js_inited.popup_js_inited.popup_to_bottom.popup_visibility_visible"))) try: button.click() except ElementNotVisibleException: button = driver.wait.until(…
type: Answer
accepted answer of: http://stackoverflow.com/q/49363360
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85628347
type: Comment
score: 2
type: QuestionComment
has text: Use `adb`: https://blog.shvetsov.com/2013/02/grab-android-screenshot-to-computer-via.html?m=1
comment on: http://stackoverflow.com/q/49313291

http://stackoverflow.com/comment/85652796
has text: likely a table locking issue (not a fan of MySQL table locking). Info on table locking and what to look for here https://stackoverflow.com/questions/2499976/detecting-locked-tables-locked-by-lock-table
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49325588
type: Comment

http://stackoverflow.com/q/49426422
has answer: http://stackoverflow.com/a/49426494
tagged with: python
has comment: http://stackoverflow.com/comment/85853668
type: AnsweredQuestion
answer count: 2
score: 1
has title: Simple decorator function in python not working
possible better answer: http://stackoverflow.com/a/49426685
downvote count: 0
upvote count: 1
has body: I am trying to execute the below code in pycharm. def auth_login(func): def wrapper(*args, **kwargs): print("Authenticating......") func(*args, **kwargs) return wrapper() @auth_login def login(username, password): print("Successfully logged in:",username) login('setu', 'setu') Looks pretty straight forward but I getting the below error: Output : &gt; Traceback (most recent call last): &gt; Authenticating...... &gt; File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", &gt; line 10, in &lt;module&gt; &gt; @auth_login &gt; File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", &gt; line 7, in auth_login &gt; return wrapper() &gt; File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py", &gt; line 5, in wrapper &gt; func(*args, **kwargs) &gt; TypeError: login() missing 2 required positional arguments: 'username' and 'password' &gt; &gt; Process finished with exit code 1
has answer: http://stackoverflow.com/a/49426685
accepted answer: http://stackoverflow.com/a/49426494
favorite count: 0
type: Question

http://stackoverflow.com/q/49325520
has body: I have to perform a clustering of a categorical sequence data set. The data set is a Time of Use survey where for each of the person involved in the survey I have a sequence of 144 (one every ten minutes) labels that represent the action that they are perfoming. I want to identify archetypes of users with respect to the pattern and with respect to labels regarding the person (eg. Age, work, Sex, ...). Which clustering technique can I use? Any python libraries?
tagged with: k-means
tagged with: cluster-analysis
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/85679589
tagged with: hierarchical-clustering
type: Question
has comment: http://stackoverflow.com/comment/85652679
has title: categorical data sequence clustering
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85692123
comment on: http://stackoverflow.com/q/49345876
score: 0
has text: @Jean-FrançoisFabre Thanks! That's even better than the one from a couple years ago (probably a newer evolution of it?); bookmaked.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49438628
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49438360
has body: Here's a minimal example of what you are trying to do. Hope this gives you enough hint: # sample data df1 = pd.DataFrame({'ticker':['AAPL','IBM','XRX'], 'hhmm':['0931','0930','1559']}) df2 = pd.DataFrame({'ticker':['AAPL','IBM','XRX'], '0931': [2,2,3], '0930': [5,6,7], '1559': [8,7,6]}) # melt to match the format to join df2 = pd.melt(df2, id_vars='ticker',var_name='hhmm',value_name='df2val') # join to df1 df1.merge(df2, on=['ticker','hhmm']) hhmm ticker df2val 0 0931 AAPL 2 1 0930 IBM 6 2 1559 XRX 6

http://stackoverflow.com/q/49375702
has answer: http://stackoverflow.com/a/49376353
accepted answer: http://stackoverflow.com/a/49376353
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85752981
tagged with: local
upvote count: 1
tagged with: multithreading
favorite count: 0
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/49375910
has title: Python threading.local() not working in Thread class
has body: In Python3.6, I use threading.local() to store some status for thread. Here is a simple example to explain my question: import threading class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.local = threading.local() self.local.test = 123 def run(self): print(self.local.test) When I start this thread: t = Test() t.start() Python gives me an error: AttributeError: '_thread._local' object has no attribute 'test' It seems the test atrribute can not access out of the __init__ function scope, because I can print the value in the __init__ function after local set attribute test=123. Is it necessary to use threading.local object inside in a Thread subclass? I think the instance attributes of a Thread instance could keep the attributes thread safe. Anyway, why the threading.local object not work as expected between instance function?
downvote count: 1
has answer: http://stackoverflow.com/a/49375910
tagged with: python

http://stackoverflow.com/q/49439103
answer count: 1
tagged with: dataframe
has body: Given a dataframe A B C 3 1 2 2 1 3 3 2 1 I would like to get a new column with column names in sorted order A B C new_col 3 1 2 [B,C,A] 2 1 3 [B,A,C] 3 2 1 [C,B,A] This is my code. It works but is quite slow. def blist(x): col_dict = {} for col in col_list: col_dict[col] = x[col] sorted_tuple = sorted(col_dict.items(), key=operator.itemgetter(1)) return [i[0] for i in sorted_tuple] df['new_col'] = df.apply(blist,axis=1) I will appreciate a better approach to solve this problem.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49439144
tagged with: sorting
tagged with: numpy
has answer: http://stackoverflow.com/a/49439144
upvote count: 2
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has title: Efficient and fastest way in Pandas to create sorted list from column values
tagged with: pandas

http://stackoverflow.com/comment/85747451
score: 0
has text: Please make sure that you refer to [the documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.ExcelFile.parse.html) before asking. The accepted answer in the question you linked shows that `read_excel` takes a `converters` parameter. So does `pd.ExcelFile.parse`. Did you try it?
comment on: http://stackoverflow.com/q/49373065
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49355899
answers question: http://stackoverflow.com/q/49354168
score: 0
has body: Order is not maintained by a dict in Python. If you want to keep the keys in the order that they are inserted, you can use an OrderedDict from collections import OrderedDict Your code would then become #Result stores a list of dicts with username key/value pair and a long list of fields result = [{ username: nasa , fields: [Nebula, Moon, Star, ...]},{ username: nationalgeographic, fields: [Grass, Tree, ...] },{ username: kingjames, fields[Basketball, Hardwood, Jersey, ...]}] for i in result: #For each dict in list num = 1 item = OrderedDict() item['username'] = i['username'] for tag in i['fields']: label_string = 'label' + str(num) item[label_string] = tag num += 1 output.append(item.copy()) #Output should store 3 dicts with username, and labels with tags for user in output: for key, value in user.items(): print(key, value)
type: Answer

http://stackoverflow.com/q/49310497
accepted answer: http://stackoverflow.com/a/49310580
answer count: 2
has body: I'm new in python and need get a value fron anoter value of same block, this is an example of JSON: { u'Name': u'test', u'ProjectPath': u'/data/compose/test_pz4u6zug8swd2isfkcrzh9kjl', u'ResourceControl': { u'ResourceId': u'test', u'UserAccesses': [ ], u'AdministratorsOnly': True, u'TeamAccesses': [ ], u'SubResourceIds': [ ], u'Type': 6, u'Id': 8 }, u'EntryPoint': u'docker-compose.yml', u'Env': [ ], u'SwarmId': u'pz4u6zug8swd2isfkcrzh9kjl', u'Id': u'test_pz4u6zug8swd2isfkcrzh9kjl' }, { u'Name': u'ycf', u'ProjectPath': u'/data/compose/ycf_pz4u6zug8swd2isfkcrzh9kjl', u'ResourceControl': { u'ResourceId': u'ycf', u'UserAccesses': [ ], u'AdministratorsOnly': True, u'TeamAccesses': [ ], u'SubResourceIds': [ ], u'Type': 6, u'Id': 5 }, u'EntryPoint': u'docker-compose.yml', u'Env': None, u'SwarmId': u'pz4u6zug8swd2isfkcrzh9kjl', u'Id': u'ycf_pz4u6zug8swd2isfkcrzh9kjl' } I need get the value of Id from filed Name, eg. I need to know value of Id (test_pz4u6zug8swd2isfkcrzh9kjl) from Name 'test', is possible? I get this JSON from a request: r_get = requests.get(http://www.example.com:9000/api/endpoints/1/stacks) id_response = json.loads(r_get.content.decode('utf-8')) print(id_response)
has title: Retrieve data from JSON?
type: Question
possible better answer: http://stackoverflow.com/a/49310574
has comment: http://stackoverflow.com/comment/85623027
has answer: http://stackoverflow.com/a/49310574
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/85623018
has comment: http://stackoverflow.com/comment/85623067
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49310580
score: 0

http://stackoverflow.com/a/54799396
type: Answer
score: 0
has body: https://anaconda.org/conda-forge/tabula-py To install this package with conda run one of the following: &gt; conda install -c conda-forge tabula-py conda install -c &gt; conda-forge/label/cf201901 tabula-py
answers question: http://stackoverflow.com/q/49373535

http://stackoverflow.com/q/49401488
has comment: http://stackoverflow.com/comment/85805327
type: AnsweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/85804234
has title: NotImplementedError: Only tempfile.TemporaryFile is available for use
accepted answer: http://stackoverflow.com/a/49402553
tagged with: python
has answer: http://stackoverflow.com/a/49402553
favorite count: 0
type: Question
score: 2
linked to: http://stackoverflow.com/q/3586134
upvote count: 2
answer count: 1
has body: I'm using django and Google App Engine. I can't determine where's the error came from because if I'm using it on local my site is functioning. After I deployed it on GAE it works fine but when using googleadwords api this error comes: NotImplementedError: Only tempfile.TemporaryFile is available for use at PlaceHolder (/base/alloc/tmpfs/dynamic_runtimes/python27/a7637d5531ec9deb_unzipped/python27_dist/lib/python2.7/tempfile.py:45) at __init__ (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/suds/cache.py:115) at __init__ (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/suds/client.py:112) at GetService (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/googleads/adwords.py:459) at post (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/ksvt/views.py:47) at dispatch (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/views/generic/base.py:88) at view (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/views/generic/base.py:68) at _get_response (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/base.py:185) at _get_response (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/base.py:187) at inner (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/exception.py:41) Can someone explain what is the meaning of this error? Thanks! Edit: The line of code that I think generates the error. adwords_client = adwords.AdWordsClient.LoadFromStorage(os.path.dirname(os.path.abspath(__file__)) + "//googleads.yaml")
downvote count: 0
tagged with: django
tagged with: google-ads-api

http://stackoverflow.com/comment/85877961
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49395087
has text: Thank you (Eric) this was helpful, wish I would have saw it before I asked my question.
score: 0

http://stackoverflow.com/a/49339123
answers question: http://stackoverflow.com/q/49322210
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49322210
type: Answer
has body: The file mentioned in the error message is a 32-bit DLL, not a 64-bit DLL -- at least assuming the logic that checks such things is correct! The code is making use of the imagehelp API mentioned here: How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?. There are a few other ways to verify that the DLL is 32-bit or 64-bit as well. Check your PATH and ensure that a 64-bit Oracle Client installation is first in the PATH. Download and unzip a 64-bit Oracle Instant Client for quick and easy testing.

http://stackoverflow.com/a/49368137
downvote count: 0
has comment: http://stackoverflow.com/comment/85737625
has comment: http://stackoverflow.com/comment/85737718
answers question: http://stackoverflow.com/q/49367943
upvote count: 1
has comment: http://stackoverflow.com/comment/85738177
has body: Try this: result_group = {} group_count = 0 for sub_group in result: first_rel_item = 0 result_group[group_count] = {} result_group[group_count][sub_group[0]] = None previtem = sub_group[0] for item in sub_group[1:]: result_group[group_count][item] = previtem previtem = item group_count += 1
accepted answer of: http://stackoverflow.com/q/49367943
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85737700
has comment: http://stackoverflow.com/comment/85737784
type: AcceptedAnswer

http://stackoverflow.com/q/49394007
has answer: http://stackoverflow.com/a/49416375
answer count: 1
tagged with: python-requests
type: Question
type: UnansweredQuestion
tagged with: python
has body: I've tried to install requests module (Debian, Python 2.7) by pip install requests command. Output was: Installing collected packages: urllib3, requests Successfully installed requests-2.18.4 urllib3-1.22 Tried following the following Quickstart tutorial but I get the following error at import requests Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "requests/__init__.py", line 76, in &lt;module&gt; check_compatibility(urllib3.__version__, chardet.__version__) AttributeError: 'module' object has no attribute '__version__' Any help?
tagged with: python-2.7
score: 0
tagged with: urllib3
has title: Python 2.7 import requests issue

http://stackoverflow.com/comment/85847196
has text: Have you used Selenium? You can do it, using Selenium.
comment on: http://stackoverflow.com/q/49423082
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85683668
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49341572
has text: I've edited my answer accordingly - this paper is linked in tf documentation on `FtrlOptimizer`...
type: Comment

http://stackoverflow.com/comment/85837287
has text: The first functionality is seen in a numpy array. The second would involve subclassing dictionaries.
type: Comment
comment on: http://stackoverflow.com/q/49417747
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85860827
type: Comment
has text: Why would a filter operation give you a max?
type: QuestionComment
comment on: http://stackoverflow.com/q/49429709
score: 0

http://stackoverflow.com/comment/85613714
has text: Stupid question .. Does your `php` installation have `exec` permissions by the server? And what (if any) errors are you receiving?
comment on: http://stackoverflow.com/q/49305721
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49360068
has comment: http://stackoverflow.com/comment/85722341
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49359782
has comment: http://stackoverflow.com/comment/85724185
has comment: http://stackoverflow.com/comment/85721929
has comment: http://stackoverflow.com/comment/85722037
answers question: http://stackoverflow.com/q/49359782
has body: Run your Docker container as a daemon process, and every time you need to run your Python script, call docker exec. docker exec -d &lt;your-container&gt; &lt;your-python-file.py&gt;
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49351882
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85703949
has title: Combine Columns Based Upon Another Column with Python and Pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39922986
has comment: http://stackoverflow.com/comment/85703862
has body: I have a huge tab-delimited file such as the following : 3 Line1 0 100 A 4 Line1 100 200 A 7 Line1 200 300 B 2 Line1 300 400 B 12 Line1 400 500 C 10 Line1 500 600 C For all the rows that have the letters (A, B, ect), I need to combine their values based upon the number in the first column. For example, what should be the result is below: 7 A 9 B 22 C I am currently using Pandas + Python to figure this out.
accepted answer: http://stackoverflow.com/a/49352007
has answer: http://stackoverflow.com/a/49352015
has answer: http://stackoverflow.com/a/49352007
tagged with: python
duplicate of: http://stackoverflow.com/q/39922986
possible better answer: http://stackoverflow.com/a/49352013
type: Question
has answer: http://stackoverflow.com/a/49352013
answer count: 3
tagged with: pandas
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85853328
type: AnswerComment
has text: @Flabou in this case they are fairly cheap to compute, so I wouldn't bother.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49425867

http://stackoverflow.com/comment/85664696
type: QuestionComment
comment on: http://stackoverflow.com/q/49331312
has text: What did you try? Please post your code.
type: Comment
score: 0

http://stackoverflow.com/q/49383494
has comment: http://stackoverflow.com/comment/85768618
has comment: http://stackoverflow.com/comment/85768710
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85768615
has comment: http://stackoverflow.com/comment/85768211
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85768694
has comment: http://stackoverflow.com/comment/85768194
tagged with: models
accepted answer: http://stackoverflow.com/a/49384045
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49384045
has comment: http://stackoverflow.com/comment/85768107
has body: Here is my code im building 6 models and i am getting accuracy in that, how do i choose that dynamically which accuracy is greater and i want to execute only that model which as highest accuracy. "prepare configuration for cross validation test harness" seed = 7 "prepare models" models = [] models.append(('LR', LogisticRegression())) models.append(('LDA', LinearDiscriminantAnalysis())) models.append(('KNN', KNeighborsClassifier())) models.append(('CART', DecisionTreeClassifier())) models.append(('NB', GaussianNB())) models.append(('RF',RandomForestClassifier())) #models.append(('SVM', SVC())) "evaluate each model in turn" results = [] names = [] scoring = 'accuracy' for name, model in models: kfold = model_selection.KFold(n_splits=10, random_state=seed) cv_results = model_selection.cross_val_score(model, orginal_telecom_80p_test[features], orginal_telecom_80p_test["Churn"], cv=kfold, scoring=scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg) This is my accuracy LR: 0.787555 (0.039036) LDA: 0.780460 (0.039821) KNN: 0.759916 (0.030417) CART: 0.706669 (0.035827) NB: 0.731637 (0.050813) RF: 0.752054 (0.048660)
has title: How to choose the best model dynamically using python
has comment: http://stackoverflow.com/comment/85767987
has comment: http://stackoverflow.com/comment/85768604
type: Question
has comment: http://stackoverflow.com/comment/85768369
has comment: http://stackoverflow.com/comment/85767962
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/85789756
type: AnswerComment
comment on: http://stackoverflow.com/a/49389645
has text: yep, you are right. I have also seen that in PostgreSQL docs, tried - and it didn't work. When you wrote - I have tried again, restarted postgresql server - and that worked from Windows cmd. But the question is - why django-dbbackup module sends a wrong command? How to fix that? Thank you anyway.
type: Comment
score: 0

http://stackoverflow.com/a/49398853
answers question: http://stackoverflow.com/q/49398567
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85799464
has comment: http://stackoverflow.com/comment/85921661
type: Answer
has comment: http://stackoverflow.com/comment/85921191
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49398567
has comment: http://stackoverflow.com/comment/85921764
has body: One way you can refactor this is to loop over four delta pairs, and then the inner loop can use the current one. For example: def perimeter(min_x, min_y, max_x, max_y): x, y = min_x, min_y for dx, dy in (1, 0), (0, 1), (-1, 0), (0, -1): while x in range(min_x, max_x+1) and y in range(min_y, max_y+1): yield (x, y) x += dx y += dy x -= dx y -= dy This isn't the cleanest way to write this, but I think it gets the idea across the best. And a nice advantage is that you can pretty easily adapt it to handle totally different shapes. Making it work with 2x2 pixels just means doubling the deltas. Making it work with pentagons means… well, you have to decide how you want to handle fractional points, but other than that it's just a matter of picking five evenly-rotated unit vectors instead of four.

http://stackoverflow.com/comment/85587475
score: 0
comment on: http://stackoverflow.com/q/49291876
type: Comment
has text: get ideas from https://stackoverflow.com/questions/32381942/get-a-list-of-file-names-from-hdfs-using-python to get the list of filenames from hdfs and then loop the list using your above logic. :) hope it helps
type: QuestionComment

http://stackoverflow.com/comment/85687302
comment on: http://stackoverflow.com/q/49343511
type: Comment
type: QuestionComment
has text: Automatize it to what? I did not gather that from your question. Do you mean the values used until the break?
score: 0

http://stackoverflow.com/comment/85589840
has text: `if any(x in line for x in my_list)`. Do not use the name `list`; you are shadowing the Python built-in
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49293803
score: 6

http://stackoverflow.com/a/49423708
type: Answer
accepted answer of: http://stackoverflow.com/q/49423548
has comment: http://stackoverflow.com/comment/85849375
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/85849694
downvote count: 0
has comment: http://stackoverflow.com/comment/85849395
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85856650
has body: Try this: data = "your json data" # of type `str` json_dict = json.loads(data) for result in json_dict["response"]["results"]: if "alternatives" in result: alternatives = result["alternatives"][0] if "confidence" in alternatives: print(alternatives["confidence"]) if "transcript" in alternatives: print(alternatives["transcript"]) Use json.loads to convert / parse str to dict "alternatives" is of type list If your data is coming from a json file, read it first with open('data.json', 'r') as f: data = f.read() # refer to above code
answers question: http://stackoverflow.com/q/49423548

http://stackoverflow.com/comment/85729143
comment on: http://stackoverflow.com/q/49364432
type: Comment
has text: Did you try `np.array(array)`
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85624221
type: AnswerComment
has text: Yup, that’s the basic mistake I was making. Holdover from playing around with this library interactively, then trying to wrap things into a function. Thank you for the fast reply.
score: 0
comment on: http://stackoverflow.com/a/49311162
type: Comment

http://stackoverflow.com/comment/85636207
has text: -rwxr-xr-x 1 root root 222 11月 16 00:19 /usr/local/bin/jupyter
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49317226
score: 0

http://stackoverflow.com/comment/85783940
score: 0
type: AnswerComment
has text: @Jared. Oh... so you want to group by hours of a day. We can do that in the group by statement also.
comment on: http://stackoverflow.com/a/49388157
type: Comment

http://stackoverflow.com/comment/85667437
has text: add an example of the output you want.
comment on: http://stackoverflow.com/q/49332765
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49330894
has body: From what I can tell, you want to output the URL's like this: www.website.com/100 www.website.com/101 www.website.com/102 The solution I came up with based on the code you provided was to use the print() function with the file argument (Documentation of the file argument) with open(r'somefile.txt', "w") as f_out: for i in range(100, 120): print(r'www.website.com/{}'.format(i), file=f_out) You might also want to read about opening files in write mode here.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49330698
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49330698

http://stackoverflow.com/q/49332759
upvote count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49341060
has title: cannot import dynamically generated sqlalchemy classes in flask-python
type: UnansweredQuestion
tagged with: python
score: 1
downvote count: 0
answer count: 1
has body: Just started learning flask and python and I had to create 10+ tables(MySQLAlchemy) with the same structure and constraints. so after looking aroud for a quicker solution than declaring each class separately, I did the following in models/user.py: #models/users.py class exchangeapis(object): email = db.Column(db.String(50), primary_key=True) api =db.Column(db.String(100)) secret= db.Column(db.String(100)) @declared_attr.cascading # Makes sure all the dbs derived from this calss get the fK and PK def email(cls): #this is necessary to propagate fk and pk to the instances return db.Column(db.String(50), db.ForeignKey('users.email'), primary_key=True) #general methods to get class data def get_api(self): return self.api def get_secret(self): return self.secret exchange=['A','B','C'] for exchange in exchanges: cls=type(exchange.title(), (exchangeapis, db.Model), { '__tablename__' : str(exchange)+"_api"}) print(cls.__name__) the print(cls.__name__) gives me 'A', 'B', 'C' which I expect to be 'A_api', 'B_api'... when I try to import it into my account/views.py file, with the following: from ..models import User, A_api I get " File "/home/puru991/flask-saas/flask-base/app/account/views.py", line 8, in from ..models import User,A_api ImportError: cannot import name 'A_api'" but if i define the class in the following way: class A_api(db.Model): __tablename__="A_api" email = db.Column(db.String(50),ForeignKey("users.email"), primary_key=True) api =db.Column(db.String(100)) secret= db.Column(db.String(100)) #general methods to get class data def get_api(self): return self.api def get_secret(self): return self.secret There are no errors. So my questions is how do I dynamically create classes based on exchangeapi(object) and import them successfully? I went through about 8-10 answers around here and the most i could learn was how to create them dynamically. I also learnt that MySQLAlchemy creates classes with the same name as the tablename, so I thought referring by the table nam…

http://stackoverflow.com/a/49359439
has comment: http://stackoverflow.com/comment/85718963
answers question: http://stackoverflow.com/q/49359186
score: 0
has comment: http://stackoverflow.com/comment/85719528
has comment: http://stackoverflow.com/comment/85719240
has body: Try this: d = {} key = None with open('/home/asha/Desktop/test.txt','r') as file: for line in file: if line.startswith(' '): d[key].append(line.strip()) else: key = line.strip(); d[key] = [] print(d)
type: Answer

http://stackoverflow.com/comment/85723634
score: 0
type: Comment
has text: Well actually I'm not really sure what you're asking. What validation is not succeeding? Since you're passing an already-populated instance, one of those radio buttons will already be selected, so I'm not sure what is failing.
type: QuestionComment
comment on: http://stackoverflow.com/q/49361430

http://stackoverflow.com/comment/85825155
comment on: http://stackoverflow.com/a/49411638
type: Comment
score: 0
type: AnswerComment
has text: No down vote, but it is a bit heavy: you have to create a new dict every time you the function is called, even though the actual value of `x` is irrelevant to the dict. You also have to create a tuple and a list whether they are needed or not.

http://stackoverflow.com/comment/85836387
score: 1
type: QuestionComment
type: Comment
has text: `sqlmigrate` just prints out the commands, it does not run them.
comment on: http://stackoverflow.com/q/49416989

http://stackoverflow.com/comment/85876142
has text: If you have a SQL file put it in a database and use it that way. If you want a neutral data format that Python can deal with, CSV or JSON works better than SQL.
comment on: http://stackoverflow.com/q/49436834
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49384696
type: AnsweredQuestion
has body: In LightFM, the evaluation methods e.g. precision_at_k have a preserve_rows parameter with default value False. In what cases would I make it True?
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
tagged with: recommendation-engine
type: Question
accepted answer: http://stackoverflow.com/a/49630915
has title: LightFM: When do I make preserve_rows=True
tagged with: python
has answer: http://stackoverflow.com/a/49630915

http://stackoverflow.com/q/49381031
tagged with: django-registration
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Check box in django redux form. I am using django-redux
score: 0
has answer: http://stackoverflow.com/a/49381219
has body: I have added two check box in django redux registration form. Now, I can check both the option, But I want user to select any one at a time. How to achieve that? Below is my code models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserSelection(models.Model): employer = models.BooleanField() candidate = models.BooleanField() user = models.OneToOneField(User) forms.py from django import forms from registration.forms import RegistrationFormUniqueEmail class MyRegForm(RegistrationFormUniqueEmail): employer = forms.BooleanField() candidate = forms.BooleanField() regbackend.py from registration.backends.default.views import RegistrationView from .forms import MyRegForm from .models import UserSelection class MyRegistrationView(RegistrationView): form_class = MyRegForm def register(self, form_class): new_user = super(MyRegistrationView, self).register(form_class) p = form_class.cleaned_data['employer'] q = form_class.cleaned_data['candidate'] new_profile = UserSelection.objects.create(user=new_user, employer=p, candidate=q) new_profile.save() return new_user
answer count: 1
type: Question

http://stackoverflow.com/comment/85613496
score: 0
comment on: http://stackoverflow.com/q/49302716
type: Comment
type: QuestionComment
has text: As you said, if you correct `logging.error(err)` with `logger.error(err)` you get the correct output `__main__ - ERROR - It was a good attempt though`. I was able to reproduce your original issue, but I believe you forgot to mention that no output file is generated. The message you get `__main__-ERROR:root:It was a good attempt though` is within the command line. Still not sure why you get the message like that.

http://stackoverflow.com/a/49353804
has body: What you're trying to write doesn't work: with self.row_sess_context(dbid=relid) as row, sess: … because a with statement can take multiple context managers and bind each one's context value, so you're asking it to enter self.row_sess_context(dbid=relid) and bind its value as row, and enter sess and ignore its value. Since sess probably isn't a context manager, this is an error. But if you just parenthesize the unpackables, it does exactly what you want: with self.row_sess_context(dbid=relid) as (row, sess): Since it's impossible to demonstrate with your incomplete code fragment, here's a minimal example that anyone can run: import contextlib @contextlib.contextmanager def ctx(): yield (1, 2) with ctx() as (x, y): print(x, y)
has comment: http://stackoverflow.com/comment/85707909
answers question: http://stackoverflow.com/q/49353737
type: Answer
has comment: http://stackoverflow.com/comment/85707834
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85748730
type: QuestionComment
has text: But TLDs don't necessarily map to a country.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49373712

http://stackoverflow.com/q/49291317
tagged with: pandas
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85586049
has title: Aggregate over two columns in pandas
type: Question
has comment: http://stackoverflow.com/comment/85585402
has comment: http://stackoverflow.com/comment/85585421
answer count: 0
has body: I'm new to python and pandas and maybe i'm missing something. I have many columns in a dataframe with two important columns in particular: Weight and Volume. I want to create many clusters with the rows from the dataframe, with conditions: No cluster accumulate (summing) above 30000 Kg in weight. No cluster accumulate (summing) above 30 M^3 in volume. The cluster are as large as possible but bellow limits expressed in first two points. The resulting cluster for each row is annotated in a "cluster" column in the same dataframe. The algorithm is implemented in a procedural style, with nested loops. I'm reading about rolling and expanding functions in pandas, but i don't find a pandoric way (without loops?) to do that. Is there a way? Here is some code to help explaining me.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85585488
downvote count: 0
tagged with: cluster-analysis
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/49351496
tagged with: pandas
upvote count: 1
has body: I have a json file for tweet data. The data that I want to look at is the text of the tweet. For some reason, some of the tweets are too long to put into the normal text part of the dictionary. It seems like there is a dictionary within another dictionary and I can't figure out how to access it very well. Basically, what I want in the end is one column of a data frame that will have all of the text from each individual tweet. Here is a link to a small sample of the data that contains a problem tweet. Here is the code I have so far: import json import pandas as pd tweets = [] #This writes the json file so that I can work with it. This part works correctly. with open("filelocation.txt") as source for line in source: if line.strip(): tweets.append(json.loads(line)) print(len(tweets) df = pd.DataFrame.from_dict(tweets) df.info() When looking at the info you can see that there will be a column called extended_tweet that only encompasses one of the two sample tweets. Within this column, there seems to be another dictionary with one of those keys being full_text. I want to add another column to the dataframe that just has this information along with the normal text column when the full_text is null. My first thought was to try and read that specific column of the dataframe as a dictionary again using: d = pd.DataFrame.from_dict(tweets['extended_tweet]['full_text]) But this doesn't work. I don't really understand why that doesn't work as that is how I read the data the first time. My guess is that I can't look at the specific names because I am going back to the list and it would have to read all or none. The error it gives me says "KeyError: 'full_text' " I also tried using the recommendation provided by this website. But this gave me a None value no matter what. Thanks in advance! I tried to do what @Dan D. suggested, however, this still gave me errors. But it gave me the idea to try this: tweet[0]['extended_tweet']['full_text'] This works and gives me the value that I am…
has answer: http://stackoverflow.com/a/49351561
downvote count: 0
possible better answer: http://stackoverflow.com/a/49351561
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49409864
accepted answer: http://stackoverflow.com/a/49409864
has title: Reading a dictionary from within a dictionary
type: Question
answer count: 2

bdd
tag name: bdd
tags question: http://stackoverflow.com/q/49365580
type: Tag

http://stackoverflow.com/q/49336556
linked to: http://stackoverflow.com/q/588004
has body: I have a numpy structured array that looks like this: &gt;&gt;&gt; arr array([(b'00:59:59.785634', 60.87), (b'01:00:00.187634', 60.88), (b'01:00:00.188634', 60.88), ..., (b'23:59:58.668559', 60.93), (b'23:59:58.668559', 60.92), (b'23:59:58.668559', 60.93)], dtype=[('Date', 'S15'), ('Value', '&lt;f4')]) When I convert it to a pandas dataframe, The values of Value column change their form. &gt;&gt;&gt; df = pd.DataFrame( arr ) Date Value 0 b'00:59:59.785634' 60.869999 1 b'01:00:00.187634' 60.880001 2 b'01:00:00.188634' 60.880001 3 b'01:00:00.189634' 60.860001 4 b'01:00:00.190634' 60.860001 &gt;&gt;&gt; df.Value Name: Value, Length: 176195, dtype: float32 It's still OK, because it prints out the same value as the array. &gt;&gt;&gt; str( df['Value'][0] ) '60.87' But a problem occurs when I have done modifying the dataframe and try to convert the dataframe to an array again. &gt;&gt;&gt; new_arr = df.values array([[b'00:59:59.785634', 60.869998931884766], [b'01:00:00.187634', 60.880001068115234], [b'01:00:00.188634', 60.880001068115234], ..., [b'23:59:58.668559', 60.93000030517578], [b'23:59:58.668559', 60.91999816894531], [b'23:59:58.668559', 60.93000030517578]], dtype=object) &gt;&gt;&gt; str( new_arr[0][1] ) '60.869998931884766' # != '60.87' I think the original dtype(float32) is lost during the last conversion. How can I still get '60.87' even after converting the dataframe to an array with .values attribute? My question is why it prints out different results('60.87' and '60.869998931884766') and how to keep the type. I think if the values can be the same when converting an array to a dataframe, there should be some ways to preserve the values when converting them the other way around.
tagged with: pandas
answer count: 0
duplicate of: http://stackoverflow.com/q/588004
score: 0
has comment: http://stackoverflow.com/comment/85675648
has comment: http://stackoverflow.com/comment/85678218
type: Question
tagged with: numpy
has title: How to set dtypes when converting a dataframe to a numpy array?
has comment: http://stackoverflow.com/comment/85678188
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85728770
type: Comment
has text: col31 and col11 are the same. Sorry about the confusion
score: 0
comment on: http://stackoverflow.com/q/49363394
type: QuestionComment

http://stackoverflow.com/a/49393055
has comment: http://stackoverflow.com/comment/85790067
has body: You are using the vanilla range object in Python. It looks like you want to use the numpy.arange operation instead which creates a NumPy array for you. range does not give you what numpy.arange does. You need to change that statement to use arange: m=arange(row*col) The reason why PyCharm is probably giving you that error is because you are implicitly converting from one type to another. This is due to their type hinting mechanism so it's good practice to produce the expected output immediately when you produce the array with arange. However, this is quite superfluous as you are creating a row x col 2D array that is linearly increasing, but you end up replacing all of the elements anyway. Consider pre-allocating the matrix with numpy.zeros of the desired size instead: m = zeros((row, col)) Also, it is very bad practice to do this: from numpy import *. This is because you may be importing other packages that could share the same function names between packages. Unless you absolutely know that doing the above style of import won't provide any conflicts, I would not recommend you do this. Instead, import NumPy with the alias np as many people do so: import numpy as np After, call any NumPy functions by accessing np: import numpy as np row=int(input()) col=int(input()) m=np.range(row*col) m=np.reshape(m,(row,col)) # or: # m = np.zeros((row, col)) for i in range(0,row): for j in range(0,col): el=int(input()) m[i][j]=el
has comment: http://stackoverflow.com/comment/85790260
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49392087
answers question: http://stackoverflow.com/q/49392087
has comment: http://stackoverflow.com/comment/85790196
has comment: http://stackoverflow.com/comment/85789466
has comment: http://stackoverflow.com/comment/85789481
has comment: http://stackoverflow.com/comment/85789303
type: Answer

http://stackoverflow.com/a/49321151
has body: from binascii import unhexlify ciphertext_1 = "4A17" ciphertext_2 = "4710" xored = (int(ciphertext_1, 16) ^ int(ciphertext_2, 16)) # We format this integer: hex, no leading 0x, uppercase string = format(xored, 'X') # We pad it with an initial 0 if the length of the string is odd if len(string) % 2: string = '0' + string # unexlify returns a bytes object, we decode it to obtain a string print(unhexlify(string).decode()) # # Not much appears, just a CR followed by a BELL Or, if you prefer the repr of the string: print(repr(unhexlify(string).decode())) # '\r\x07'
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49320891
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49320891
has comment: http://stackoverflow.com/comment/85647303
score: 1
has comment: http://stackoverflow.com/comment/85650306

http://stackoverflow.com/comment/85961651
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49394526
has text: Have you tried RTLD_LOCAL? "Symbols exported from this image (dynamic library or bundle) are generally hidden and only availble to dlsym() when directly using the handle returned by this call to dlopen()."
type: Comment

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49370281
tags question: http://stackoverflow.com/q/49324886

http://stackoverflow.com/comment/85839841
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49418797
has text: Thanks for your answer, my problem is in merge. In my case the merge takes a lot of time to execute (avg: 5hours) Then I want to optimize it. I tried your code works perfectly with a small dataset.
type: AnswerComment

http://stackoverflow.com/comment/85867181
has text: @AlexeyTrofimov have you considered using HDF5? I regularly use this with the `pandas` implementation via `pytables`. Some information and other formats can be found in the `pandas` docs [here](http://pandas.pydata.org/pandas-docs/stable/io.html)
comment on: http://stackoverflow.com/q/49430747
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49377120
has comment: http://stackoverflow.com/comment/85765793
type: Answer
answers question: http://stackoverflow.com/q/49376997
has comment: http://stackoverflow.com/comment/85755427
downvote count: 0
score: 1
upvote count: 1
has body: You can set initial values to None for the function arguments like below: def custom_mean(x=None, y=None): # if either of x or y is None, return the mean of whole column if x is None or y is None: return df['Test 1'].mean() # otherwise, filter and get mean return df.loc[df['Time'].between(x,y), 'Test 1'].mean() &gt;&gt;&gt; custom_mean() 5.384615384615385 &gt;&gt;&gt; custom_mean(x=0.0, y=2.05) 5.0 &gt;&gt;&gt; custom_mean(x=0.0, y=0.6) 6.0

http://stackoverflow.com/q/49394900
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35642322
downvote count: 1
linked to: http://stackoverflow.com/q/48267331
favorite count: 0
type: Question
tagged with: pyinstaller
has body: I have a problem in an app I created using PyInstaller. I want to create a report on excel using openpyxl, then I save it in a directory I choose using tkinter.filedialog.askdirectory() comand. Everything works perfectly when I run the code from Spyder, but when I create an .exe app using PyInstaller it all runs correctly until the line where the excel file is saved, import tkinter.filedialog as filedialog import os import openpyxl as opxl wk = opxl.Workbook() ... #More code ... file = 'Report.xlsx' #If I comment the next two lines, there is no Error in the .exe app root = filedialog.askdirectory(title='Where do you want to save '+file+'?') file = os.path.join(root, file) wk.save(file) #Here is where the error is raised where a PermissionError [Errno 13] is raised. The funny thing is that I don't have this issue if the tkinter command isn't used and the file is saved in the same directory where the .exe file is. My pyinstaller command was: pyinstaller --onedir --onefile --name "C:\\blablabla" "root\\my_code.py" My spec file is: # -*- mode: python -*- block_cipher = None a = Analysis(['root\\my_code.py'], pathex=['C:\\blablabla'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='exe_file_name', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) I have seen other people having this kind of issue and it looks that it is a Windows problem, but I haven't found an useful answer so far: App Packaged With Pyinstaller Loses Write Permissions Update: I tried adding the option "--uac-admin", but it neither works. I have the suspicion I need to add a manifest, but not 100% sure nor how to create it. Thanks beforehand.
score: 1
tagged with: python
has title: How can I solve a PermissionError, raised when I save a file using PyInstaller in a given directory?

google-translate
tags question: http://stackoverflow.com/q/49319836
tag name: google-translate
type: Tag
tags question: http://stackoverflow.com/q/49339541

http://stackoverflow.com/q/49327771
possible better answer: http://stackoverflow.com/a/49353443
has body: I am looking for a function in pandas that aligns data wrt to a different columns. For example, I have four columns, two times and two are identifiers. id time id time a , 1:10, a , 1:11 a , 1:12 , a , 1:13 b , 1:13 c , 1:15 c , 1:14 d , 1:15 I would like to match the rows with id c to each other and get the following: id time id time a , 1:10, a , 1:11 a , 1:12, a , 1:13 b , 1:13, NaN, NaN c, 1:14, c , 1:15 d , 1:15, NaN, NaN I have my data in a dataframe with respective labels. I have tried loops to find matches and reindexing, but run into errors. I can potentially have thousands of entries, with numerous missing points. A = pd.DataFrame({'Error Time':array1[:,0],'Err ID':array1[:,1],'Alert Type':array1[:,2]}) B = pd.DataFrame({'Recover Time':array2[:,0], 'Rec ID':array2[:,1]}) data_array = pd.concat([A,B], axis=1) #Joins the two arrays together pd.to_datetime(data_array['Error Time'],format='%H:%M:%S.%f').dt.time pd.to_datetime(data_array['Recover Time'],format='%H:%M:%S.%f').dt.time #data_array = data_array.sort_values(by=['Error Time']) col_size = len(data_array['Error Time']) for i in range(col_size): if data_array.iloc[i,1] == data_array.iloc[i,3]: indexA.append(i) else: for j in range(col_size): if data_array.iloc[i,1] == data_array.iloc[j,3]: if indexA.count(j) &gt; 0: j = j + 1 else: indexA.append(j) break for k in range(col_size): if indexA.count(k)== 0: indexA.append(k) data_array = data_array.reindex(['Error Time', 'Error ID', 'Alert Type],index=[indexA])
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49365949
answer count: 2
has answer: http://stackoverflow.com/a/49365949
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Is there a function in pandas to align rows with matching identifiers and fill voids with NaN?
has answer: http://stackoverflow.com/a/49353443
tagged with: python
has comment: http://stackoverflow.com/comment/85657569

http://stackoverflow.com/comment/85655066
comment on: http://stackoverflow.com/a/49326252
score: 0
type: AnswerComment
has text: With those quads isolated how might I populate different shapes into just those regions?
type: Comment

http://stackoverflow.com/a/49365953
score: 1
has comment: http://stackoverflow.com/comment/85732626
has body: Python 3.x is not nesscarily backward compatible. For instance in python 3.6, string interpolation was introduced, aka f-string. In python 3.5 type hints were introduced which would not be backwards compatible with older 3.x versions.
type: Answer
has comment: http://stackoverflow.com/comment/85732871
upvote count: 4
answers question: http://stackoverflow.com/q/49365864
downvote count: 3

http://stackoverflow.com/q/49287132
has body: I am trying to find the presence of a string pattern like '/*' in a string using python . I tried a code snippet like the following : strk = "*\" if strk in num print ("here it is") But at the first line Ii got an error stating : syntax error : "EOL while scanning string literal . How to make the interpreter distinguish between "\" used as a string element and "\" as the newline character ? I. .being inspired by the following link, tried using strk = "*(\)" But this didn't work . http://python-reference.readthedocs.io/en/latest/docs/str/escapes.html
type: Question
upvote count: 0
possible better answer: http://stackoverflow.com/a/49287186
tagged with: python
has answer: http://stackoverflow.com/a/49287186
downvote count: 1
has answer: http://stackoverflow.com/a/49287299
has comment: http://stackoverflow.com/comment/85577444
favorite count: 0
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/49287305
has title: searching for a "\*" in a string
has answer: http://stackoverflow.com/a/49287305
has comment: http://stackoverflow.com/comment/85577383
score: -1
has comment: http://stackoverflow.com/comment/85577650

http://stackoverflow.com/q/49437764
has comment: http://stackoverflow.com/comment/85880279
type: Question
score: 0
has body: I'm trying to install Plotly through pip, and I'm unable to install the Plotly packaging in particular. I get the following error: C:\Python 3.6&gt;python -m pip show SetupTools Name: setuptools Version: 39.0.1 Summary: Easily download, build, install, upgrade, and uninstall Python packages Home-page: https://github.com/pypa/setuptools Author: Python Packaging Authority Author-email: distutils-sig@python.org License: UNKNOWN Location: c:\python 3.6\lib\site-packages Requires: C:\Python 3.6&gt;python -m pip install Plotly Collecting Plotly Using cached plotly-2.5.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'setuptools' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\rskin\AppData\Local\Temp\pip-build-uw5jnlnh\Plotly\ I'm using Python 3.6 and both pip and setuptools are installed and up-to date. I'm able to install other Python packages with no issues. I think it may have soemthing to do with the location of my Python 3.6 file, but I'm not exactly sure Any ideas?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85880487
answer count: 1
tagged with: pip
has title: Can't Find SetupTools -
has answer: http://stackoverflow.com/a/74236000
has comment: http://stackoverflow.com/comment/85878442
tagged with: plotly
tagged with: python
has comment: http://stackoverflow.com/comment/85911099

http://stackoverflow.com/comment/85765533
score: 1
type: Comment
has text: Please, read [MCVE](https://stackoverflow.com/help/mcve)
type: QuestionComment
comment on: http://stackoverflow.com/q/49381342

http://stackoverflow.com/q/49391076
upvote count: 1
tagged with: python
has body: I am familiar with the recursive function of the Hanoi Tower. Now I need to visualize the movements, representing the discs with asterisks (I guess disc number = number of asterisks makes sense). Does anyone have a hint or example for how to draw the disc movements step by step using just * *** *** ***** ***** * -------------------- ----------------------- ... or similar? This is the sample code my professor provided and I do understand how the recursion works. But after one lecture in Python I must say that I'm somewhat overwhelmed with the visualization task. def hanoi(n, p1, p2, p3): if n==1: print("move from %d to %d" %(p1, p3)) else: hanoi(n-1, p1, p3, p2) print("move from %d to %d " %(p1, p3)) hanoi(n-1, p2, p1, p3) return if __name__=='__main__': j=int(input('Input the number of disk to be moved:\n')) print('Number of disk to be move is %d \n'%j) hanoi(j, 1, 2, 3) Help would be much appreciated!
tagged with: towers-of-hanoi
has title: Illustrate Tower of Hanoi with ASCII
type: AnsweredQuestion
tagged with: recursion
tagged with: visualization
accepted answer: http://stackoverflow.com/a/49393320
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49393320
favorite count: 0
type: Question
tagged with: ascii
has comment: http://stackoverflow.com/comment/85784940
downvote count: 0

http://stackoverflow.com/comment/85922168
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49419788
has text: the network is not pre-trained I will hopefully be training it with the png files if I can figure out how to get them into python

http://stackoverflow.com/a/51139867
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49286741
type: AcceptedAnswer
has body: In my case I had to avoid importing : import matplotlib.pyplot as plt fig,ax = plt.subplots(figsize=(8,9)) l = plt.plot(x,s, 'y-', label="line") and substitute it with: from matplotlib.figure import Figure fig = Figure() ax = fig.add_subplot(111)) l = ax.plot(x,s, 'y-', label="line")
accepted answer of: http://stackoverflow.com/q/49286741
type: Answer

http://stackoverflow.com/comment/85857042
has text: For general case, the `True` might occur in more than 2 dimension.
type: QuestionComment
comment on: http://stackoverflow.com/q/49427866
type: Comment
score: 0

http://stackoverflow.com/comment/85572542
comment on: http://stackoverflow.com/a/49283854
has text: @qfd yw：-） happy coding
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49422798
type: AcceptedAnswer
has body: For me working: df['last_2'] = (df.sum(axis=1).rolling(window=2, min_periods=1).sum() / df.count(axis=1).rolling(window=2, min_periods=1).sum()) print (df) a001 a002 last_2 0 1.0 1.0 1.000000 1 NaN 7.0 3.000000 2 NaN NaN 7.000000 3 NaN 3.0 3.000000 4 NaN NaN 3.000000 5 2.0 2.0 2.000000 6 NaN 6.0 3.333333
accepted answer of: http://stackoverflow.com/q/49422329
has comment: http://stackoverflow.com/comment/85846272
type: Answer
has comment: http://stackoverflow.com/comment/85846263
downvote count: 0
answers question: http://stackoverflow.com/q/49422329
score: 1
upvote count: 1

http://stackoverflow.com/comment/85676147
comment on: http://stackoverflow.com/q/49336415
score: 0
type: QuestionComment
type: Comment
has text: With this code, you will be getting output `red pressed` every 0.3 seconds without pressing the button

http://stackoverflow.com/comment/85834531
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49414987
has text: I mean you could just not do the work, and that's probably the most clever thing you could do; and something my co-workers often try to pull. But don't be that guy ;-)

http://stackoverflow.com/comment/85866799
type: QuestionComment
has text: I have never used the debugger. After reading up on it and messing around I cannot quite figure it out. I tried python -m pdb script.py and hitting 'n' to step my way through but it just gets stuck on one line and idk why, and I'm not sure which other methods to try. I'm looking what neeraj dixit mentioned now
score: 0
comment on: http://stackoverflow.com/q/49428431
type: Comment

http://stackoverflow.com/q/49347864
score: 0
accepted answer: http://stackoverflow.com/a/49350502
tagged with: dataframe
has answer: http://stackoverflow.com/a/49350502
has comment: http://stackoverflow.com/comment/85696166
type: Question
answer count: 2
has title: Python Pandas Dataframe: based on DateTime criteria, I would like to populate a dataframe with data from another dataframe
has answer: http://stackoverflow.com/a/49348500
tagged with: python
has body: I have created a simple dataframe,"F_test". I would now like to populate another dataframe,"P", with data from "F_test" based on whether the cell in "P" lies in the same row as "F_test" and is inbetween the startdates/enddates for that row. However, when I execute a simple For Loop to do this, after the first row, no other data is updated in the "P" matrix. In the code on my PC, I actually extract "F_test" data from an Excel File, but for the purposes of giving a complete dataset on this forum, I have manually created the simple dataframe, named "F_test". As you may be able to tell from the code, I am a recent convert from the Matlab/VBA Excel world... I would really appreciate your wisdom on this topic. F0 = ('08/02/2018','08/02/2018',50) F1 = ('08/02/2018','09/02/2018',52) F2 = ('10/02/2018','11/02/2018',46) F3 = ('12/02/2018','16/02/2018',55) F4 = ('09/02/2018','28/02/2018',48) F_mat = F0,F1,F2,F3,F4 F_test = pd.DataFrame(np.array(F_mat).reshape(5,3),columns= ('startdate','enddate','price')) #convert string dates into DateTime data type F_test['startdate'] = pd.to_datetime(F_test['startdate']) F_test['enddate'] = pd.to_datetime(F_test['enddate']) #convert datetype to be datetime type for columns startdate and enddate F['startdate'] = pd.to_datetime(F['startdate']) F['enddate'] = pd.to_datetime(F['enddate']) #create contract duration column F['duration'] = (F['enddate'] - F['startdate']).dt.days + 1 #re-order the F matrix by column 'duration', ensure that the bootstrapping #prioritises the shorter term contracts F.sort_values(by=['duration'], ascending=[True]) #create D matrix, dataframe containing each day from start to end date tempDateRange = pd.date_range(start=F['startdate'].min(), end=F['enddate'].max(), freq='D') D = pd.DataFrame(tempDateRange) #define Nb of Calendar Days in a variable to be used later intNbCalendarDays = (F['enddate'].max() - F['startdate'].min()).days + 1 #define Nb of Contracts in a variable to be used later intNbContracts = len(F) #…
type: AnsweredQuestion
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49348500

http://stackoverflow.com/q/49301732
type: AnsweredQuestion
tagged with: python-2.7
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Python-Child class triggers parent
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85621369
accepted answer: http://stackoverflow.com/a/49309900
has answer: http://stackoverflow.com/a/49309900
has comment: http://stackoverflow.com/comment/85620528
tagged with: python
has body: I need to modify a declared object on parent from child object in python. I know that in java is possible to modify a parent object from a child by passing the parent as parameter when initializing the child object. I dont need to inherit everything from parent to child, I just need the child to show and hide frames declared on parent. For example in Java. public class Parent(){ public Child1 objtchild1; public Parent(){ ] Child2 panel = new Child2(this); Child1 objtchild1 = new Child1(); } public class Child1 (){ public int var = 1; } public class Child2 () { private Parent parent; public Child(Parent parent) { this.parent = parent; parent.objtchild1.var=2;//Modify parent child object } I want to apply Model view controller where the view interact with the controller. Just like in the following url but in python. MVC codeprojects.com example Is the example above on Java possible in python?
has comment: http://stackoverflow.com/comment/85619966
has comment: http://stackoverflow.com/comment/85606195
has comment: http://stackoverflow.com/comment/85606085

http://stackoverflow.com/comment/85610103
has text: `df.groupby(pd.Grouper(freq='1M')).prod().tail(12).prod()` instead of `df.tail(12).prod()` should work but this would give you `inf` because the product is a large number.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49300590

http://stackoverflow.com/comment/85724203
type: Comment
score: 0
has text: @DanielRoseman Alright have all the code...
type: QuestionComment
comment on: http://stackoverflow.com/q/49362030

http://stackoverflow.com/q/49327879
type: Question
has body: I just installed tensorflow using the instructions for the virtualenv method. The installation process went smoothly, so I don't think there was any problem there. After installation I proceeded to try and import it to validate that everything is ok, and I got the following message: [1] 4492 illegal hardware instruction (core dumped) python This happened after I use the following command using th python interactive console: import tensorflow as tf I tried using the link with pip to reinstall it, but no success. I have created the virtualenv with: python3.6 -m venv venv After this didn't work (as in it generated the same error) I tried with: virtualenv --system-site-packages -p python3.6 venv I got the same result. The command I used to install tensorflow was: pip install tensorflow As you can see, I intend to install the CPU-only version. I read some think about other frameworks and technologies that show this message em the hardware does not have the instruction implemented, so there's nothing to do about that except getting new hardware. Is there any way to fix this issue? I already tried some different installation methods, but none of then seen to work As for the system specifications: OS = Ubuntu 16.04 x64 LTS Python = Python 3.6 pip version = 9.0.1 tensorflow version = TensorFlow 1.6.0 CPU = Intel Core 2 Quad Q6600 @2.40GHz OBS: I do have a GPU on this machine, but I don't think that tensorflow will run on it, since it is kind of old. It's a Nvidia 8800 GTS 512. I appreciate any help, and if there's any missing info, please let me know.
has comment: http://stackoverflow.com/comment/85659924
has comment: http://stackoverflow.com/comment/85660875
tagged with: python
tagged with: python-3.6
tagged with: illegal-instruction
score: 2
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/49388337
has title: Illegal hardware instruction when trying to import tensorflow
answer count: 1
tagged with: virtualenv
has answer: http://stackoverflow.com/a/49388337
downvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/85737625
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49368137
score: 0
has text: Just tried I got this. [link](https://prnt.sc/itdgor) but I need the one like I mentioned in top. Your advice welcome

http://stackoverflow.com/a/49438521
answers question: http://stackoverflow.com/q/49438421
has comment: http://stackoverflow.com/comment/85879067
has comment: http://stackoverflow.com/comment/85879058
has comment: http://stackoverflow.com/comment/85881655
type: Answer
has comment: http://stackoverflow.com/comment/85882535
has body: It is likely that mod_wsgi Apache is using is compiled for Python 2.6. You cannot make mod_wsgi compiled for Python 2.6, work with a Python 2.7 installation or virtual environment. You should verify what Python version mod_wsgi was compiled for by running ldd on the mod_wsgi.so binary. Don't assume it is using the pip installed version, you may still have system mod_wsgi installed. If it is the system mod_wsgi package and it is compiled for Python 2.6, you will need to uninstall it.
score: 0

http://stackoverflow.com/a/49439358
answers question: http://stackoverflow.com/q/49439314
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: The package name is "PyMySQL"; you use the package name to install it. To use the installed package, you need to use the module name, which may not be the same. In this case, the module is named "pymysql" (all lower-case). The import should be import pymysql. https://pymysql.readthedocs.io/en/latest/py-modindex.html
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49439314

http://stackoverflow.com/q/49308718
tagged with: list
has comment: http://stackoverflow.com/comment/85619734
has body: I am trying to figure out if an input list is a strictly increasing list. Moreover, If removing only one element from the list results in a strictly increasing list, we still consider the list true. Here is my code. It seems to have an index error, but I do not understand why. def almostIncreasingSequence(sequence): n=len(sequence) count=0 if n&lt;=2: return True for i in range (n-1): #test if the i-th element is bigger or equal to the elements after it. If it is, remove that element, and add one to count for j in range (i+1,n): if sequence[i]&gt;=sequence[j]: sequence.pop(i) count+=1 #if there is more than one element that has to be taken out, it's false if count&gt;1: return False return True
has answer: http://stackoverflow.com/a/49310554
has comment: http://stackoverflow.com/comment/85619908
downvote count: 0
has comment: http://stackoverflow.com/comment/85619996
has comment: http://stackoverflow.com/comment/85619957
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49310554
has comment: http://stackoverflow.com/comment/85619738
has comment: http://stackoverflow.com/comment/85619834
has answer: http://stackoverflow.com/a/49308968
has answer: http://stackoverflow.com/a/49308849
tagged with: python
has title: Determine if the input list is strictly increasing
has comment: http://stackoverflow.com/comment/85620026
score: 4
accepted answer: http://stackoverflow.com/a/49308967
answer count: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49308967
type: AnsweredQuestion

http://stackoverflow.com/comment/85762583
comment on: http://stackoverflow.com/q/49359479
has text: Finally, what is actually your problem? You are still not fitting anything.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49439008
downvote count: 0
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49439315
tagged with: lxml
has title: Creating an XML File from a dataframe using Python and LXML
has body: I'm trying to create an XML file that uses a Pandas dataframe to populate the elements and subelements. Here is the code I have written: import pandas as pd from lxml import etree as et df = pd.DataFrame({'id_profile': [439, 444654, 56454, 12222], 'ServiceDate': ['2017-12-05', '2017-01-25', '2017-12-05', '2017-01-25'], 'PrimaryServiceCategory': [25, 25, 33, 25]}) root = et.Element('ClientReport') idnum = et.SubElement(root, 'ID') prime_serv = et.SubElement(root, 'ServiceCategory') serv_date = et.SubElement(root, 'ServiceDate') for row in df.iterrows(): idnum.text = df['id_profile'] prime_serv.text = df['PrimaryServiceCategory'] serv_date.text = df['ServiceDate'] print(et.tostring(root, pretty_print=True)) My expected outcome is: 439 25 2017-12-05 444654 25 2017-01-25 12222 25 2017-01-25 Instead, I get: TypeError: Argument must be bytes or unicode, got 'Series' I'm not sure how to get iterated rows, rather than a static value, to populate the XML file's attributes. Is Pandas the right package here? And is LXML the right one as well?
has comment: http://stackoverflow.com/comment/118075282
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18574108
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49439315
upvote count: 3
answer count: 1

http://stackoverflow.com/a/49300874
type: Answer
has comment: http://stackoverflow.com/comment/85603957
answers question: http://stackoverflow.com/q/49300784
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: I think need: np.random.seed(456) a = [] for i in range(5): tmp_df = pd.DataFrame(np.random.random((10,4))) tmp_df['lvl'] = i a.append(tmp_df) df = pd.concat(a, axis=0) #print (df) df1 = (df[df.lvl ==0 ] + df[df.lvl ==1 ] + df[df.lvl ==2 ] + df[df.lvl ==3 ] + df[df.lvl ==4 ]) / 5 print (df1) 0 1 2 3 lvl 0 0.411557 0.520560 0.578900 0.541576 2 1 0.253469 0.655714 0.532784 0.620744 2 2 0.468099 0.576198 0.400485 0.333533 2 3 0.620207 0.367649 0.531639 0.475587 2 4 0.699554 0.548005 0.683745 0.457997 2 5 0.322487 0.316137 0.489660 0.362146 2 6 0.430058 0.159712 0.631610 0.641141 2 7 0.399944 0.511944 0.346402 0.754591 2 8 0.400190 0.373925 0.340727 0.407988 2 9 0.502879 0.399614 0.321710 0.715812 2 df = df.set_index('lvl') df2 = df.groupby(df.groupby('lvl').cumcount()).mean() print (df2) 0 1 2 3 0 0.411557 0.520560 0.578900 0.541576 1 0.253469 0.655714 0.532784 0.620744 2 0.468099 0.576198 0.400485 0.333533 3 0.620207 0.367649 0.531639 0.475587 4 0.699554 0.548005 0.683745 0.457997 5 0.322487 0.316137 0.489660 0.362146 6 0.430058 0.159712 0.631610 0.641141 7 0.399944 0.511944 0.346402 0.754591 8 0.400190 0.373925 0.340727 0.407988 9 0.502879 0.399614 0.321710 0.715812 EDIT: If each subset of DataFrame have index from 0 to len(subset): df2 = df.mean(level=0) print (df2) 0 1 2 3 lvl 0 0.411557 0.520560 0.578900 0.541576 2 1 0.253469 0.655714 0.532784 0.620744 2 2 0.468099 0.576198 0.400485 0.333533 2 3 0.620207 0.367649 0.531639 0.475587 2 4 0.699554 0.548005 0.683745 0.457997 2 5 0.322487 0.316137 0.489660 0.362146 2 6 0.430058 0.159712 0.631610 0.641141 2 7 0.399944 0.511944 0.346402 0.754591 2 8 0.400190 0.373925 0.340727 0.407988 2 9 0.502879 0.399614 0.321710 0.715812 2
accepted answer of: http://stackoverflow.com/q/49300784

http://stackoverflow.com/q/49353243
favorite count: 0
has answer: http://stackoverflow.com/a/59541568
has comment: http://stackoverflow.com/comment/85707502
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85710583
has answer: http://stackoverflow.com/a/70664118
tagged with: scikit-learn
tagged with: python
answer count: 4
has title: XGBoost can't find sklearn
has comment: http://stackoverflow.com/comment/85706746
has answer: http://stackoverflow.com/a/50034026
score: 3
has answer: http://stackoverflow.com/a/66929802
upvote count: 3
downvote count: 0
has body: I’m experimenting with XGBoost and am blocked by an error I can’t figure out. I have sklearn installed in the active environment and can verify it by training a sklearn RandomForestClassifier in the same notebook. When I try to train a XGBoost model I get the error XGBoostError: sklearn needs to be installed in order to use this module This works: clf = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1) This throws the exception: clf = xgb.XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05).fit(train_X, train_y) UPDATE: Created a PyCharm module with exactly the same code and imports and it executed without an exception. So this appears to be a Jupyter Notebook issue. PyCharm is pointed to the same Anaconda environment as the notebook. UPDATE 2: Created a new notebook and copied the code from the one that was throwing the exception. The code runs OK in the new notebook. Sigh. Case closed.
tagged with: xgboost

http://stackoverflow.com/comment/85787299
has text: Sure, I am using Python 3.6.4 and Pandas 0.22
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49372599
type: Comment

http://stackoverflow.com/q/49373712
type: Question
has comment: http://stackoverflow.com/comment/85748767
has comment: http://stackoverflow.com/comment/85749057
has comment: http://stackoverflow.com/comment/85748786
tagged with: python
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85748730
type: UnansweredQuestion
has title: Get country for a given ccTLD
downvote count: 0
has body: Assuming I have a tld extracted as: ext = tldextract.extract(item.get("google.co.uk")) print(magic_func(ext.suffix)) &gt; United Kingdoms How can I achieve this magic_func functionality without querying DBPedia/Wikipedia etc.? I am only interested in country tlds. Edit: Querying the web is quite costly for me as I may have millions of cctlds to check!
has comment: http://stackoverflow.com/comment/85748773
favorite count: 0

http://stackoverflow.com/q/49408445
has comment: http://stackoverflow.com/comment/85864109
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85860577
has comment: http://stackoverflow.com/comment/85864426
downvote count: 5
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/85818355
has body: I am using the following piece of code in Python 3.6: age = 65 retirement = age - 64 if retirement &lt; 10: print "(you will get retire soon)" else: Syntax Error: invalid syntax I tried several different ways in an if-else statement but it still does not work. Does anyone know a way for the program to detect the errors for me? Thanks.
tagged with: python
has title: Syntax error in if-else statement
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/85818134
has comment: http://stackoverflow.com/comment/85860524
has answer: http://stackoverflow.com/a/49408701
upvote count: 1
has comment: http://stackoverflow.com/comment/85818137

http://stackoverflow.com/a/49364863
downvote count: 0
has comment: http://stackoverflow.com/comment/85730208
type: AcceptedAnswer
has body: If you are using the venv module there is --system-site-packages flag that will grant the created virtual environment access to the system-wide site-packages directory: --system-site-packages Give the virtual environment access to the system site-packages dir.
accepted answer of: http://stackoverflow.com/q/49364776
answers question: http://stackoverflow.com/q/49364776
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/comment/85933447
type: AnswerComment
comment on: http://stackoverflow.com/a/49462054
has text: Thank you so much for your help. I can't thank enough
type: Comment
score: 0

http://stackoverflow.com/q/49333795
type: AnsweredQuestion
has title: Why arr[idx,:] (for 2D arrays) considered a good methodology
has answer: http://stackoverflow.com/a/49333905
tagged with: python
accepted answer: http://stackoverflow.com/a/49333905
has body: A lot of python snippets using numpy are using arr[idx,:] notation when the array is 2D. e.g gradPred = -outputVectors[target,:] * (1 - r_W_prob[target]) gradPred += np.dot(r_W_prob[negative_samples], outputVectors[negative_samples, :]) I have two followup questions: a) Is there a difference betwenn outputVectors[target,:] and just outputVectors[target]? b) If there is a difference, Is there a "prefered way" to operate, or it's context dependent? Thanks!
tagged with: numpy
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85669253
answer count: 1
downvote count: 1
tagged with: arrays
favorite count: 0
type: Question

http://stackoverflow.com/q/49320158
has answer: http://stackoverflow.com/a/49364227
has body: I'm trying to connect celery with a rabbitMQ broker using SSL certificates. This is the code: from celery import Celery import ssl broker_uri = 'amqp://user:pwd@server:5672/vhost' certs_conf = { "ca_certs": "/certs/serverca/cacert.pem", "certfile": "/certs/client/rabbit-cert.pem", "keyfile": "/certs/client/rabbit-key.pem", "cert_reqs": ssl.CERT_REQUIRED } app = Celery('tasks', broker=broker_uri) app.conf.update(BROKER_USE_SSL=certs_conf) app.send_task('task.name', [{'a': 1}]) When I try to execute this code i get the following exception: Traceback (most recent call last): File "C:\Python36\lib\site-packages\kombu\utils\functional.py", line 36, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test_send_task.py", line 44, in &lt;module&gt; app.send_task('task.name', [message]) File "C:\Python36\lib\site-packages\celery\app\base.py", line 737, in send_task amqp.send_task_message(P, name, message, **options) File "C:\Python36\lib\site-packages\celery\app\amqp.py", line 558, in send_task_message **properties File "C:\Python36\lib\site-packages\kombu\messaging.py", line 181, in publish exchange_name, declare, File "C:\Python36\lib\site-packages\kombu\connection.py", line 494, in _ensured return fun(*args, **kwargs) File "C:\Python36\lib\site-packages\kombu\messaging.py", line 187, in _publish channel = self.channel File "C:\Python36\lib\site-packages\kombu\messaging.py", line 209, in _get_channel channel = self._channel = channel() File "C:\Python36\lib\site-packages\kombu\utils\functional.py", line 38, in __call__ value = self.__value__ = self.__contract__() File "C:\Python36\lib\site-packages\kombu\messaging.py", line 224, in &lt;lambda&gt; channel = ChannelPromise(lambda: connection.default_channel) File "C:\Python36\lib\site-packages\kombu\connection.py", line 819, in default_channel self.ensure_connection()…
score: 0
answer count: 3
has title: How to connect celery to rabbitMQ using SSL
has comment: http://stackoverflow.com/comment/86640840
has answer: http://stackoverflow.com/a/60837022
tagged with: celery
has answer: http://stackoverflow.com/a/59634788
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: rabbitmq

http://stackoverflow.com/q/49310014
has comment: http://stackoverflow.com/comment/85626814
tagged with: django
has answer: http://stackoverflow.com/a/49314124
answer count: 1
has comment: http://stackoverflow.com/comment/85626519
has comment: http://stackoverflow.com/comment/85626766
has title: parse uploaded file to another format before saving it in django
has comment: http://stackoverflow.com/comment/85626279
has comment: http://stackoverflow.com/comment/85626701
type: Question
has comment: http://stackoverflow.com/comment/85626564
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85626715
has body: I am trying to upload csv file and then parse to xml format but before saving it "import csv file and save it as xml file" I have got the uploading functionality working fine and be saved correctly; however, my issue is how to pass the uploaded file to the function where it is parsed to xml format. I am using django python Model.py from django.db import models from django.urls import reverse from .validators import validate_file_extension # Create your models here. class DataFile(models.Model): title = models.CharField(max_length=250) description = models.CharField(max_length=1000) file = models.FileField() def __str__(self): return self.title + ' - ' + self.description + ' - ' + self.file and here is my form.py from django import forms from .models import DataFile class FileForm(forms.ModelForm): class Meta: model = DataFile fields = ['title', 'description', 'file' ] here is my view.py def importing(request): form = FileForm(request.POST or None) if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): #here is where the passing supose to be form = csv2xml(request.FILES['file']) form.save() return HttpResponseRedirect('http://127.0.0.1:8000') return render(request, 'import.html', { 'form': form }) UPDATE: function that i want to pass my uploaded file to: def csv2xml(csv_file): xml = dicttoxml.dicttoxml(csv_file) return xml I want the file to be passed to csv2xml function, converted, and then save it as xml When I use the above way to pass it to the function it says: AttributeError at /importing 'InMemoryUploadedFile' object has no attribute 'save'
score: 0

http://stackoverflow.com/q/49378987
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85766582
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85763769
tagged with: selenium
has title: Available element not found in selenium
has comment: http://stackoverflow.com/comment/85767071
has answer: http://stackoverflow.com/a/49379218
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85769571
has body: I have a very complex and non public selenium script to perform GUI tests. When running the tests locally everything works fine. But when I run the exact same tests inside a docker image (used on jenkins), the tests do not run through. An element is not found in the webpage. The following is a part where I wait for an input box to appear and to fill in some text: self._handler.log("B") elem = WebDriverWait(self._handler.webdriver, 30).\ until(EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='Create new collab']"))) # TIMEOUT self._handler.log("C") elem.clear() self._handler.log("D") elem.send_keys(collab_name) I get a timeout error in the WebDriverWait line. I save the page source in the log step (just before the WebDriverWait line), and see the following part in the html: &lt;div class="md-tab container-centered" id="create" style="width: 988px; left: 988px;"&gt; &lt;div class="md-input-container md-theme-default md-input-placeholder md-input-focused"&gt; &lt;label&gt; Collab Name &lt;/label&gt; &lt;input class="md-input" placeholder="Create new collab" type="text"/&gt; &lt;!-- --&gt; &lt;!-- --&gt; &lt;!-- --&gt; &lt;/div&gt; So the element is available in the page source, and visible as well (as the following screenshot made at step 'B' reveals): What is going on? A bug in selenium? Addendum What I tried as well is the following chain: elem = WebDriverWait(self._handler.webdriver, 30).\ until(EC.presence_of_element_located((By.XPATH, "//div[@id='create']//input"))) actions = ActionChains(self._handler.webdriver) actions.move_to_element(elem) actions.send_keys(collab_name) actions.perform() But in this case the input field is not populated by the text in collab_name. The input field stays empty.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85765570
has comment: http://stackoverflow.com/comment/85765713
has comment: http://stackoverflow.com/comment/85767635

http://stackoverflow.com/a/49414518
type: Answer
has comment: http://stackoverflow.com/comment/85830750
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85830639
score: 2
answers question: http://stackoverflow.com/q/49414401
has body: Correct: that merge won't do what you want. You have accumulation to do multiple levels down. I suspect that the easiest way for you to get what you want -- merging at unspecified (arbitrary) depth -- is to write a recursive routine to do the merge you want. def dict_merge(d1, d2): for key in d1: if key in d2: one_merge = dict_merge(d1[key], d2[key]) else: one_merge = d1[key] for ... # also pick up keys in d2 that are not in d1. I'll leave it to you whether to handle this logic with set intersection and difference.

http://stackoverflow.com/comment/85814534
type: AnswerComment
comment on: http://stackoverflow.com/a/49406733
score: 0
has text: "balanced". (4 more to go)
type: Comment

http://stackoverflow.com/comment/85825901
type: Comment
comment on: http://stackoverflow.com/a/49411641
type: AnswerComment
score: 0
has text: they should use `==` not `is`

http://stackoverflow.com/comment/85623561
score: 0
has text: OK, so it sounds like an archive is simply a copy of a file, stored in another S3 location. AWS SDKs support a 'copy object' operation that you can use to copy an object. There's no need for you to download the object and re-upload it. You should think carefully about how you intend to provide a link to this archived object to the user. Unless they can authenticate as an AWS user, you need a more sophisticated solution because the standard candidates (publicly-accessible object ir pre-signed URL) won't work for you.
comment on: http://stackoverflow.com/q/49309147
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49303034
answers question: http://stackoverflow.com/q/49298768
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49298768
score: 1
type: Answer
has body: You call it Event Hubs but it's actually a Service Bus Queue. They are distinct services. Event Hubs have no queues. The error message is quite clear I think: the shared access policy that you are using has permissions for Send and Listen, but no Manage permission which is required to create Service Bus queues.
type: AcceptedAnswer

http://stackoverflow.com/q/49324024
tagged with: python-3.x
tagged with: comtypes
has title: Python + Access via pyodbc: Unable to open registry key Temporary (volatile), etc
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/39995802
has comment: http://stackoverflow.com/comment/85652105
has comment: http://stackoverflow.com/comment/85684148
tagged with: python
tagged with: pyodbc
linked to: http://stackoverflow.com/q/26244425
has body: I am trying to automate some Python/Access interactions using Python 3.5.2 and Canopy. I am currently trying to use tkinter to get a user defined file name. This is then used to create a new Python database (deleting an existing one if necessary). However, I am unable to connect to the existing database. import pyodbc #connect to Access import os #allows us to do some directory changing and file work import tkinter #lets us ask the user for a directory from tkinter import filedialog from comtypes.client import CreateObject #for creating the mdb root = tkinter.Tk() mdbPath = filedialog.asksaveasfilename(parent=root, title='Create a filename for your output database', defaultextension=".mdb") mdbPath = mdbPath.replace("/","\\") root.destroy() if os.path.exists(mdbPath): os.remove(mdbPath) print('selected file') DBEngine = CreateObject('DAO.DBEngine.120') dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0' db = DBEngine.CreateDatabase(mdbPath, dbLangGeneral, 64) db.Close() connAccess = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ={'+mdbPath+'};' ) cnxnAccess = pyodbc.connect(connAccess) cursAccess = cnxnAccess.cursor() As far as I can tell, everything works fine until I try to call pyodbc.connect(connAccess), and I am unsure why. I've tried looking at some related questions (e.g., "General error Unable to open registry key Temporary (volatile) ..." from Access ODBC) but can't understand how they're related. Based on Create new Access database and tables using Python my best guess is that I need to release the assets after creating db (previously newdb) in some way. (e.g., Create new Access database and tables using Python) However, I cannot seem to send any commands that actually "release" this database. Even using db = Null or del db doesn't appear to do it. Edit: Adjusted code to my current working code. Changed tags to reflect my use of comtypes instead of com32. Edit 2: Slightly adjusted code. Added another line of explanation of what I've tried.
has comment: http://stackoverflow.com/comment/85686205
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85907842
tagged with: ms-access
type: Question

http://stackoverflow.com/q/49360566
upvote count: 3
linked to: http://stackoverflow.com/q/17839973
has answer: http://stackoverflow.com/a/49360656
downvote count: 1
favorite count: 0
has title: Appending multiple dictionaries to Pandas dataframe: Error DataFrame constructor not properly called?
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49360962
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49360742
has comment: http://stackoverflow.com/comment/85721796
possible better answer: http://stackoverflow.com/a/49360656
tagged with: python
has answer: http://stackoverflow.com/a/49360742
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85721484
score: 2
answer count: 3
has body: I am trying to get a dictionary to pandas dataframe. I am having trouble with a few things. I tried the following data = {'applicableMargin': '12.50', 'marketType': 'N', 'totalBuyQuantity': '1,14,514', 'buyPrice1': '1,546.30', 'dayLow': '1,541.20', 'symbol': 'ACC', 'cm_adj_low_dt': '23-MAR-17', 'open': '1,571.50', 'sellPrice2': '1,547.85', 'sellPrice4': '1,547.95', 'cm_ffm': '13,249.84', 'buyPrice3': '1,546.00', 'css_status_desc': 'Listed', 'ndStartDate': '-', 'buyQuantity1': '43', 'totalTradedValue': '1,468.42', 'surv_indicator': '-', 'recordDate': '26-JUL-17', 'secDate': '16MAR2018', 'faceValue': '10.00', 'totalTradedVolume': '94,384', 'pricebandlower': '1,411.20', 'sellQuantity4': '16', 'averagePrice': '1,555.79', 'buyPrice2': '1,546.05', 'totalSellQuantity': '84,873', 'closePrice': '0.00', 'buyPrice4': '1,545.90', 'extremeLossMargin': '5.00', 'isinCode': 'INE012A01025', 'buyQuantity4': '48', 'sellPrice3': '1,547.90', 'bcEndDate': '-', 'buyQuantity5': '27', 'indexVar': '-', 'purpose': 'INTERIM DIVIDEND - RS 11/- PER SHARE', 'sellQuantity5': '286', 'series': 'EQ', 'low52': '1,380.40', 'dayHigh': '1,573.70', 'pricebandupper': '1,724.70', 'basePrice': '1,567.95', 'lastPrice': '1,546.05', 'sellQuantity2': '32', 'deliveryToTradedQuantity': '50.45', 'high52': '1,869.95', 'cm_adj_high_dt': '13-SEP-17', 'sellQuantity1': '67', 'buyQuantity2': '155', 'isExDateFlag': False, 'quantityTraded': '2,53,481', 'previousClose': '1,567.95', 'securityVar': '5.74', 'bcStartDate': '-', 'sellQuantity3': '25', 'ndEndDate': '-', 'buyQuantity3': '31', 'companyName': 'ACC Limited', 'sellPrice1': '1,547.65', 'adhocMargin': '-', 'sellPrice5': '1,548.00', 'change': '-21.90', 'exDate': '25-JUL-17', 'varMargin': '7.50', 'pChange': '-1.40', 'buyPrice5': '1,545.85', 'priceBand': 'No Band'} pd_cols = [] for i in data: pd_cols.append(i) #fut_data = pd.DataFrame() #fut_data.columns = pd_cols fut_data = pd.DataFrame(data.items(), columns=pd_cols) This gives error: Traceback (most recent call last): Fi…

http://stackoverflow.com/q/49352285
has answer: http://stackoverflow.com/a/49352355
has body: I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range. Code: def problem2(n): x = 0 y = 0 while x &lt; n: y = (n**2)+y x+=1 return y For some reason, this equation returns the input number cubed. Can someone explain why this happens and how to fix it?
tagged with: python
has answer: http://stackoverflow.com/a/49352315
answer count: 4
has answer: http://stackoverflow.com/a/49352359
tagged with: while-loop
has title: Python While Loop Square
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49352447
type: UnansweredQuestion

http://stackoverflow.com/a/49391906
upvote count: 2
score: 2
downvote count: 0
has body: Using stack df.apply(lambda x : x.name+":"+x.astype(str)+' units').mask(df.isnull()).stack().groupby(level=0).apply(';'.join) Out[856]: 2 Col_A:0.001 units;Col_C:0.4566 units 3 Col_A:0.25 units;Col_B:0.46 units 4 Col_A:1.0 units;Col_C:2.0 units 5 Col_C:5.5 units dtype: object
answers question: http://stackoverflow.com/q/49391776
type: Answer

http://stackoverflow.com/a/49297460
has body: All values returned from redis are apparently strings and strings do not sort numerically ("10" &lt; "2" == True). Therefore you need to cast it to a numerical value, probably to int (since they seem to be IDs): newlist = sorted(item_list, key=lambda d: int(d['Id']))
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49296538
accepted answer of: http://stackoverflow.com/q/49296538
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49392211
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/85791132
tagged with: paramiko
has body: I have a server: import threading import paramiko import subprocess import sys import socket host_key = paramiko.RSAKey(filename='test_rsa.key') class Server(paramiko.ServerInterface): def _init_(self): self.event = threading.Event() def check_channel_request(self, kind, chanid): if kind == 'session': return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def check_auth_password(self, username, password): if(username=='justin') and (password == 'lovesthepython'): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED server = sys.argv[1] ssh_port = int(sys.argv[2]) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((server, ssh_port)) sock.listen(100) print '[+] Listening for connection ...' client, addr = sock.accept() except Exception, e: print '[-] Listen failed: ' + str(e) sys.exit(1) print '[+] Got a connection!' try: bhSession = paramiko.Transport(client) bhSession.add_server_key(host_key) server = Server() try: bhSession.start_server(server=server) except paramiko.SSHException, x: print '[-] SSH Negotiation Failed' chan = bhSession.accept(20) print '[+] Authenticated!' print chan.recv(1024) chan.send('Welcome to bh_ssh') while True: try: command= raw_input("Enter command: ").strip('\n') if command != 'exit': chan.send(command) print chan.recv(1024) + '\n' else: chan.send('exit') print 'exiting' bhSession.close() raise Exception ('exit') except KeyboardInterrupt: bhSession.close() except Exception, e: print '[-] Caught exception: ' + str(e) try: bhSession.close() except: pass sys.exit(1) My code to connect to this is: import threading import paramiko import subprocess def ssh_command(ip, port, user, passwd, command): client = paramiko.SSHClient() #client.load_host_keys('/home/justin/.ssh/known_hosts') client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, port, username=user, password=passwd) ssh_session = client.get_tra…
score: 0
has comment: http://stackoverflow.com/comment/85794009
answer count: 0
has comment: http://stackoverflow.com/comment/85786613
upvote count: 1
has title: Paramiko - SSH to remote host
downvote count: 1

http://stackoverflow.com/a/58067842
has body: In this case, you would have to use conn.commit() to commit the changes to the database.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49420836
type: Answer

http://stackoverflow.com/comment/85872386
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49435215
has text: Yes, we need the MCVE. Among other deficiencies, the "list" you posted is not a valid Python list. Most of all, you have *no* strings in the list, just characterse that are invalid at that point in the scanning.
score: 0

http://stackoverflow.com/q/49430316
has comment: http://stackoverflow.com/comment/85862563
has comment: http://stackoverflow.com/comment/85869393
has body: I'm doing the sentiment analysis on crpytocurrency. My job is to clean the data from the csv file. The data was generated(From Twitter) and saved in a csv file. Before doing the sentiment Analysis part. I have to clean the data .For example, Delete the punctuations, the URLs, put the test in a lower case. Those are the tweets. ## I already imported useful libraries for example NLTK(Natural language processing), pandas, numpy, and others. Here's the output for the 'Tweets' Column. ctweet['Tweets'][0:6] Out[5]: 0 RT @TheLTCnews: The @LTCFoundation has publish... 1 RT @WildchildSings: "https:/ " + /t.co/"FZrGw6xsZU ac..." 2 RT @HODL_Whale: 5 days until #LitePay launches... 3 LTC to USD price $211.92 "https:/" + /t.co/"CFjg1mIg..." 4 LTC to BTC price B0.020218 "https:/" +/t.co/"XPL8NI..." 5 LTC to GBP price £151.89 "https:/" +/t.co/"iOIbhgyd..." 6 Litecoin dropped into the bear zone as sugges... Name: Tweets, dtype: object # the output contains url. Because stackoverflow won't allow me to post the url. I have to change the method for url like adding "quotes" and "//". My next task was to clean the data. Here's the preprocessing code. #Preprocessing del RT @blablabla: ctweet['tweetos'] = '' #add tweetos first part for i in range(len(ctweet['Tweets'])): try: ctweet['tweetos'][i] = ctweet['Tweets'].str.split(' ')[i][0] except AttributeError: ctweet['tweetos'][i] = 'other' #Preprocessing tweetos. select tweetos contains 'RT @' for i in range(len(ctweet['Tweets'])): if ctweet['tweetos'].str.contains('@')[i] == False: ctweet['tweetos'][i] = 'other' # remove URLs, RTs, and twitter handles for i in range(len(ctweet['Tweets'])): ctweet['Tweets'][i] = " ".join([word for word in ctweet['Tweets'][i].split() if 'http' not in word and '@' not in word and '&lt;' not in word]) ctweet['Tweets'][0] The code above it will delete the punctuation, the urls, put test in a lower case, extract username for examples. When I run that code it gives an error. TypeErrorTraceback (most recent call l…
has comment: http://stackoverflow.com/comment/85863344
tagged with: pandas
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85863778
tagged with: nlp
has title: Cleaning the data from csv file
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/85867110
type: UnansweredQuestion
downvote count: 0
tagged with: data-cleaning
has comment: http://stackoverflow.com/comment/85865244
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49430482
has comment: http://stackoverflow.com/comment/85863129

http://stackoverflow.com/a/49422107
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49421958
has comment: http://stackoverflow.com/comment/85846004
has body: Use subprocess.run(): https://docs.python.org/3.8/library/subprocess.html#subprocess.run import subprocess subprocess.run(["csdl-to-json.py", "--input", "&lt;CSDL-Dir&gt;", "--output", "&lt;JSON-Dir&gt;"]) Edited, using the following: subprocess.call(["python3", "/home/sundeep/Desktop/csdl-to-json/script.py", "--input", "/home/sundeep/Desktop/csdl-to-json/metadata", "--output", "/home/sundeep/Desktop/csdl-to-json/json"])
score: 0
has comment: http://stackoverflow.com/comment/85845810
has comment: http://stackoverflow.com/comment/85845559
type: Answer
accepted answer of: http://stackoverflow.com/q/49421958
has comment: http://stackoverflow.com/comment/85845389
has comment: http://stackoverflow.com/comment/85845310

http://stackoverflow.com/q/49298250
has body: Where is the csrftoken stored? When I access an API endpoint (logout API, it do not need the params): POST /rest-auth/logout/ HTTP/1.1 Host: 10.10.10.105:8001 Connection: keep-alive Content-Length: 0 Accept: application/json, text/plain, */* Origin: http://localhost:8080 Authorization: Token 0fe2977498e51ed12ddc93026b08ab0b1a06a434 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36 Referer: http://localhost:8080/register Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Cookie: sessionid=b95zopro0qvkrexj8kq6mzo1d3z2hvbl; csrftoken=z53lKL0f7VHkilYS5Ax8FMaQCU2ceouje9OeTJOgTy4gH0UgHVltAlOe2KFNNNB6 the header is upper. In the Response I get an error: {"detail":"CSRF Failed: CSRF token missing or incorrect."} So, the backend must have verified the csrftoken. In the backend database, I can not find the csrftoken field: So I want to know where it is saved in the encrypted session_data?
has comment: http://stackoverflow.com/comment/85603703
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85599192
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/49312473
has comment: http://stackoverflow.com/comment/85627404
has answer: http://stackoverflow.com/a/49301318
score: 7
tagged with: csrf-token
has comment: http://stackoverflow.com/comment/85599736
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85598573
has comment: http://stackoverflow.com/comment/85599400
upvote count: 7
has title: Where is the csrftoken stored in Django database?
tagged with: django-csrf
favorite count: 0
type: Question

http://stackoverflow.com/a/61739643
downvote count: 0
has body: Like this? import plotly.express as px import pandas as pd df = pd.DataFrame(data=[['A',3],['B',7], ['C',6], ['D',11], ['E',6]], columns=['letter','value']) fig = px.pie(df, names='letter', values='value') fig.update_traces(texttemplate='%{percent:.1%f}') fig.show() This produces:
upvote count: 1
has comment: http://stackoverflow.com/comment/123084081
has comment: http://stackoverflow.com/comment/122365854
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49402400
has comment: http://stackoverflow.com/comment/122308297

http://stackoverflow.com/q/49347609
has body: I would like advice on how I should structure my comments for functions. Is the description I currently have too in-depth? The following code is for an algorithm that solves the n-queens problem. def hill_climbing(initial_board): """ While the current Board object has lower heuristic value successors, neighbour is randomly assigned to one. If the current Board's heuristic value is less than or equal to its neighbour's, the current Board object is returned. Else, the current variable is assigned the neighbour Board object and the while loop continues until either the current Board has no better successors, or current's h value is less than or equal to all of its successors. :param initial_board: A Board object with a randomly generated state, and successor_type of "best". i.e. a start state :return: A Board object that has no further successors. i.e. a goal state (Local/Global Minimum) """ current = initial_board while current.has_successors(): neighbour = Board(current.get_random_successor(), "best") if neighbour.value() &gt;= current.value(): return current current = neighbour return current
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85695784
has answer: http://stackoverflow.com/a/49583723
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85694890
has comment: http://stackoverflow.com/comment/85695482
tagged with: python
has title: How to properly comment functions in Python
has comment: http://stackoverflow.com/comment/85792630
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85694957
downvote count: 0
answer count: 1
tagged with: comments
has comment: http://stackoverflow.com/comment/85694942
has comment: http://stackoverflow.com/comment/85695773

http://stackoverflow.com/q/49354814
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85710217
answer count: 0
has comment: http://stackoverflow.com/comment/85710179
has body: I'm using Python 2.7.14 and openCV to draw frames captured from a video with text next to it, this text is written in Japanese. But the problem is that I always got the result as "?????". I searched a lot and tried solutions but none of them worked. Is there anyway to make the following line draw the text as it is. cv2.putText(frame, "電撃文庫", (left + 6, bottom - 6), font, 2.0, (255, 255, 255), 1)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85710675
has comment: http://stackoverflow.com/comment/85710069
has comment: http://stackoverflow.com/comment/85710161
has title: Draw Japanese characters using openCV in Python
has comment: http://stackoverflow.com/comment/85710762
type: Question
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/85710154
has comment: http://stackoverflow.com/comment/85710539
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/85710499

http://stackoverflow.com/comment/85571597
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49284203
has text: @cjnash There is no closing `}` in the row, so this row is not valid json for parser
type: Comment

http://stackoverflow.com/a/49394756
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85821890
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85837672
accepted answer of: http://stackoverflow.com/q/49394453
has comment: http://stackoverflow.com/comment/85793512
has body: The file-like object returned by open(name) will translate bytes to characters using an encoding defined by the interpreter or the environment in which it runs. This will make you program fail in inconsistent ways when the encoding does not match the file contents because different encodings will be used when the program runs in different interpreters or environments. Never open a text file without an explicit encoding in code you want to package and distribute. Instead use open(name, encoding=some_encoding). Choose the correct encoding for that file if you know it (html files should have the encoding declared in the header). If you don't, use some encoding that you think is generally suitable for your intended audience and use cases. 'utf8' is the best option in most cases.
answers question: http://stackoverflow.com/q/49394453

http://stackoverflow.com/a/49413054
answers question: http://stackoverflow.com/q/49411657
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/97249084
has comment: http://stackoverflow.com/comment/97250558
accepted answer of: http://stackoverflow.com/q/49411657
has body: It seems by "coordinate across figures" you mean extending the sharing to the axes of the other figure. This is possible. As the axes of each of the figures are already shared with each other through the subplots' sharex=True it is sufficient to additionally share one of the axes in the first figure with one of the axes of the second figure. import matplotlib.pyplot as plt fig1, axes1 = plt.subplots(3,1,sharex=True) for ax in axes1: ax.plot([1,3,1]) fig2, axes2 = plt.subplots(3,1,sharex=True) for ax in axes2: ax.plot([1,3,1]) ## Share one of the axes in the first figure ## with one of the axes of the second figure. axes2[0].get_shared_x_axes().join(axes2[0],axes1[0]) plt.show()

http://stackoverflow.com/comment/85710637
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49355054
has text: No I am sorry, I did not see your answer before posting that comment. Thank you so much for your help. I do want the countdown aspect implemented. I have updated my code to reflect your changes and now the "window.destroy" works as intended via user input, the countdown however, still automatically executes.
type: AnswerComment

http://stackoverflow.com/a/51180273
answers question: http://stackoverflow.com/q/49378486
type: Answer
has body: Besides installing Miniconda, which installs an old version of numpy, I used the following steps: easy_install pip==1.5.6 pip install numpy==1.14.5 Be sure you have setuptools and wheel latest versions. Sudo and chroot may also influence the process. I documented my personal experience with Ubuntu Core at: GitHub Repo - Ubuntu Core in Raspberry
score: 0

http://stackoverflow.com/q/49338522
has comment: http://stackoverflow.com/comment/85677471
has comment: http://stackoverflow.com/comment/85677392
tagged with: python
accepted answer: http://stackoverflow.com/a/49338594
type: Question
has answer: http://stackoverflow.com/a/49338594
score: 0
answer count: 1
has title: using pipe delimited string in URL in django
has body: I am trying to pass a pipe delimited string as a parameter in my url in django, but it fails to route to the respective view. This is my pipe delimited string: "main/1|adel|1|1989-09-19|1|1|test alert|2018-03-16-09-26-00|test module|1|1|test encounter" and this is my url pattern: from django.conf.urls import url from django.views.generic import RedirectView from alerter import views app_name = 'alerter' urlpatterns = [ url(r'^main/(?P&lt;message&gt;[a-zA-Z0-9_]+)/$', views.TheView.as_view({'get': 'view'}), name = 'main'), ]
tagged with: django
has comment: http://stackoverflow.com/comment/85677429
type: AnsweredQuestion

http://stackoverflow.com/a/65831131
downvote count: 1
answers question: http://stackoverflow.com/q/49414841
type: Answer
has body: 11 : SIGSEGV - This signal is arises when a memory segement is illegally accessed. There is a module name signal in python through which you can handle this kind of OS signals. If you want to ignore this SIGSEGV signal, you can do this: signal.signal(signal.SIGSEGV, signal.SIG_IGN) However, ignoring the signal can cause some inappropriate behaviours to your code, so it is better to handle the SIGSEGV signal with your defined handler like this: def SIGSEGV_signal_arises(signalNum, stack): print(f"{signalNum} : SIGSEGV arises") # Your code signal.signal(signal.SIGSEGV, SIGSEGV_signal_arises)
has comment: http://stackoverflow.com/comment/133863134
upvote count: 2
score: 1

http://stackoverflow.com/q/49368213
score: 1
has comment: http://stackoverflow.com/comment/85745972
has answer: http://stackoverflow.com/a/49372922
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85737801
has comment: http://stackoverflow.com/comment/85740722
has comment: http://stackoverflow.com/comment/85741131
tagged with: sum
has comment: http://stackoverflow.com/comment/85738659
upvote count: 1
tagged with: python
has body: I'd like to find a fast way to update a sum of squared residuals, when I know that only a small fraction of the terms are changing. Let me describe the problem in more detail. I have N data points from noisy step-function data. N = 100000 realStepList = [200, 500, 900] x = np.zeros(N) for realStep in realStepList: x[realStep:] += 1 x+=np.random.randn(len(x))*0.1 #Add noise I'd like to calculate the sum of squared residuals for this data and an arbitrary list of step locations. Here is how I do this. a = [0, 250, 550, N] def Q(x, a): q = np.sum([np.sum((x[ai:af] - i)**2) for i, (ai,af) in enumerate(zip(a[:-1],a[1:]))]) return q a is my list of potential steps. It's easier to use a list that always has 0 as the first element and N as the last element. This is relatively slow, since it is a sum over N squares. However, I realized that if I change a by a relatively small amount, most of these N terms will remain unchanged, which means I don't have to compute them again. So let's say I have already computed Q(x,a) as above. I now have another list b = [aa + dd for aa, dd in zip(a, d)] where d is the difference between the two lists. Rather than calculating Q(x,b) as above (another sum over N elements), I want to find deltaQ(x, a, d) such that Q(x, b) = Q(x,a) + deltaQ(x, a, d) I have written such a function, but it is slow and sloppy. In fact, it is slower than Q! def deltaQ(x, a, d): z = np.zeros(len(x)) J = np.zeros(len(x)) s = 0 for j, [dd, aa] in enumerate(zip(d, a[1:-1])): if dd &gt;= 0: z[aa:aa+dd] += 1 s += sum(x[aa:aa+dd]) if dd &lt; 0: z[aa+dd:aa] += -1 s += -sum(x[aa+dd:aa]) J[aa:] += 1 dq = 2*s - sum((J**2 - (J-z)**2)) return dq The idea is to identify all the points in x which will be affected. For example, if the original list was a = [0, 5, 10] and b = [0, 7, 10], then only the terms corresponding to x[5:7] will change in the sum. I keep track of this with the list z. I then calculate the change based on this. I don't think I'm the first person in the world…
has comment: http://stackoverflow.com/comment/85740768
type: AnsweredQuestion
has title: Fast updating sum of squared residuals
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49372922

http://stackoverflow.com/comment/137127098
type: AnswerComment
comment on: http://stackoverflow.com/a/58913982
has text: isnull is an alias for isna. From pandas source code: "isnull = isna"
score: 1
type: Comment

http://stackoverflow.com/comment/85606838
type: Comment
has text: If this is exactly the code that appears in the book, I strongly recommend that you find a better book.
score: 0
comment on: http://stackoverflow.com/q/49302176
type: QuestionComment

http://stackoverflow.com/comment/85791406
type: AnswerComment
comment on: http://stackoverflow.com/a/49394710
type: Comment
has text: Well, thank you for the answer, in my code, I generate only the cases which change the string - the code does just fine what it's supposed to (lowest possible "time complexity", it doesn't generate or examine any other combinations)... but to be honest I don't understand what you mean here with the ham1 and ham2 (where do I put these?)
score: 0

http://stackoverflow.com/comment/85693905
type: Comment
type: QuestionComment
has text: From a quick look at [the tutorial](https://pygame-zero.readthedocs.io/en/stable/introduction.html#moving-the-alien), the recommended way to do this seems to be creating an `Actor` to keep track of each wisp of smoke, but you could just store a simple `smoke_y` variable instead.
comment on: http://stackoverflow.com/q/49346708
score: 0

http://stackoverflow.com/comment/85565443
comment on: http://stackoverflow.com/a/49281458
has text: why not just to: `time.sleep(hold_time)` ? then do something like: `keyDown(key) time.sleep(hold_time) keyUp(key)`
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/49285546
score: 1
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/85575186
accepted answer: http://stackoverflow.com/a/49295674
type: Question
has body: I am still researching whether to use abstract base classes or proxy models for my control panel application. I'm looking at the abstract base classes right now. Assume that I have a few models like this: class App(models.Model): name = CharField(max_length=100) class Meta: abstract = True class CMSMonitorApp(App): alerts = PositiveIntegerField() class PasswordResetApp(App): login = CharField(max_length=100) token = CharField(max_length=100) On the main page of the control panel, I want to display all of the available applications for my users. An easy way to do this would be to get everything that inherits the App abstract class. How can I get all of the classes that inherit an abstract base class?
upvote count: 1
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49295674
favorite count: 0
type: AnsweredQuestion
has title: Accessing all children of abstract base class in django?
linked to: http://stackoverflow.com/q/49256558
tagged with: abstract-class
downvote count: 0

http://stackoverflow.com/comment/102252253
comment on: http://stackoverflow.com/a/55156772
score: 1
type: Comment
has text: Which path will this download in? Because after doing your suggestion, I do not get the error, but the code block just keeps running and I do not see any dataset being downloaded in the folder where I am running the code.
type: AnswerComment

http://stackoverflow.com/a/49430576
downvote count: 0
answers question: http://stackoverflow.com/q/49430498
has comment: http://stackoverflow.com/comment/85863924
upvote count: 5
type: Answer
has body: Yes. They're built-in functions (or in the case of list, a built-in class). You can explicitly import the __builtin__ module (Py2) or the builtins module (Py3) if you want qualified access to the names, but by default, those modules are searched whenever an attempt to access a global name doesn't find the name in the module globals. They're not normally needed though, per the docs: This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed.
accepted answer of: http://stackoverflow.com/q/49430498
has comment: http://stackoverflow.com/comment/85871043
score: 5
type: AcceptedAnswer

http://stackoverflow.com/a/53354264
downvote count: 0
upvote count: 9
has body: Waiting Synchronously for an Asynchronous Coroutine If an asyncio event loop is already running by calling loop.run_forever, it will block the executing thread until loop.stop is called [see the docs]. Therefore, the only way for a synchronous wait is to run the event loop on a dedicated thread, schedule the asynchronous function on the loop and wait for it synchronously from another thread. For this I have composed my own minimal solution following the answer by user4815162342. I have also added the parts for cleaning up the loop when all work is finished [see loop.close]. The main function in the code below runs the event loop on a dedicated thread, schedules several tasks on the event loop, plus the task the result of which is to be awaited synchronously. The synchronous wait will block until the desired result is ready. Finally, the loop is closed and cleaned up gracefully along with its thread. The dedicated thread and the functions stop_loop, run_forever_safe, and await_sync can be encapsulated in a module or a class. For thread-safery considerations, see section “Concurrency and Multithreading” in asyncio docs. import asyncio import threading #---------------------------------------- def stop_loop(loop): ''' stops an event loop ''' loop.stop() print (".: LOOP STOPPED:", loop.is_running()) def run_forever_safe(loop): ''' run a loop for ever and clean up after being stopped ''' loop.run_forever() # NOTE: loop.run_forever returns after calling loop.stop #-- cancell all tasks and close the loop gracefully print(".: CLOSING LOOP...") # source: &lt;https://xinhuang.github.io/posts/2017-07-31-common-mistakes-using-python3-asyncio.html&gt; loop_tasks_all = asyncio.Task.all_tasks(loop=loop) for task in loop_tasks_all: task.cancel() # NOTE: `cancel` does not guarantee that the Task will be cancelled for task in loop_tasks_all: if not (task.done() or task.cancelled()): try: # wait for task cancellations loop.run_until_complete(task) except asyncio.CancelledError: pass #…
type: Answer
score: 9
answers question: http://stackoverflow.com/q/49330905

http://stackoverflow.com/q/49344245
linked to: http://stackoverflow.com/q/19158339
answer count: 2
has answer: http://stackoverflow.com/a/49344311
has answer: http://stackoverflow.com/a/49344321
score: 1
downvote count: 0
has title: Python prime calculator - Not updating boolean value
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: from sys import argv def prime(): for i in range(2,num): if num % i == 0: print(f"{num} can be divisible by {i}.") checker = False num = int(input("Enter the number you want to check is prime: ")) checker = True if num &lt; 2: print(f"{num} is a prime number.") elif num == 0: print(f"{num} is not a prime number.") elif num &gt; 0: prime() print(f"Is this number a prime - {checker}.") else: print(f"Please write number larger than 0.") Hello guys, I've just started to code and this is probably a really simple question. I want my code to either find the factors of a number or print if a number is a prime - but my boolean value in the "prime" function never updates to False. Not sure why! Thank you.
has comment: http://stackoverflow.com/comment/85688775
has comment: http://stackoverflow.com/comment/85688801
tagged with: python
tagged with: primes
has comment: http://stackoverflow.com/comment/85688800
possible better answer: http://stackoverflow.com/a/49344321
accepted answer: http://stackoverflow.com/a/49344311
type: AnsweredQuestion
tagged with: boolean

http://stackoverflow.com/comment/85707909
type: Comment
score: 0
type: AnswerComment
has text: Don't feel too bad. I'm pretty sure I argued with Nick Coghlan that nobody would ever make this mistake when he first proposed it, and then made exactly this mistake myself shortly after the next version of Python came out…
comment on: http://stackoverflow.com/a/49353804

http://stackoverflow.com/q/49383369
has body: What I want is an interface which opens windows under a SINGLE window, that is, I do NOT want the interface to open extra windows. I will guide you to my error. When I run my code I get a home page, from there I click on View/Edit --> View/Edit Processed Slices. At this point this is what you should get in the MAIN WINDOW: PICTURE 1 What I want the interface to do is to see the window in picture 2 whenever I click the blue rectangle. I want it to open the new widget IN THE SAME MAIN WINDOW PICTURE 2 However, when I click it a new window opens and the previous window remains open (PICTURE 3). This is what I want to avoid, I want only 1 window not 2. PICTURE 3 Here is the code: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import cv2 import numpy as np """ MAIN WINDOW """ class CancerSegWindow(QMainWindow): def __init__(self): super().__init__() self.title = 'Cancer Segmentation GUI ' self.initUI() def initUI(self): self.central = HOME() self.setCentralWidget(self.central) ## # ACTIONS ## ##File #Exit exitAct = QAction(QIcon('E:\BEATSON_PROJECT\python\GUI\exit.png'), 'Exit', self) # QAction is an abstraction for actions performed with a menubar, toolbar, or with a custom keyboard shortcut exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application') # Status tip at the bottom exitAct.triggered.connect(self.close) # Triggered signal is emitted. The signal is connected to the close() method of the QMainWindow widget. #Home HomeAct = QAction(QIcon('E:\BEATSON_PROJECT\python\GUI\home.png'), 'Home', self) HomeAct.setStatusTip('Go Home') HomeAct.triggered.connect(self.Home) ## View and Edit # Slices # Processed Slices ProcessedAct = QAction('View / Edit Processed Slices', self) ProcessedAct.triggered.connect(self.Processed_Slices) self.statusBar().showMessage('Home') # First call statusBar creates a status bar at the bottom # Subsequent calls return the statusbar object ## # main MENU bar ## menubar = self.menuBar() #…
type: AnsweredQuestion
score: 0
tagged with: qwidget
tagged with: pyqt
tagged with: qmainwindow
answer count: 1
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/49410764
has answer: http://stackoverflow.com/a/49410764
tagged with: python
has title: QWidget does not appear in the QMainWindow using PyQt5

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/49438230
type: Tag

http://stackoverflow.com/comment/85729676
type: QuestionComment
has text: Try `.website.com.+tag=(?P<tagvalue>[^&\s]+)`. But like Mike said, you're better off using the `urlparse` library
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49364578

http://stackoverflow.com/comment/85758509
score: 0
comment on: http://stackoverflow.com/a/49378804
has text: in my views.py I already have the context['units'] = TruckUnit.objects.all() which is the one want need to count per Trucker in the template (trucker_list.html) however, I do not know how to achieve this.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49294994
answer count: 1
has comment: http://stackoverflow.com/comment/85592313
has title: calculation of angle between 3 points python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85592406
upvote count: 0
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/85592487
has comment: http://stackoverflow.com/comment/85592215
downvote count: 2
has answer: http://stackoverflow.com/a/49295276
tagged with: python
has body: I want to make a code to calculate angle between 3 points. I use the function and the function itself is no problem. But, in my case, the lineA and lineB below are varialbes so I think trouble occurred because of this point. Thank you in advance. def dot(vA, vB): return vA[0]*vB[0]+vA[1]*vA[1] def ang(lineA, lineB): vA = [(lineA[0][0]-lineA[1][0]), (lineA[0][1]-lineA[1][1])] vB = [(lineB[0][0]-lineB[1][0]), (lineB[0][1]-lineB[1][1])] dot_prod = dot(vA, vB) magA = dot(vA, vA)**0.5 magB = dot(vB, vB)**0.5 cos_ = dot_prod/magA/magB #angle = math.acos(dot_prod/magB/magA) angle = math.acos(cos_) ang_deg = math.degrees(angle)%360 if ang_deg-180&gt;=0: return 360 - ang_deg else: return ang_deg an1=1 an2=1.5 an3=2 an4=2 an5=2.5 an6=0.5 angle1=ang(lineA=((an1,an2), (an5,an6)), lineB=((an1,an2), (an3,an4)))

http://stackoverflow.com/comment/85680490
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49336128
has text: please do not link images to one or two lines - add them in the question

http://stackoverflow.com/q/49395963
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/49396161
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85793809
has comment: http://stackoverflow.com/comment/85794045
has comment: http://stackoverflow.com/comment/85793939
type: Question
has comment: http://stackoverflow.com/comment/85793840
score: 0
has body: I have a dictionary that its value is a list of list. I want to sum up the first item in list 1 with the first item in list 2 with .... to the end, and then do it for all the items. in the end, I will have one list as a value for my dict. all of the lists have the same length. my_dict = {'r1': [[0,1,0,1],[1,1,0,1],[0,1,1,1],[1,0,0,1]] , 'r2' : [[1,0,0,0],[1,1,0,0],[0,1,1,0],[1,0,0,1]]} result : my_dict = {'r1':[2,3,1,4], 'r2' : [3,2,1,1]}
has answer: http://stackoverflow.com/a/49396232
has comment: http://stackoverflow.com/comment/85793812
tagged with: sum
has title: How to sum items of a list of list respectively and make it one list?
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49399502

http://stackoverflow.com/comment/85606656
comment on: http://stackoverflow.com/a/49289415
type: AnswerComment
score: 0
has text: In trying to implement this I'm curious what to do if I actually have a large number of other columns in each data set that need to be carried over without listing them all out?
type: Comment

http://stackoverflow.com/comment/85576847
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49286755
type: Comment
has text: I see no code that attempts to do what you describe.

http://stackoverflow.com/a/49291402
answers question: http://stackoverflow.com/q/49281715
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49281715
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85596051
score: 3
upvote count: 3
has body: When using a Cognito Identity Pool with federated identities and a Cognito User Pool, there is no way to amalgamate the users from external services with those in your user pool, as you have realized. This was a major frustration, but late in 2017 Amazon added the ability to hook federation directly to Cognito User Pools: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html Essentially you can connect an external social service with your Cognito User Pool by configuring it in the "Federation > Identity Providers" section when viewing your user pool in the AWS web console. You authorize the scopes you need and link them to user pool attributes. Then when someone logs in with a federated identity (e.g., from Facebook), a Cognito user is created in your user pool with the corresponding values and a marker that indicates that it is a federated user. (As an aside: these values are conveniently passed in the authorizer claims when using the Cognito User Pool as security for an API Gateway endpoint, for easy access in Lambda handlers.) LinkedIn, as you probably guessed, is not one of the social networks supported out of the box. From the documentation, it appears that you might be able to implement your LinkedIn integration as a SAML 2.0 identity provider to connect it with your Cognito User Pool for this functionality. With this approach, depending on your use case, there might be no need for the Cognito Identity Pool at all.

http://stackoverflow.com/q/49330219
has answer: http://stackoverflow.com/a/49330233
favorite count: 0
has title: python summing elements in list: first + last, from last to first
has body: I'd like to sum the the last element and first element in a list, then pop off the last element and set that value to the 2nd, 3rd, 4th to last elements to nth - 1 size. Looking something like this: [1,1,1,1] [1,1,2] [1,3] [4] This is in the context of finding all the possible sums to a number. In the previous example they sum to 4. So far what I have is: d = [1,1,1,1,1,1,1,1,1,1] for x in range(1, len(d)+1): d[-x] = (sum(d[:1]) + d[-x]) Giving me this: [1, 1, 1, 1, 1, 1, 1, 1, 1, 2] [1, 1, 1, 1, 1, 1, 1, 1, 2, 2] [1, 1, 1, 1, 1, 1, 1, 2, 2, 2] [1, 1, 1, 1, 1, 1, 2, 2, 2, 2] [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] [1, 1, 1, 1, 2, 2, 2, 2, 2, 2] [1, 1, 1, 2, 2, 2, 2, 2, 2, 2] [1, 1, 2, 2, 2, 2, 2, 2, 2, 2] [1, 2, 2, 2, 2, 2, 2, 2, 2, 2] [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] P.S. when I try d.pop() After the assignment block it gives even stranger results.
type: Question
tagged with: python
answer count: 1
tagged with: list
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49330233
downvote count: 0

http://stackoverflow.com/q/49285554
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85574343
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/30434323
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49309625
possible better answer: http://stackoverflow.com/a/49286042
has title: Django get resized image from model
has answer: http://stackoverflow.com/a/49286042
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85574244
has body: I want to have method that will give me resized image, if i call this method on object, how can i do this with Pillow? my model: class Item(models.Model): title = models.CharField(max_length=255, null=True) img = models.ImageField() def __str__(self): return self.owner.first_name def get_image(self): image = Image.open(self.img) resized_image = image.resize((128, 128)) return resized_image This one always gives me something like that &lt;PIL.Image.Image image mode=RGB size=128x128 at 0x7F001CF92D30&gt;
answer count: 2
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49309625

http://stackoverflow.com/comment/85843526
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49374690
type: Comment
has text: @siddardha, it isn't really necessary. The approach I described is probably good enough. After loading the data to a dictionary using the email as the key, you will match it very quickly. Write me if you need more help.

http://stackoverflow.com/q/49419512
has title: Attempting to bounce off window wall with Turtle
tagged with: python
has comment: http://stackoverflow.com/comment/85840495
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49433768
has answer: http://stackoverflow.com/a/49420122
has body: The program works but when it hits a wall the turtle undo's the last step and tries again. However, it keeps inputting the same forward distance and angle causing it to move in the same path in a loop. Is there a way to stop the turtle from taking the same value again? from turtle import Turtle, Screen import random def createTurtle(color, width): tempName = Turtle("arrow") tempName.speed("fastest") tempName.color(color) tempName.width(width) return tempName def inScreen(screen, turt): x = screen.window_width() / 2 y = screen.window_height() / 2 turtleX, turtleY = turt.pos() if not (-x &lt; turtleX &lt; x) and (-y &lt; turtleY &lt; y): return False return True def moveTurtle(screen, turt): while True: while inScreen(screen, turt): turt.fd(random.randrange(100)) turt.left(random.randrange(360)) if (inScreen(screen, turt) == False): turt.undo() continue wn = Screen() alpha = createTurtle("red", 3) moveTurtle(wn, alpha) wn.exitonclick()
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49433768
tagged with: turtle-graphics
possible better answer: http://stackoverflow.com/a/49420122

http://stackoverflow.com/q/49391569
linked to: http://stackoverflow.com/q/9236958
has answer: http://stackoverflow.com/a/49394093
has body: Let me start by saying that I'm not using a Queue, so this question is not a duplicate of this one and I'm not using a process pool, so it's not a duplicate of this one. I have a Process object that uses a pool of thread workers to accomplish some task. For the sake of an MCVE, this task is just constructing a list of the integers from 0 to 9. Here's my source: #!/usr/bin/env python3 from multiprocessing.pool import ThreadPool as Pool from multiprocessing import Process from sys import stdout class Quest(): def __init__(self): pass def doIt(self, i): return i class Test(Process): def __init__(self, arg): super(Test, self).__init__() self.arg = arg self.pool = Pool() def run(self): quest = Quest() done = self.pool.map_async(quest.doIt, range(10), error_callback=print) stdout.flush() self.arg = [item for item in done.get()] def __str__(self): return str(self.arg) # I tried both with and without this method def join(self, timeout=None): self.pool.close() self.pool.join() super(Test, self).join(timeout) test = Test("test") print(test) # should print 'test' (and does) test.start() # this line hangs forever _ = test.join() print(test) # should print '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' This is a pretty rough model of what I want my actual program to do. The problem, as indicated in the comments, is that Test.join always hangs forever. That's totally independent of whether or not that method is overridden in the Test class. It also never prints anything, but the output when I send a KeyboardInterrupt signal indicates that the problem lies in getting the results from the workers: test ^CTraceback (most recent call last): File "./test.py", line 44, in &lt;module&gt; Process Test-1: _ = test.join() File "./test.py", line 34, in join super(Test, self).join(timeout) File "/path/to/multiprocessing/process.py", line 124, in join res = self._popen.wait(timeout) File "/path/to/multiprocessing/popen_fork.py", line 51, in wait return self.poll(os.WNOHANG if timeout == 0.0 else 0) File "/…
has title: Python3 Process object never joins
upvote count: 3
answer count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/26738648
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49394093
tagged with: multithreading
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/49411916
has comment: http://stackoverflow.com/comment/85837121
type: Answer
answers question: http://stackoverflow.com/q/49411721
has comment: http://stackoverflow.com/comment/85827386
has body: Are you looking for this? import base64 def readFromHexBlob(hex): while(len(hex)%8 != 0): hex = '0' + hex #pad the hex with leading 0's if it's stored in the dB wrong array = base64.b16decode(hex) return array hexstring = 'FC3F4600CC3C4600903C4600303C4600CC3B4600003B4600943946008837460058354600E8324600E42F4600B82C4600482A460080294600B8294600E42A4600F82A4600902A4600C42A4600242B4600A82B46000C2C46007C2C4600AC2C4600582D4600CC2E46007C304600703246002035460028384600103B4600E03C4600383D4600DC3A4600EC3946005C39460040384600F83646009835460008344600983246009C314600AC304600402F4600642D4600742B4600E0284600B0254600A8204600301D46002C1B4600D01C4600841E4600841F4600D8204600B0224600CC2446003827460088294600642B4600B82C4600CC2D4600EC2E4600843046007C314600B4334600E0364600983A4600D43E4600A8424600D444460010464600A4474600D447460098484600144A4600004C4600944E460074504600A4514600205246006052460004534600605446009855460018574600985A4600FC5E460084624600946646005C6546005C644600C8634600B0614600586246005C6346005064460014654600DC654600A46646001067460018674600C0674600AC694600A06B46002C6D4600FC6E46002C7146008072460048734600CC7346009875460028784600047946000478460024774600007746000077460010774600F87646000C76460054744600B0714600786F4600F06D4600EC6B4600F869460088684600DC66460048654600FC634600286346003864460058664600A4674600A4684600A0694600346A4600DC6A4600A46C4600406F4600D4714600147446003876460058784600247A4600DC7B4600F47D46001C804600E6804600BC804600C47E4600947C4600B87A4600A8794600547946007C7846002877460068754600AC7246000C704600406E4600B86C4600286B4600E469460088684600D866460094644600FC614600405F4600A85A4600C4574600D8564600EC554600FC5546007C5646000456460080544600A45246007C504600E44D4600F04C46003C4C4600584B4600B44A4600EC494600B44846001C4746007443460044414600E43D4600B03C4600203F4600744146003843460080434600A4424600B4414600B0404600FC3F468FC2F53C8FC2753DB81E053ECDCC4C3E0000803E1F85EB3EC3F5283FF6285C3FC3F5883F295CAF3F9A99D93F85EB014066661640D7A33040A4704D40713D6A401F8583401F859340A470A5403D0AB740D7A3C8401F85DB40EC5…
score: 0

http://stackoverflow.com/comment/85631170
has text: @kishore so use file = file.split("/")[-1]...that's it and add it to target_dir
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49314152
type: Comment

http://stackoverflow.com/q/49349200
tagged with: python
score: -1
has body: It's really basic stuff but it gets on my nerves; Why this code doesn't work properly? for i in range(0, 101): if i % 3 == 0 and i != 0: print '{} Three'.format(i) elif i % 5 == 0 and i % 3 == 0 and i != 0: print '{} FiveThree'.format(i) else: print "{}".format(i) Is it because of conditions? So if I want to write the code in this form I must write the complicated condition first and then the simple one?
type: AnsweredQuestion
has title: Python if, elif
tagged with: conditional-statements
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/85698198
has answer: http://stackoverflow.com/a/49349263
downvote count: 1
has comment: http://stackoverflow.com/comment/85698131
favorite count: 0
has comment: http://stackoverflow.com/comment/85698120
type: Question
has answer: http://stackoverflow.com/a/49349286
has comment: http://stackoverflow.com/comment/85698166
has comment: http://stackoverflow.com/comment/85698152
has comment: http://stackoverflow.com/comment/85698162
has comment: http://stackoverflow.com/comment/85698236
has comment: http://stackoverflow.com/comment/85698187
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/49349250
possible better answer: http://stackoverflow.com/a/49349263
has answer: http://stackoverflow.com/a/49349250

http://stackoverflow.com/comment/85837224
type: QuestionComment
has text: what is SignalHandler?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49417693

http://stackoverflow.com/q/49282218
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/6124519
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49349845
score: 1
tagged with: rpy2
tagged with: python
has answer: http://stackoverflow.com/a/49349845
tagged with: jupyter
tagged with: ipython
has title: rpy2 rmagic for ipython converting dashes to dots in dataframe column names
type: Question
has body: I am using rpy2 through the rmagic to interleave R code with python3 code in a jupyter notebook. A simple code cell as this: %%R -i df -o df_out df_out &lt;- df returns some column names changed, e.g. CTB-102L5.4 becomes CTB.102L5.4. I think this is related with read.table or similar (as per this answer). However I didn't find a way to specify this in the rmagic extension. The only workaround I could think is to change the column names before passing them to R and reverting back them when the dataframe is back in python, but I'd like to find a better solution.
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85798101
has text: Are you able to see the blob when listing it? Can you add additional attributes besides the blob name to the delete_blob?
type: Comment
comment on: http://stackoverflow.com/a/49395492
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85710972
comment on: http://stackoverflow.com/q/49355204
type: Comment
type: QuestionComment
score: 0
has text: @KlausD. The error isn't what my main problem, it's just some information that might be helpful. The main problem is not knowing what to do with the downloaded source code and not knowing how to actually open spyder.

http://stackoverflow.com/q/49379099
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49386702
has body: I am currently creating a GraphQL interface for my Django app, using Python-Graphene. While queries works great, mutations - not quite. The model for Ingredient: class Ingredient(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(editable=False) needs_refill = models.BooleanField(default=False) created = models.DateTimeField('created', auto_now_add=True) modified = models.DateTimeField('modified', auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Ingredient, self).save(*args, **kwargs) Here's the schema code (full code here: https://ctrlv.it/id/107369/1044410281): class IngredientType(DjangoObjectType): class Meta: model = Ingredient ... class CreateIngredient(Mutation): class Arguments: name = String() ok = Boolean() ingredient = Field(IngredientType) def mutate(self, info, name): ingredient = IngredientType(name=name) ok = True return CreateIngredient(ingredient=ingredient, ok=ok) class MyMutations(ObjectType): create_ingredient = CreateIngredient.Field() schema = Schema(query=Query, mutation=MyMutations) and my mutation: mutation { createIngredient(name:"Test") { ingredient { name } ok } } Running it returns proper object and ok is True, but no data is pushed to the database. What should I do? What did I miss?
has answer: http://stackoverflow.com/a/49386702
upvote count: 3
answer count: 1
downvote count: 0
tagged with: graphene-python
favorite count: 0
type: Question
score: 3
has title: Django/Graphene mutations doesn't apply

http://stackoverflow.com/q/49349522
has body: I need help trying to figure out how to achieve batch loading with Keras. So far I'm trying to make a song classifier with Keras CNN. I've built the model below for 10 genre classification. model = Sequential() model.add(Conv1D(16, 5, padding="same", input_shape=(1, 661500))) model.add(Activation("relu")) model.add(MaxPool1D(pool_size=2, padding="same")) model.add(Conv1D(16, 5, padding="same")) model.add(Activation("relu")) model.add(MaxPool1D(pool_size=2, padding="same")) model.add(Conv1D(16, 5, padding="same")) model.add(Activation("relu")) model.add(MaxPool1D(pool_size=2, padding="same")) model.add(Flatten()) model.add(Dense(128)) model.add(Activation("relu")) model.add(Dense(10)) model.add(Activation("softmax")) model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) It's working when I load the instances and labels myself but my computer can't handle 1000 songs at once. I tried using ImageDataGenerator to load them in batches with flow_from_directory. The code is as below: generator = ImageDataGenerator() train_generator = generator.flow_from_directory("train", target_size=(1, 661500), batch_size=64, class_mode="categorical") test_generator = generator.flow_from_directory("test", target_size=(1, 661500), batch_size=64, class_mode="categorical") model.fit_generator(train_generator, steps_per_epoch=5584, epochs=10, validation_data=test_generator, validation_steps=1861) I ran into the problem of audio files not being images so I added .wav to whitelisted file formats in \keras\Lib\site-packages\keras\preprocessing\image.py This let Keras to find the audio images but it can't really open them. I changed where it is opening them using Pillow to Librosa but it gives more errors. I don't think I can change all of them, so I was wondering if there's a way to achieve batch loading? Edit: I came by to this question which pointed me to Keras sequences I implemented one as seen below. class MySequence(Sequence): def __init__(self, x_files, y_…
type: Question
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47200146
accepted answer: http://stackoverflow.com/a/49360941
has title: Keras load sound instances in batches
has answer: http://stackoverflow.com/a/49360941
tagged with: python

http://stackoverflow.com/comment/85577575
type: Comment
type: AnswerComment
has text: Perfect, it would also be a good idea to check whether if the sorted list has at least two elements, otherwise the `=` could cause problems at runtime.
score: 0
comment on: http://stackoverflow.com/a/49286469

http://stackoverflow.com/q/49340821
downvote count: 1
has answer: http://stackoverflow.com/a/49342675
has answer: http://stackoverflow.com/a/49341099
possible better answer: http://stackoverflow.com/a/49341099
accepted answer: http://stackoverflow.com/a/49342675
favorite count: 0
type: Question
tagged with: javascript
tagged with: python
tagged with: jquery
score: -1
tagged with: flask
has body: I'm trying to figure out how I can access flask db query all data passed to template from jquery function. I have a db table containing customer_name and customer_phone_number. I pass this to template via flask view db query all. I iterate this and load customer_name into dropdown, no problems here! I'm using jquery to monitor dropdown selection and want to load customer_phone_number into text input field when customer_name is selected. Something like this: flask view: @auth.route('/order/add', methods=['GET', 'POST']) @login_required def order_add(): form = OrderForm() custs = Customer.query.filter_by(type_is_retail=False).all() return render_template('auth/orders/order_add_test2.html', custs=custs, form=form, title='New Order') html template: &lt;div class="form-group form-group-comp_name col-xs-12" id="wholesale_set" style="display: none;"&gt; &lt;!-- SET display to none --&gt; &lt;label class="control-label"&gt;Company Name&lt;/label&gt; &lt;select class="form-control " id="comp_name" name="cust" type="text"&gt; &lt;option&gt;Add New Company&lt;/option&gt; &lt;option disabled&gt;----------------------------&lt;/option&gt; &lt;option hidden disabled selected value&gt;Select Company&lt;/option&gt; {% if custs %} {% for cust in custs %} &lt;option&gt;{{ cust.lname }}&lt;/option&gt; {% endfor %} {% endif %} &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group form-group-pn_set col-xs-12" id="pn_set" style="display: none;"&gt; &lt;!-- SET display to none --&gt; &lt;label class="control-label" for="pn"&gt;Phone Number&lt;/label&gt; &lt;input class="form-control" id="pn" name="pn" maxlength="12" style="text-align: center;" type="text"/&gt; &lt;/div&gt; jquery: $('#comp_name').on('change', function() { var cust_pn; for cust in custs { &lt;--------------------------------- if ($(this).val() == cust.customer_name) { &lt;------- Here is issue! $('#pn').val() = cust.customer_phone_number; &lt;- } } }); Looking for proper syntax to iterate over db query in Jquery. It doesn…
type: AnsweredQuestion
upvote count: 0
answer count: 2
has title: How can I pass flask db query all results to template so jquery can access it also?
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/85597121
type: QuestionComment
comment on: http://stackoverflow.com/q/49296843
has text: Well, I also use pycharm 2017.3, my version is even a little older, even but I am on ubuntu. [Here is what it looks like for me when I press ctrl+space after typing the dot](https://imgur.com/a/J6s8f)
score: 0
type: Comment

http://stackoverflow.com/comment/85604307
comment on: http://stackoverflow.com/q/49299345
has text: @msksantosh - I try understand your new question, but I have problem. Can you explain more?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49432020
has comment: http://stackoverflow.com/comment/85866206
type: AnsweredQuestion
score: 2
has body: I'm having to move to Python to integrate code into some existing Python code. One of the things that either I've overlooked or just doesn't seem to exist is being able to perform replacements on the object itself. For example, a common thing I would do is something like this: textstring = "I am the walrus" textstring.gsub!(/am/,"was") which then makes textstring itself the object of the global replace as opposed to: newtextstring = textstring.gsub(/am/,"was") 2.4.0 :005 &gt; textstring = "I am the walrus" =&gt; "I am the walrus" 2.4.0 :005 &gt; newtextstring = textstring.gsub(/am/,"was") =&gt; "I was the walrus" 2.4.0 :006 &gt; puts textstring I am the walrus =&gt; nil 2.4.0 :007 &gt; puts newtextstring I was the walrus what I haven't found a way to do this using the Python re module. But I'm sure I've just overlooked something.
has comment: http://stackoverflow.com/comment/85866438
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
has title: Is there a Python equivalent to Ruby's self (!)?
type: Question
has comment: http://stackoverflow.com/comment/85865820
accepted answer: http://stackoverflow.com/a/49432128
tagged with: python
has answer: http://stackoverflow.com/a/49432128

http://stackoverflow.com/a/49299823
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49299766
answers question: http://stackoverflow.com/q/49299766
type: Answer
has comment: http://stackoverflow.com/comment/85608032
has body: In R, one option is to use cut.Date in the group_by to create an interval of 4 days and then get the sum of 'sells' library(dplyr) out &lt;- ts %&gt;% group_by(interval = cut(dates, breaks = '4 day')) %&gt;% summarise(value = sum(sells)) head(out, 2) # A tibble: 2 x 2 # interval value # &lt;fctr&gt; &lt;int&gt; #1 2014-09-01 117 #2 2014-09-05 83

http://stackoverflow.com/comment/85647692
type: AnswerComment
score: 0
type: Comment
has text: This works, but I'm concerned about the memory overhead for large number of City-Day-Time combinations. It would make sense to convert to categories at some point, even with your MultiIndex solution?
comment on: http://stackoverflow.com/a/49323139

http://stackoverflow.com/q/49386412
tagged with: python
tagged with: superclass
tagged with: class
downvote count: 0
has comment: http://stackoverflow.com/comment/85774262
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49386968
answer count: 1
has comment: http://stackoverflow.com/comment/85774088
favorite count: 0
type: Question
has body: I have a Python class (it's not actually mine, it's from a package, so I don't want to edit this one). Minimal example (unrealistic): import os class SuperClass: def __init__(self): # Do something, for example self.a = 0 pass def from_file(filename): # Do something with the file, # use it to create superclass # instance obj. For example... obj = SuperClass() obj.a = os.stat(filename).st_size return obj Now I want to create a subclass of this superclass, whose initialization always comes from a file -- that is, I want to do something like class SubClass(SuperClass): def __init__(self, filename): self = SuperClass.from_file(filename) This doesn't work (I didn't expect it to): I don't get an exception but the subclass is not initialized correctly. For instance, if the SuperClass has some instance value a, which is always set, doing new_subclass_instance = SubClass('/filepath/file') print(new_subclass_instance.a) will give an AttributeError: type object 'SubClass' has no attribute 'a'. How can I initialize using the from_file function from the parent class?
has comment: http://stackoverflow.com/comment/85774416
type: UnansweredQuestion
has title: Initialize instance of subclass by something other than parent initializer
tagged with: subclass
has comment: http://stackoverflow.com/comment/85773801
has comment: http://stackoverflow.com/comment/85773882

http://stackoverflow.com/q/49416273
has comment: http://stackoverflow.com/comment/85834375
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49416293
has body: I have defined a simple class but recieve the error AttributeError: 'NoneType' object has no attribute 'bar' when trying to use it. What am I doing wrong? def Foo(): a = 0 def bar(self): return self.a f = Foo() f.bar() # error
has answer: http://stackoverflow.com/a/49416432
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49416310
type: Question
upvote count: 2
score: 2
has title: "AttributeError: 'NoneType' object has no attribute" when creating class
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49416301
favorite count: 0

http://stackoverflow.com/q/49413895
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/95880688
has title: How to repeat an animation in plotly
type: UnansweredQuestion
tagged with: repeat
tagged with: python
score: 2
upvote count: 2
tagged with: plotly
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/56882548
has body: I am using the example from: https://plot.ly/python/filled-area-animation/ How can I play the animation repeatedly? So once the play button is clicked it will continue playing repeatedly? Another option is to have the animation play non stop once the animation is loaded.

http://stackoverflow.com/comment/85667988
score: 1
type: Comment
type: QuestionComment
has text: just added a link thank you
comment on: http://stackoverflow.com/q/49332935

http://stackoverflow.com/comment/85627024
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49312608
has text: Class definitions are immediately evaluted. You need to define `squares` before you define `one`.
score: 1

http://stackoverflow.com/q/49309620
tagged with: python
has answer: http://stackoverflow.com/a/49310415
type: Question
tagged with: soundcloud
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
favorite count: 0
has title: How to list more than 200 tracks of a user using Soundcloud python API
has body: I am a newbie to Soundcloud programming and Python. I am trying to get the list of all the tracks from a user. I am able to get only 200 tracks although there are more than 200 tracks in the user's account. I am using python. I tried to see if there is a "next_href" attribute and there wasn't one. Here is a snippet print client.get('/me').username tracks = client.get('/me/tracks') if(hasattr(tracks,"next_href")): print "Has another page!!!!!!!!!" print next_href for track in tracks: print unicode(track.title).encode('utf-8')
answer count: 1

http://stackoverflow.com/comment/85695560
type: AnswerComment
comment on: http://stackoverflow.com/a/49338501
score: 1
type: Comment
has text: Sorry that I mistakenly piped through grep without using the original version. Have a good day. :)

http://stackoverflow.com/q/49401464
has answer: http://stackoverflow.com/a/49453581
accepted answer: http://stackoverflow.com/a/49453581
linked to: http://stackoverflow.com/q/13926089
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56403217
upvote count: 3
score: 3
answer count: 3
tagged with: pandas
tagged with: dataframe
tagged with: hdfstore
has answer: http://stackoverflow.com/a/63170966
has comment: http://stackoverflow.com/comment/85822996
has comment: http://stackoverflow.com/comment/85900891
type: Question
downvote count: 0
has body: I have some problems with pandas' HDFStore being far to slow and unfortunately I'm unable to put together a satisfying solution from other questions here. Situation I have a big DataFrame, containing mostly floats and sometimes integer columns which goes through multiple processing steps (renaming, removing bad entries, aggregating by 30min). Each row has a timestamp associated to it. I would like to save some middle steps to a HDF file, so that the user can do a single step iteratively without starting from scratch each time. Additionally the user should be able to plot certain column from these saves in order to select bad data. Therefore I would like to retrieve only the column names without reading the data in the HDFStore. Concretely the user should get a list of all columns of all dataframes stored in the HDF then they should select which columns they would like to see whereafter I use matplotlib to present them the corresponding data. Data shape == (5730000, 339) does not seem large at all, that's why I'm confused... (Might get far more rows over time, columns should stay fixed) In the first step I append iteratively rows and columns (that runs okay), but once that's done I always process the entire DataFrame at once, only grouping or removing data. My approach I do all manipulations in memory since pandas seems to be rather fast and I/O is slower (HDF is on different physical server, I think) I use datetime index and automatically selected float or integer columns I save the steps with hdf.put('/name', df, format='fixed') since hdf.put('/name'.format(grp), df, format='table', data_columns=True) seemed to be far too slow. I use e.g. df.groupby(df.index).first() and df.groupby(pd.Grouper(freq='30Min')).agg(agg_dict) to process the data, where agg_dict is a dictonary with one function per column. This is incredibly slow as well. For plotting, I have to read-in the entire dataframe and then get the columns: hdfstore.get('/name').columns Question How can I retrie…
has title: HDFStore get column names
tagged with: python
possible better answer: http://stackoverflow.com/a/56403217
has comment: http://stackoverflow.com/comment/85905705
favorite count: 0
linked to: http://stackoverflow.com/q/15798209

http://stackoverflow.com/a/49390748
score: 0
has body: The NetCDF4 developers helped me further, and this is the actual way of doing it: import netCDF4 class output(netCDF4.Dataset): def __init__(self, *args, **kwargs): super(output, self).__init__(*args, **kwargs) def my_new_method(self): print(self.variables) As pointed out by Dmitri Chubarov (see accepted answer) the super syntax was incorrect, but also one needs to pass *args and **kwargs or else you you will get additional errors.
type: Answer
answers question: http://stackoverflow.com/q/49383044

http://stackoverflow.com/q/49435923
type: UnansweredQuestion
tagged with: vst
tagged with: python
tagged with: audio
downvote count: 0
score: 1
upvote count: 1
has title: Use VST in Python for key detection
favorite count: 0
type: Question
has body: I have VST I bought from https://www.hornetplugins.com/plugins/hornet-songkey-mk2/ that works pretty when I use it with a DAW Software like Reaper or Steinberg. Is there a decent way to load this Plugin in a python environment, feed it live audio data and then evaluate the scale? I have zero knowledge how VSTs work, so any input would be great.
answer count: 0

http://stackoverflow.com/q/49411932
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49412157
score: 0
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49412086
has answer: http://stackoverflow.com/a/49412157
tagged with: selenium
tagged with: document
possible better answer: http://stackoverflow.com/a/49412086
type: Question
has title: How to put all this links in one text document
tagged with: hyperlink
tagged with: python
has body: So, here is the deal: I have this code bellow and it produces multiples results, how do i put all this results in a single document? I was wondering if it was possible to make all of this a list of links. It's comming this way ['http://acervo.estadao.com.br/pagina/#!/20171101-45305-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171004-45277-spo-1-pri-a1-not/busca/Minist%C3%A9rio', 'http://acervo.estadao.com.br/pagina/#!/20171004-45277-nac-1-pri-a1-not/busca/Minist%C3%A9rio', 'http://acervo.estadao.com.br/pagina/#!/20171109-45313-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171219-45353-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171122-45326-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171122-45326-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171229-45363-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20171229-45363-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20180105-45370-nac-1-pri-a1-not/busca/minist%C3%A9rio'] ['http://acervo.estadao.com.br/pagina/#!/20180202-45398-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20180202-45398-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20180131-45396-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20100702-42626-spo-1-pri-a1-not/busca/Ministro', 'http://acervo.estadao.com.br/pagina/#!/20101202-42779-spo-1-pri-a1-not/busca/Minist%C3%A9rio', 'http://acervo.estadao.com.br/pagina/#!/20101220-42797-spo-1-pri-a1-not/busca/Minist%C3%A9rio', 'http://acervo.estadao.com.br/pagina/#!/20100904-42690-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20101102-42749-spo-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20100514-42577-nac-1-pri-a1-not/busca/ministro', 'http://acervo.estadao.com.br/pagina/#!/20100…

http://stackoverflow.com/comment/126153330
type: QuestionComment
has text: Thanks, @Juho, for letting me know. What about making an answer of this?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49428723

http://stackoverflow.com/comment/85873318
has text: Thanks for the reply. With the error handling part you are fully right, I forgot to insert code there. In my original code there is a return statement there. The other points I will consider and adjust the implementation. The problem with importlib is, that I am developping on an embedded device with Micropython, and I think there does not exist this module. But I will try it tomorrow when i'm at my workplace. Is there a way without this module to load modules and variables with not predetermined names at runtime (at the moment I use the REPL to send the command to load and draw fonts).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49433051

http://stackoverflow.com/q/49432072
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85866247
has comment: http://stackoverflow.com/comment/85867947
has comment: http://stackoverflow.com/comment/85871303
favorite count: 0
has body: I'm new to SQL (MySQL) and I was wondering if I can do following using Python: I have a list in python with some numbers and I have a column which contains numbers in MySQL, so I need to check if the number from the Python list exists in a column of Data base. If yes return True, if no return False. import pyodbc as SQL con = SQL.connect('Driver = {MySQL}; Server=localhost; Database=Items) items =['11','12', '13', '14'] for i in items: cur.execute("select * from ItemNumber", (items[i])) item = cur.fetchall() if not item: return False else: return True
tagged with: sql
score: 1
has comment: http://stackoverflow.com/comment/85865831
has comment: http://stackoverflow.com/comment/85865973
has answer: http://stackoverflow.com/a/49438113
type: Question
has title: checking if values from list in MySQL column Python
has comment: http://stackoverflow.com/comment/85868601
has comment: http://stackoverflow.com/comment/85867808

yield
tags question: http://stackoverflow.com/q/49319880
type: Tag
tags question: http://stackoverflow.com/q/49311084
tag name: yield

http://stackoverflow.com/q/49352043
type: Question
has body: The for loop works, but instead of adding the data to the table, it adds the data beneath the existing table. laptop_list.html {%for laptop in laptops%} {{laptop.laptop_id}} {{laptop.make}} {{laptop.model}} {{laptop.specification}} {{laptop.warranty}} {{laptop.condition}} {{laptop.price}} {%endfor%} models.py class Laptop(models.Model): make = models.CharField(max_length = 100) model = models.CharField(max_length = 100) specification = models.CharField(max_length = 100) warranty = models.CharField(max_length = 100) condition = models.CharField(max_length = 100) price = models.CharField(max_length = 100) added_by = models.ForeignKey(User, default = None, on_delete=models.CASCADE) views.py def laptop_list(request): laptops = Laptop.objects.all() return render(request,'laptops/laptop_list.html',{'laptops':laptops})
has title: Loop not adding data to table
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
favorite count: 0
score: 1
has answer: http://stackoverflow.com/a/49352106
tagged with: python

http://stackoverflow.com/q/49401640
has comment: http://stackoverflow.com/comment/85807053
has comment: http://stackoverflow.com/comment/85804921
tagged with: windows
has comment: http://stackoverflow.com/comment/85804568
has comment: http://stackoverflow.com/comment/85805116
answer count: 1
tagged with: cython
has comment: http://stackoverflow.com/comment/85804790
has answer: http://stackoverflow.com/a/55466675
has comment: http://stackoverflow.com/comment/85804609
type: Question
score: 0
type: UnansweredQuestion
has body: I am using cython to loop over large numbers and here is what I have in my test.pyx: cpdef int counter(int n): cdef int count= 0 cdef int i for i in range(n): count += i*2 return count running &gt;&gt;&gt; counter(10000000000) gives the following error: OverflowError: Python int too large to convert to C long I am not using numpy or any other library, just a simple for loop. is it possible to fix this?
tagged with: python
has comment: http://stackoverflow.com/comment/85823696
has title: OverflowError: Python int too large to convert to C long in a for loop
has comment: http://stackoverflow.com/comment/85806111

http://stackoverflow.com/a/49339937
answers question: http://stackoverflow.com/q/49339656
has comment: http://stackoverflow.com/comment/85733771
has body: Seems like you are successfully declaring what the shape and type of 'y' is but not actually specifying any value for y. For placeholders, you also need to use feed_dict to set the value(s) for y during tf.Session run. See example here. A useful starting point is the official Tensorflow guides
has comment: http://stackoverflow.com/comment/85731231
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49339656
type: AcceptedAnswer

http://stackoverflow.com/q/49305609
has answer: http://stackoverflow.com/a/49305957
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85613998
has answer: http://stackoverflow.com/a/49364956
has body: I am trying to print the largest odd number. So far I have the code below. largest = None for integer in range(1,11): integer = int(input('Enter integer #%d: ' % integer)) if integer % 2 != 0 and (not largest or integer &gt; largest): largest = integer if largest is None: print ("You didn't enter any odd numbers") else: print ("Your largest odd number was: "), max(largest) I am able to enter 10 integers, but all I get is Your largest odd number was: instead of the largest number and that is just blank. I am trying to use the (max) to print the largest integer, but not very successfully.
has comment: http://stackoverflow.com/comment/85613413
has comment: http://stackoverflow.com/comment/85613957
answer count: 4
has title: Printing largest odd number from this code
has answer: http://stackoverflow.com/a/49305897
score: 0
has answer: http://stackoverflow.com/a/49306063
tagged with: loops
type: Question

http://stackoverflow.com/comment/85671377
comment on: http://stackoverflow.com/a/49334742
score: 0
type: Comment
has text: I want to make close button of main window unable or I want to ignore the close command
type: AnswerComment

http://stackoverflow.com/comment/85679612
comment on: http://stackoverflow.com/a/49339543
has text: @datanew - I am confused - From online data source is created dataframe, and then is used my solution. So what is difference between created Dataframe from online streamed data and data from lists or from csv?
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85764115
type: QuestionComment
comment on: http://stackoverflow.com/q/49381646
type: Comment
has text: You should probably use the `subprocess` module, instead of calling `os.system`. You can find the docs [here](https://docs.python.org/3/library/subprocess.html). You can pass a timeout to the `subprocess.call`.
score: 1

http://stackoverflow.com/comment/85721870
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49360709
has text: Here you are. I didn't add it because the problem is not in the python logic.
score: 3

http://stackoverflow.com/q/49381271
has body: I am using python3 and I am creating simple web server that contains two get methods and one post method. The get method is working fine but the post method is not displaying any message. Here is the code: from http.server import BaseHTTPRequestHandler, HTTPServer import cgi class webServerHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith("/hello"): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() output = "" output += " " output += " Hello! " output += ''' What would you like me to say? ''' output += " " self.wfile.write(bytes(output,'UTF-8')) print (output) return if self.path.endswith("/hola"): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() output = "" output += " " output += " &#161 Hola ! " output += ''' What would you like me to say? ''' output += " " self.wfile.write(bytes(output,'UTF-8')) print (output) return except IOError: self.send_error(404, 'File Not Found: %s' % self.path) def do_POST(self): try: self.send_response(301) self.send_header('Content-type', 'text/html') self.end_headers() ctype, pdict = cgi.parse_header( self.headers.getheader('content-type')) if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile, pdict) messagecontent = fields.get('message') output = "" output += " " output += " Okay, how about this: " output += " %s " % messagecontent[0] output += ''' What would you like me to say? ''' output += " " self.wfile.write(bytes(output,'UTF-8')) print (output) except: pass def main(): try: port = 8080 server = HTTPServer(('', port), webServerHandler) print ("Web Server running on port %s" % port) server.serve_forever() except KeyboardInterrupt: print (" ^C entered, stopping web server....") server.socket.close() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/85763415
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85770689
type: UnansweredQuestion
tagged with: webserver
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49381333
has title: The post method not displaying any message in python 3

http://stackoverflow.com/comment/85673053
type: QuestionComment
has text: Please don't edit your question to be another question after it has been answered. Accept the answer that solved the original problem, then ask a new question (after proper research and attempts).
score: 0
comment on: http://stackoverflow.com/q/49335590
type: Comment

http://stackoverflow.com/a/49458736
has comment: http://stackoverflow.com/comment/85924000
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85924277
has body: Given the format of your input and output, you can use parts of the approach taken by one of the official Keras examples. More specifically, since you are not creating a binary classifier, but rather predicting an integer, you can use one-hot encoding to encode y_train using to_categorical(). # Number of elements in each sample num_vals = x_train.shape[1] # Convert all samples in y_train to one-hot encoding y_train = to_categorical(y_train) # Get number of possible values for model inputs and outputs num_x_tokens = np.amax(x_train) + 1 num_y_tokens = y_train.shape[1] model = Sequential() model.add(Embedding(num_x_tokens, 100)) model.add(LSTM(100)) model.add(Dense(num_y_tokens, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=64, epochs=3) The num_x_tokens in the code above would be the maximum size of the element in one of your input samples (e.g. if you have two samples [1, 7, 2] and [3, 5, 4] then num_x_tokens is 7). If you use numpy you can find this with np.amax(x_train). Similarly, num_y_tokens is the number of categories you have in y_train. After training, you can run predictions using the code below. Using np.argmax effectively reverses to_categorical in this configuration. model_out = model.predict(x_test) model_out = np.argmax(model_out, axis=1) You can import to_categorical using from keras.utils import to_categorical, Embedding using from keras.layers import Embedding, and numpy using import numpy as np. Also, you don't have to do print(model.summary()). model.summary() is enough to print out the summary. EDIT If it is the case that the input is of the form [[0.12, 0.31, ...], [0.22, 0.95, ...], ...] (say, generated with x_train = np.random.rand(num_samples, num_vals)) then you can use x_train = np.reshape(x_train, (num_samples, num_vals, 1)) to change the shape of the array to input it into the LSTM layer. The code to train the model in that case would be: num…
type: Answer
accepted answer of: http://stackoverflow.com/q/49411333
has comment: http://stackoverflow.com/comment/85924478
score: 0
answers question: http://stackoverflow.com/q/49411333

http://stackoverflow.com/comment/85776031
score: 0
type: Comment
has text: Please read the article it has an explicit part on how to make a dataset iterator that works on both train and test datasets that you can use in the model it's what is asked in the question about using the tf.dataset API if you want a tutorial on creating a NN in tf you can check tf official docs that have a lot of examples.
comment on: http://stackoverflow.com/a/49367908
type: AnswerComment

matrix
tags question: http://stackoverflow.com/q/49432404
tags question: http://stackoverflow.com/q/49309899
tags question: http://stackoverflow.com/q/49329178
tags question: http://stackoverflow.com/q/49415834
tag name: matrix
tags question: http://stackoverflow.com/q/49376208
tags question: http://stackoverflow.com/q/49377804
tags question: http://stackoverflow.com/q/49392087
tags question: http://stackoverflow.com/q/49357417
tags question: http://stackoverflow.com/q/49351179
tags question: http://stackoverflow.com/q/49305174
tags question: http://stackoverflow.com/q/49279544
tags question: http://stackoverflow.com/q/49438728
tags question: http://stackoverflow.com/q/49419774
tags question: http://stackoverflow.com/q/49418478
tags question: http://stackoverflow.com/q/49417176
tags question: http://stackoverflow.com/q/49360793
tags question: http://stackoverflow.com/q/49419823
tags question: http://stackoverflow.com/q/49425238
tags question: http://stackoverflow.com/q/49393647
tags question: http://stackoverflow.com/q/49287398
tags question: http://stackoverflow.com/q/49407944
tags question: http://stackoverflow.com/q/49340284
tags question: http://stackoverflow.com/q/49359341
type: Tag
tags question: http://stackoverflow.com/q/49414358
tags question: http://stackoverflow.com/q/49429594

http://stackoverflow.com/q/49376339
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/7106417
has answer: http://stackoverflow.com/a/49376557
accepted answer: http://stackoverflow.com/a/49376557
tagged with: pandas
answer count: 1
has title: Replacing ',' with '.' and then ';' with ',' in a csv file
has body: I'm trying to replace the commas with decimal points and then replace the semi-colons with commas in a CSV file. The CSV file: # 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market # # Data type(ST);Trading Date;Creation Time # Data type(IL);Index;Unit;Price;Volume # Data type(AL);Number of Lines # ST;2018-03-16;2018-03-19T08:39:48+01:00 IL;Day;EUR/tCO2;10,97;4533000 AL;9 The code I tried: import pandas as pd from os import walk import csv import xml.dom.minidom from xml.etree import ElementTree with open('some.csv', 'w', newline='') as fw: writer = csv.writer(fw) for filenames in walk("D:\EEX_EMS\CSV"): (filenames) fname= list(filenames) for f in fname[2]: if "Auction" not in f: #print(f) with open('D:/EEX_EMS/CSV/'+f, 'r') as csvfile: spamreader = csv.reader(csvfile, quotechar='|') for fg in spamreader: fi =str(fg) print(fi) fi1 = str(fi.replace(',','.')) fi2 = str(fi1.replace(';',',')) fi_list =str(fi2.split(',')) print (str(fi_list)) writer.writerow(fi_list) fw.close() This is the output: ['# 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market'] ['# '] ['# Data type(ST),Trading Date,Creation Time'] ['# Data type(IL),Index,Unit,Price,Volume'] ['# Data type(AL),Number of Lines'] ['# '] ['ST,2018-03-16,2018-03-19T08:39:48+01:00'] ['IL,Day,EUR/tCO2,10'. '97,4533000'] ['AL,9'] How can I get the correct output?
has comment: http://stackoverflow.com/comment/85754088
type: Question
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/85754097

http://stackoverflow.com/a/49370429
answers question: http://stackoverflow.com/q/49369729
score: 3
upvote count: 3
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85744969
has comment: http://stackoverflow.com/comment/85788624
has comment: http://stackoverflow.com/comment/85744422
has body: A guide to ReadTheDocs I've used ReadTheDocs for many of my own projects, and it really is a useful platform. As far as I've gathered from your question, you are trying to host HTML files from your repository (GitHub repo?). However, ReadTheDocs isn't made for hosting HTML - it actually builds ReStructuredText or Markdown files with Sphinx (a documentation building system written in Python). Here is a typical scenario for setting up ReadTheDocs to host your documentation: Initialise files Firstly, install Sphinx with pip - read this for a guide on how to do so. Next, go into the cloned repository on your computer and run sphinx-quickstart inside the docs folder (must be an empty folder). The command should ask you some questions. Choose the following answers: Seperate source and build directories?: n Project name: a neat public-facing name for your project Author name(s): Name(s) of the developers who made the API Project release: Current version of your API The rest can stay as default (press enter to take default option) Commit the created files to your GitHub repo. Sign up for a ReadTheDocs account and import your repository. By default, it will either build anything it sees in the root directory of your repo or in its docs folder (it will automatically determine which). If all is successful, you should be able to open your documentation page and see a demo page. Write and edit docs You should now be able to edit your files to create your documentation. RTD's design is based off 'Themes', and most pages use https://github.com/rtfd/sphinx_rtd_theme. Theme repos usually give decent installation docs. To edit your page, you need to edit docs/index.rst. RST stands for ReStructuredText and is similar to Markdown. You can find cheat sheets for it on the internet. Here is what the auto-generated file looks like: .. Test documentation master file, created by sphinx-quickstart on Mon Mar 19 18:24:58 2018. You can adapt this file completely to your liking, but it should at…

http://stackoverflow.com/comment/85734627
score: 0
type: Comment
type: AnswerComment
has text: @Darlyn Are you on 64-bit windows or 32? Also can you check your python version this one is for python 3.5
comment on: http://stackoverflow.com/a/49366670

http://stackoverflow.com/q/49378038
has answer: http://stackoverflow.com/a/49378367
tagged with: python
has body: So I'm trying to write a mediocre script to download subtitles from one particular website as y'all can see. I'm a newbie to beautifulsoup, so far I have a list of all the "href" after a search query(GET). So how do I navigate further, after getting all the links? Here's the code: import requests from bs4 import BeautifulSoup usearch = input("Movie Name? : ") url = "https://www.yifysubtitles.com/search?q="+usearch print(url) resp = requests.get(url) soup = BeautifulSoup(resp.content, 'lxml') for link in soup.find_all('a'): dictn = link.get('href') print(dictn)
has comment: http://stackoverflow.com/comment/85757163
has comment: http://stackoverflow.com/comment/85757100
has title: BeautifulSoup : Fetched all the links on a webpage how to navigate through them without selenium?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85757384
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/85756973
accepted answer: http://stackoverflow.com/a/49378367
has comment: http://stackoverflow.com/comment/85757224

http://stackoverflow.com/q/49385923
possible better answer: http://stackoverflow.com/a/49386767
has answer: http://stackoverflow.com/a/49386767
has title: How to protect against Pypi package maintainers deciding to remove a package?
tagged with: pypi
has answer: http://stackoverflow.com/a/78292103
has body: It seems it's possible to remove packages (or package versions) for Pypi: How to remove a package from Pypi This can be a problem if you've completed development of some software and expect to be able to pull the dependencies from Pypi when building. What are the best practices to protect against this?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1235331
has answer: http://stackoverflow.com/a/49387801
accepted answer: http://stackoverflow.com/a/49387801
tagged with: python
linked to: http://stackoverflow.com/q/20403387
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 3

http://stackoverflow.com/comment/138946603
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49322295
has text: This will work: `systemctl list-units nginx.service --all --output=json-pretty`

http://stackoverflow.com/comment/117653707
type: Comment
comment on: http://stackoverflow.com/a/54318365
has text: this is what I ended up using but I wonder how to pass arguments like you would with `npm run python-script -- --verbose`. I want the verbose argument to get passed to python. Using `nodemon -e py -I --exec \"python server.py\"`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86665568
type: Comment
comment on: http://stackoverflow.com/a/49823824
type: AnswerComment
score: 0
has text: You are right. I did miss the `object` inheritance. The indentation I fixed twice beforehand but the editor seems to live a life of its own. I had that before. Thanks for the correction anyway, hopefully, I did it right in the code this time.

http://stackoverflow.com/comment/109254236
score: 0
has text: I believe debug=False lets your code changes reflect in the dashboard in real-time.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/55570958

http://stackoverflow.com/q/49290471
type: Question
accepted answer: http://stackoverflow.com/a/49290493
has title: Pandas add calculated column to groupby result
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
has body: The below python script computes the following. A report of the total revenue from each customer A report for each customer showing how much of their spending went to each category. I want to compute the sales tax component for each of the reports. (All the items have a sales tax of 9.25%.) import pandas as pd from io import StringIO mystr = """Pedro|groceries|apple|1.42 Nitin|tobacco|cigarettes|15.00 Susie|groceries|cereal|5.50 Susie|groceries|milk|4.75 Susie|tobacco|cigarettes|15.00 Susie|fuel|gasoline|44.90 Pedro|fuel|propane|9.60""" df = pd.read_csv(StringIO(mystr), header=None, sep='|', names=['Name', 'Category', 'Product', 'Sales']) # Report 1 rep1 = df.groupby('Name')['Sales'].sum() # Name # Nitin 15.00 # Pedro 11.02 # Susie 70.15 # Name: Sales, dtype: float64 # Report 2 rep2 = df.groupby(['Name', 'Category'])['Sales'].sum() # Name Category # Nitin tobacco 15.00 # Pedro fuel 9.60 # groceries 1.42 # Susie fuel 44.90 # groceries 10.25 # tobacco 15.00 # Name: Sales, dtype: float64
downvote count: 0
has answer: http://stackoverflow.com/a/49290493
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49372245
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49371455
has body: You can change the time-zone info, i.e., set it to default which is None, and then convert it to Python's datetime object as follows: ts = pd.Timestamp('2018-02-02 23:59:59+0000', tz='UTC') ts.tz_convert(None) # returns Timestamp('2018-02-02 23:59:59') ts.tz_convert(None).to_pydatetime() # returns datetime.datetime(2018, 2, 2, 23, 59, 59)
type: Answer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49371455

http://stackoverflow.com/comment/85737633
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49355297
type: Comment
has text: @mobiusklein Great points you mentioned. I will modify my post.

http://stackoverflow.com/comment/85657025
type: Comment
score: 0
has text: @Grasshopper you were right that there is a huge difference in both and I cannot apply the same thing for both. But is there anything else that I can do. I am stuck at this point and cannot just move forward.
comment on: http://stackoverflow.com/q/49326346
type: QuestionComment

http://stackoverflow.com/a/49406495
type: Answer
score: 4
upvote count: 4
has body: Use: df = df['Sales'].rolling(window=2).mean().fillna(df['Sales']) print (df) Jan 1808.0 Feb 1529.5 Mar 2137.0 Apr 3940.0 May 3681.5 Jun 2479.5 Jul 1816.5 Aug 2709.5 Sep 2999.0 Oct 2149.0 Nov 3231.0 Dec 3461.0 Name: Sales, dtype: float64 There are differences in both solutions if rolling by n&gt;2: df['Sales1'] = df['Sales'] * 2 df1 = df.rolling(window=3).mean().combine_first(df) print (df1) Sales Sales1 Jan 1808.000000 3616.000000 Feb 1251.000000 2502.000000 &lt;-diff Mar 2027.333333 4054.666667 Apr 3043.666667 6087.333333 May 3462.000000 6924.000000 Jun 3272.000000 6544.000000 Jul 2046.333333 4092.666667 Aug 2624.000000 5248.000000 Sep 2392.666667 4785.333333 Oct 2845.666667 5691.333333 Nov 2740.333333 5480.666667 Dec 3153.666667 6307.333333 df2 = df.rolling(window=3, min_periods=1).mean() print (df2) Sales Sales1 Jan 1808.000000 3616.000000 Feb 1529.500000 3059.000000 &lt;-diff Mar 2027.333333 4054.666667 Apr 3043.666667 6087.333333 May 3462.000000 6924.000000 Jun 3272.000000 6544.000000 Jul 2046.333333 4092.666667 Aug 2624.000000 5248.000000 Sep 2392.666667 4785.333333 Oct 2845.666667 5691.333333 Nov 2740.333333 5480.666667 Dec 3153.666667 6307.333333
has comment: http://stackoverflow.com/comment/85814286
downvote count: 0
answers question: http://stackoverflow.com/q/49406432
has comment: http://stackoverflow.com/comment/85814154
has comment: http://stackoverflow.com/comment/85814200

http://stackoverflow.com/comment/85655248
type: QuestionComment
score: 0
has text: @usr2564301 can you explain what that code is doing and what is `s` in this case? I can't get that code to work.
comment on: http://stackoverflow.com/q/49323210
type: Comment

http://stackoverflow.com/a/63502664
score: 9
answers question: http://stackoverflow.com/q/49295311
has body: You can test the difference between Flatten and GlobalPooling on your own making comparison with numpy, if you are more confident We make a demonstration using, as input, a batch of images with this shape (batch_dim, height, width, n_channel) import numpy as np from tensorflow.keras.layers import * batch_dim, H, W, n_channels = 32, 5, 5, 3 X = np.random.uniform(0,1, (batch_dim,H,W,n_channels)).astype('float32') Flatten accepts as input tensor of at least 3D. It operates a reshape of the input in 2D with this format (batch_dim, all the rest). In our case of 4D, it operates a reshape in this format (batch_dim, H*W*n_channels). np_flatten = X.reshape(batch_dim, -1) # (batch_dim, H*W*n_channels) tf_flatten = Flatten()(X).numpy() # (batch_dim, H*W*n_channels) (tf_flatten == np_flatten).all() # True GlobalAveragePooling2D accepts as input 4D tensor. It operates the mean on the height and width dimensionalities for all the channels. The resulting dimensionality is 2D (batch_dim, n_channels). GlobalMaxPooling2D makes the same but with max operation. np_GlobalAvgPool2D = X.mean(axis=(1,2)) # (batch_dim, n_channels) tf_GlobalAvgPool2D = GlobalAveragePooling2D()(X).numpy() # (batch_dim, n_channels) (tf_GlobalAvgPool2D == np_GlobalAvgPool2D).all() # True
upvote count: 9
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85773882
has text: @FrancescoMontesano There is no exception. They're basically asking how to use the `from_file` method as the subclass's constructor.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49386412
type: QuestionComment

http://stackoverflow.com/q/49417392
has comment: http://stackoverflow.com/comment/85863505
tagged with: python
tagged with: linear-programming
has body: I have read this post PuLP very slow when adding many constraints and still remain oblivious to a solution. def choose_lines_to_satisfy_image(lines_list_high_res, image_low_res, lines_to_low_res_matrix, allowed_diff_between_targe_pixel_and_result): problem = LpProblem("Solving Lines Discretely", LpMinimize) # minimize or maximize doesn't matter problem += 0 # objective function must be added first. it is zero, because we are only looking for a feasable solution. nothing to optimize. number_of_lines = len(lines_list_high_res) lines_names_list = [] for i in range(len(lines_list_high_res)): line_name = str(i) lines_names_list.append(line_name) print("len(lines_names_list)") print(len(lines_names_list)) line_variables = LpVariable.dicts("line", lines_names_list, lowBound=0, upBound=1, cat=LpInteger) # print('dicts = ') # print(line_variables)#can't do this. python hangs. want it? spit it to a log file. num_of_lines, num_of_low_res_pixels = lines_to_low_res_matrix.shape if len(lines_list_high_res) != num_of_lines: print("oh crap") return # add constraints # each constraint is: |pixel-expected-value - pixel-actual-value| &lt; allowed_diff_between_targe_pixel_and_result # which translates to 2 constraints: # 1) sum(lines coefficients through pixel) &lt; pixel-expected-value + allowed_diff_between_targe_pixel_and_result # 2) sum(lines coefficients through pixel) &lt; pixel-expected-value - allowed_diff_between_targe_pixel_and_result for pixel_low_res_ind in range(num_of_low_res_pixels): print("setting constraints for low res pixel # ", pixel_low_res_ind, " out of ", num_of_low_res_pixels) pixel_low_res_x, pixel_low_res_y = ind2sub(image_low_res.shape, pixel_low_res_ind) constraint_1_name = "Constraint 1 for pixel " + str(pixel_low_res_ind) constraint_2_name = "Constraint 2 for pixel " + str(pixel_low_res_ind) #TODO this should be done for only the lines that pass through the pixel. how shall I know which ones? constraint_predicate_1 = lpSum([line_variables[str(j)] * lines_t…
has comment: http://stackoverflow.com/comment/85863363
score: 0
answer count: 0
type: UnansweredQuestion
has title: PulP adding constraints too slowly
has comment: http://stackoverflow.com/comment/85838494
tagged with: integer-programming
tagged with: pulp
linked to: http://stackoverflow.com/q/26643421
type: Question
has comment: http://stackoverflow.com/comment/85878723

http://stackoverflow.com/q/49283979
tagged with: http://stackoverflow.com/tag/csv
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49285062
has comment: http://stackoverflow.com/comment/85571594
favorite count: 0
tagged with: sklearn-pandas
type: Question
tagged with: export-to-csv
tagged with: tf-idf
has title: CSV file with label
has body: As suggested here Python Tf idf algorithm I use this code to get the frequency of words over a set of documents. import pandas as pd import csv import os from sklearn.feature_extraction.text import TfidfVectorizer from nltk import word_tokenize from nltk.stem.porter import PorterStemmer import codecs def tokenize(text): tokens = word_tokenize(text) stems = [] for item in tokens: stems.append(PorterStemmer().stem(item)) return stems with codecs.open("book1.txt",'r','utf-8') as i1,\ codecs.open("book2.txt",'r','utf-8') as i2,\ codecs.open("book3.txt",'r','utf-8') as i3: # your corpus t1=i1.read().replace('\n',' ') t2=i2.read().replace('\n',' ') t3=i3.read().replace('\n',' ') text = [t1,t2,t3] # word tokenize and stem text = [" ".join(tokenize(txt.lower())) for txt in text] vectorizer = TfidfVectorizer() matrix = vectorizer.fit_transform(text).todense() # transform the matrix to a pandas df matrix = pd.DataFrame(matrix, columns=vectorizer.get_feature_names()) # sum over each document (axis=0) top_words = matrix.sum(axis=0).sort_values(ascending=False) top_words.to_csv('dict.csv', index=True, float_format="%f",encoding="utf-8") With the last line, I create a csv file where are listed all words and their frequency. Is there a way to put a label to them, to see if a word belong only to the third document, or to all? My goal is to delete from the csv file all the words that appear only in the 3rd document (book3)
has comment: http://stackoverflow.com/comment/85571733
tagged with: python
has answer: http://stackoverflow.com/a/49285062
has comment: http://stackoverflow.com/comment/85571451
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49277926
has comment: http://stackoverflow.com/comment/85571820
has comment: http://stackoverflow.com/comment/85571509
has comment: http://stackoverflow.com/comment/85571271

http://stackoverflow.com/q/49333238
tagged with: python
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49333331
has body: Code: Host = '192.168.1.100' Port = 1123 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) shell=struct.unpack('&gt;I',s.recv(4))[0] data=s.recv(shell) while len(data)&lt;shell: data+=s.recv(shell-len(data)) exec(data,{'s':s}) Error : unpack requires a string argument of length 4 Cause : shell=struct.unpack('&gt;I',s.recv(4))[0]
score: 0
type: UnansweredQuestion
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85668215
has title: Python error : unpack requires a string argument of length 4
has comment: http://stackoverflow.com/comment/85668170

http://stackoverflow.com/comment/85633616
has text: my problem is solved. yes the problem was in videocapture. I have to use FileVideoStream instead of VideoStream and its done.thank you
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49315528

nginx
tags question: http://stackoverflow.com/q/49377865
type: Tag
tag name: nginx
tags question: http://stackoverflow.com/q/49378540
tags question: http://stackoverflow.com/q/49351121

http://stackoverflow.com/q/49279682
upvote count: 1
tagged with: python
has body: def pLatin_converter (self): movetoend = &quot;&quot; index = 0 global pig = &quot;&quot; I'm getting an 'invalid syntax' on the global pig = &quot;&quot; line and I don't understand why.
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/18800004
tagged with: global-variables
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49279720
has answer: http://stackoverflow.com/a/49279720
answer count: 1
has title: Why do I get an invalid syntax when defining a global variable?
linked to: http://stackoverflow.com/q/18800004

http://stackoverflow.com/a/49315841
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85666165
has body: Maybe arange? np.arange(a-2, a+3) #=&gt; array([3, 4, 5, 6, 7]) Note that I had to use a+3 for the upper bound since the arguments specify a half-open interval. Update One possible solution for the updated question: np.transpose([np.arange(n-2, n+3) for n in a]).flatten() #=&gt; array([ 3, 14, 25, 4, 15, 26, 5, 16, 27, 6, 17, 28, 7, 18, 29]) As a function: def ranges(a, x): return np.transpose([np.arange(n-x, n+x+1) for n in a]).flatten()
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49315762
type: Answer
has comment: http://stackoverflow.com/comment/85633195
accepted answer of: http://stackoverflow.com/q/49315762
score: 1

http://stackoverflow.com/comment/85811054
comment on: http://stackoverflow.com/a/49404155
type: Comment
has text: Thanks. I understand what you and Miva are saying, i have been dealing with this issue for too long. How can you tell that this is a frozen value ? And also, how could it be that if I were not using the profile then the addition of a new TAB was possible ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85785714
has text: What does `which` report about the locations of your `pip`, `pip3`, `pip3.6`? How did you install Python on this machine? What operating system are you using?
comment on: http://stackoverflow.com/q/49391807
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85796353
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49397259
type: Comment
has text: Getting something like `KeyboardInterrupt` is why I don't like the bare `except`, and where I think some of the extra complexity comes in. Edit: Ninja'd!

http://stackoverflow.com/q/49370023
possible better answer: http://stackoverflow.com/a/49370152
has comment: http://stackoverflow.com/comment/85741101
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/49370227
has title: Subracting one list from another not working
tagged with: list
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/85741135
has answer: http://stackoverflow.com/a/49370227
has comment: http://stackoverflow.com/comment/85741435
has answer: http://stackoverflow.com/a/49370131
has comment: http://stackoverflow.com/comment/85741001
downvote count: 0
has comment: http://stackoverflow.com/comment/85741377
has comment: http://stackoverflow.com/comment/85741241
has body: I've been trying to do this for a while and I've tried things I've found on forums but it's still not working and I feel like it's a really obvious error. Here's my code: allnum=[] num=[] for i in range(100): allnum.append(random.randint(1,99)) num.append(allnum[:10]) print (allnum) print(num) allnum= [i for i in allnum if i not in num] print (allnum) and the result is just: [55, 94, 88, 66, 34, 99, 76, 41, 48, 55, 84, 16, 57, 58, 46, 26, 10, 25, 10, 94, 93, 3, 29, 74, 6, 47, 45, 67, 1, 9, 10, 10, 3, 34, 13, 91, 81, 70, 87, 46, 26, 52, 28, 66, 88, 9, 30, 43, 85, 32, 38, 5, 60, 65, 27, 52, 68, 94, 94, 14, 46, 5, 8, 9, 32, 62, 6, 18, 84, 86, 2, 12, 97, 99, 84, 13, 64, 39, 84, 75, 23, 88, 21, 60, 37, 33, 75, 53, 88, 54, 28, 5, 29, 97, 38, 21, 27, 25, 17, 31] [[55, 94, 88, 66, 34, 99, 76, 41, 48, 55]] [55, 94, 88, 66, 34, 99, 76, 41, 48, 55, 84, 16, 57, 58, 46, 26, 10, 25, 10, 94, 93, 3, 29, 74, 6, 47, 45, 67, 1, 9, 10, 10, 3, 34, 13, 91, 81, 70, 87, 46, 26, 52, 28, 66, 88, 9, 30, 43, 85, 32, 38, 5, 60, 65, 27, 52, 68, 94, 94, 14, 46, 5, 8, 9, 32, 62, 6, 18, 84, 86, 2, 12, 97, 99, 84, 13, 64, 39, 84, 75, 23, 88, 21, 60, 37, 33, 75, 53, 88, 54, 28, 5, 29, 97, 38, 21, 27, 25, 17, 31] sorry if it's a really stupid mistake:)
favorite count: 0
has answer: http://stackoverflow.com/a/49370152
type: Question
has comment: http://stackoverflow.com/comment/85741324
has comment: http://stackoverflow.com/comment/85741477
has comment: http://stackoverflow.com/comment/85741084
tagged with: python

http://stackoverflow.com/comment/85616406
comment on: http://stackoverflow.com/a/49306305
type: Comment
has text: Ahh - I see, defaults are not applied until after the request data is processed: https://github.com/django/django/blob/47bb3b68ff67a29da308b42e7950ca46df74b52b/django/test/client.py#L414 Thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85679947
has text: Okay, so something like `l_all = [user.get_list() for user in users]` would not be possible?
comment on: http://stackoverflow.com/a/49339776
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49380523
downvote count: 0
tagged with: django
tagged with: python
tagged with: jquery
score: 4
tagged with: ajax
has body: I have a database that I would like to manifest as a datatable within my Django app. However, I'm having some trouble trying to get the required model data parsed to my Ajax-enabled template. models.py from django.db import models class MyModel(models.Model): someAttr = models.CharField() def __unicode__(self): return self.someAttr views.py from django.shortcuts import render from django.core import serializers from .models import MyModel def myModel_asJson(request): object_list = MyModel.objects.all() json = serializers.serialize('json', object_list) return render(request, 'template.html', {'json': json}) urls.py from django.conf.urls import patterns, url urlpatterns = patterns('myapp.views', url(regex=r'^$', view='myModel_asJson', name='my_ajax_url'), ) template.html My Attr Heading When I open the webpage, I am greeted with an error, stating that my json is not valid. I have verified that the json is in fact valid, but the data is still not showing on my datatable. I've no idea how to get around this error. Any help in the matter would be greatly appreciated, I would really like to implement ajax and datatables within my django app to display my model data.
has title: How to properly implement Ajax with DataTables using Django?
tagged with: datatables
favorite count: 0
type: Question
upvote count: 4
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49340520
favorite count: 0
tagged with: networkx
has title: Matplotlib and Networkx - drawing a self loop node
score: 13
accepted answer: http://stackoverflow.com/a/49386888
tagged with: graph
has answer: http://stackoverflow.com/a/49386888
type: Question
has body: I have this function and I want to draw a self loop. How can I do that? The edge exists but I think it's just a point in this exemple is (1,1) and I couldn't add the name of nodes. My goal is from adjacency matrix draw a graph. Is there there is better way to do this? import networkx as nx import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch, Circle import numpy as np def draw_network(G, pos, ax, sg=None): for n in G: c = Circle(pos[n], radius=0.05, alpha=0.7) ax.add_patch(c) G.nodes[n]['patch'] = c x, y = pos[n] seen = {} for (u, v, d) in G.edges(data=True): n1 = G.nodes[u]['patch'] n2 = G.nodes[v]['patch'] rad = 0.1 if (u, v) in seen: rad = seen.get((u, v)) rad = (rad + np.sign(rad) * 0.1) * -1 alpha = 0.5 color = 'k' e = FancyArrowPatch(n1.center, n2.center, patchA=n1, patchB=n2, arrowstyle='-|&gt;', connectionstyle='arc3,rad=%s' % rad, mutation_scale=10.0, lw=2, alpha=alpha, color=color) seen[(u, v)] = rad ax.add_patch(e) return e G = nx.MultiDiGraph([(1, 2), (1, 1), (1, 2), (2, 3), (3, 4), (2, 4), (1, 2), (1, 2), (1, 2), (2, 3), (3, 4), (2, 4)] ) pos = nx.spring_layout(G) ax = plt.gca() draw_network(G, pos, ax) ax.autoscale() plt.axis('equal') plt.axis('off') plt.show()
tagged with: matplotlib
linked to: http://stackoverflow.com/q/14943439
tagged with: python
linked to: http://stackoverflow.com/q/39657395
upvote count: 13
tagged with: draw
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/26691442
answer count: 1

http://stackoverflow.com/q/49385744
favorite count: 0
has comment: http://stackoverflow.com/comment/85897074
tagged with: python
tagged with: sqlalchemy
has title: SQLAlchemy Date field less or equal query on empty value
type: Question
has comment: http://stackoverflow.com/comment/85870165
answer count: 0
has body: I have a problem querying records from MySql database with SQLAlchemy. This is my table: class CarLicenceData(Base): ... userIdOwner = sa.Column(sa.String(100)) MOTExpiry = sa.Column(sa.Date) ... And this is my query: now = datetime.datetime.now() car = session.query(CarLicenceData).filter(and_( CarLicenceData.MOTExpiry &lt;= now.date(), CarLicenceData.MOTExpiry != None, CarLicenceData.userIdOwner == 'eu-west-1:97923fc8-2b0f-4caa-b6b9-7974941073ec' )).one() print car &lt;CarLicenceData(1585)&gt; car.MOTExpiry is None True It returns record even if MOTExpiry is None. What's wrong here?
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: mysql
upvote count: 1
has comment: http://stackoverflow.com/comment/85810458

http://stackoverflow.com/a/49300938
upvote count: 3
has comment: http://stackoverflow.com/comment/85603816
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85603808
answers question: http://stackoverflow.com/q/49300900
downvote count: 0
type: Answer
has body: Dictionary comprehensions came along in Python 2.7. For Python 2.6, you can pass dict a sequence of key-value pairs. d = dict((k,0) for k in keys if k not in ('time_us', 'status'))
has comment: http://stackoverflow.com/comment/85603727
has comment: http://stackoverflow.com/comment/85603791
accepted answer of: http://stackoverflow.com/q/49300900
score: 3

http://stackoverflow.com/q/49341570
tagged with: data-science
type: Question
has comment: http://stackoverflow.com/comment/85904021
has comment: http://stackoverflow.com/comment/85684753
tagged with: python
has comment: http://stackoverflow.com/comment/85684586
has comment: http://stackoverflow.com/comment/85704884
score: 0
has body: In a dataset read into pandas with multiple columns two columns have for some rows the same values. When this is the case it seems that the column layout is inproperly interpreted by Pandas I'm almost a Pandas beginner so I certainly have not grasped all of pandas subtleties but this behaviour is weird to say the least.The dataset is the 2016 kickstarter projects from Kaggle, a zip file where I kept the 2016 dataset, I removed the other dataset. The set does have 12 columns and for a start I'm most interested in the 'main_category' and 'state'. I wanted to have an insight the most occurring main_categories together with the different states 'failed', 'successful', 'suspended' etc. I used the following code to 'sort this out': import numpy as np import pandas as pd ks = pd.read_csv('kickstarter-projects.zip', quotechar='"', encoding='latin1') ks['total']=ks.groupby('main_category').transform('count')['ID'] ks.groupby(['total','main_category','state']).count().reset_index().sort_values(['total','ID'], ascending=False) There was something strange about the result above however: the state contained the expected values mentioned above, but also some other numeric values. Inspecting the csv file, I found these values coming from an adjacent column, and only the case when the columns 'category' and 'main_category' shared the same values ('Publishing', 'Publishing') total main_category state counts-&gt; 638 34233 Publishing live 448 448 448 448 448 448 448 640 34233 Publishing suspended 51 51 51 51 51 51 626 34233 Publishing 0 2 2 2 2 2 2 2 627 34233 Publishing 1 2 2 2 2 2 2 2 Changing (globally) the category to something else like 'Pub lishing' in the CSV file, solved it and the numeric states disappeared. This behavior is consistent for other combinations like 'Music', 'Film &amp; Video'. What am I doing wrong or what is going wrong?
answer count: 0
has comment: http://stackoverflow.com/comment/85904127
tagged with: pandas
has comment: http://stackoverflow.com/comment/85704730
type: UnansweredQuestion
has title: Pandas column layout misinterpreted when 2 columns have same value?

http://stackoverflow.com/comment/85759587
comment on: http://stackoverflow.com/q/49379254
score: 0
type: Comment
type: QuestionComment
has text: How do i fix that

http://stackoverflow.com/q/49435971
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85919134
tagged with: python
tagged with: pyautogui
has body: so I have a problem with PyAutoGui! I have this code: import pyautogui import time import sys import os def run(): time.sleep(3) pyautogui.moveRel(30, 30) pyautogui.click() time.sleep(0.1) pyautogui.click() pyautogui.hotkey('ctrl', 'c') pyautogui.moveTo(1903, 2) pyautogui.click() pyautogui.moveTo(906, 1060) pyautogui.click() pyautogui.click() intervalvariable = 0.025 intervalvariablebetweenwords = 0.4 print("Please enter the first word and press Strg and v:") FullText = input() buttonlocation = None while buttonlocation == None: buttonlocation = pyautogui.locateOnScreen("button.png") buttonx, buttony = pyautogui.center(buttonlocation) pyautogui.moveTo(buttonx, buttony) pyautogui.moveRel(-20, 20) pyautogui.click() words = FullText.split(" ") for i in range(0, len(words)): if i == len(words)-4: intervalvariable = 0.015 intervalvariablebetweenwords = 0 pyautogui.typewrite(words[i], interval=intervalvariable); pyautogui.typewrite(" ", interval=0); time.sleep(intervalvariablebetweenwords) os.system('cls') print("Do You want to go again? If so, type 'YES' if not type something else!") Again = input() if Again == "YES": os.system('cls') run() else: os.system('cls') sys.exit("Ok!") run() And if i try to run it in the Python Shell it functions perfectly, but when I run it in the Command Prompt it just crashes at the point, where it tries to find the image (Its an image of some text, where it orients itself). When it searches the image in the Python shell it searches about 1 second and finds it and everything works but I cant even get the error Message from the Command Prompt, so I would be pleased if you could help me! Excuse my writing im German. :D
score: 0
tagged with: command-prompt
answer count: 0
has title: Programm with PyAutoGui working in Python Shell but not in Command Prompt
has comment: http://stackoverflow.com/comment/85926852
has comment: http://stackoverflow.com/comment/85926725
has comment: http://stackoverflow.com/comment/85916394
has comment: http://stackoverflow.com/comment/85928310
has comment: http://stackoverflow.com/comment/85879055
has comment: http://stackoverflow.com/comment/85912070

http://stackoverflow.com/q/49341343
tagged with: python
score: 0
tagged with: tkinter
tagged with: user-interface
has title: Destroying login page window and opening a new one
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85683566
type: UnansweredQuestion
has body: I'm trying to close a window while creating a new one. The following function runs once a login has been entered. Do you have any suggestions on how to close this window while the MenuPage(window) is opened? from tkinter import * class LoginPage(): def __init__(self): window = Tk() #UI to retrieve login details #While loop when submit is clicked. if UserLogins: #Maybe here a close window function is ran window = Toplevel() start= MenuPage(window) else: print('Incorrect Login') class MenuPage(object): #Menu UI if __name__ == '__main__': LoginPage()
has answer: http://stackoverflow.com/a/49367424
has comment: http://stackoverflow.com/comment/85684679

http://stackoverflow.com/comment/126039866
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49398706
has text: May I kindly draw your attention to a similar [question](https://stackoverflow.com/questions/71305465/how-can-plot-loss-curves-for-training-and-test-for-multi-output-regression-task).

http://stackoverflow.com/comment/85636480
has text: Ignoring an indentation error and assuming Python 2, your current code should work, although using `enumerate()` would be more pythonic
comment on: http://stackoverflow.com/q/49317638
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49386219
answer count: 0
has comment: http://stackoverflow.com/comment/85773366
has comment: http://stackoverflow.com/comment/85773532
type: Question
has body: I downloaded matplotlib wheel file and installed it using pip and it got successfully installed. But the matplotlib does not contain pyplot. What should I do? import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t) plt.plot(t, s) plt.xlabel('time (s)') plt.ylabel('voltage (mV)') plt.title('About as simple as it gets, folks') plt.grid(True) plt.savefig("test.png") plt.show() Error: import matplotlib.pyplot as plt ImportError: No module named pyplot
has title: Why I am getting this error "ImportError: No module named pyplot" while using matplotlib in Python
has comment: http://stackoverflow.com/comment/85817062
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85814099
score: 0

http://stackoverflow.com/a/49426694
has body: So you have two fields, one is name and the other is displayname, and you don't want to allow names which match with displaynames? If you want to prevent users to create the record, add a constraint to your partners model: @api.one @api.constrains('displayname', 'name', 'is_exist') def onchange_displayname(self): if self.displayname and self.is_exist is False: is_name_exist = self.env['your.partners.model'].search([('name', '=', self.displayname)]) if is_name_exist: raise ValidationError(_('Alread exist')) else: pass But, if you mean that the only thing you want is avoid two partners who have the same name, you'd better implement this functionality with a SQL constraint and using UNIQUE. Create it in your partners model: _sql_constraints = [ ('unique_name', 'unique(name)', 'Alread exist'), ] Another way (but not good) to manage what you want is to overwrite the partners ORM create method (this means that you should overwrite the ORM write method too): @api.model def create(self, vals): partner = super(YourPartnerModel, self).create(vals) if partner.displayname and partner.is_exist is False: is_name_exist = self.env['your.partner.model'].search([('name', '=', partner.displayname)]) if is_name_exist: self.is_exist = True raise ValidationError(_('Alread exist')) return partner
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49426612

http://stackoverflow.com/a/49348920
has comment: http://stackoverflow.com/comment/85700887
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85742475
score: 1
type: Answer
has body: You should use char* instead of void*. In addition, you should not use the %include &lt;std_string.i&gt; in the example.i file, as that has the typemap definition converting char * to a string. Minor issue: you example.cpp shall #include "example.hpp" to have a definition for MyTestCLass.
answers question: http://stackoverflow.com/q/49346490

http://stackoverflow.com/comment/85638125
score: 0
has text: I don't quite understand. If you have strings like 'Location1' in col A then how do you expect them to be plotted?
comment on: http://stackoverflow.com/q/49318170
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49345688
answers question: http://stackoverflow.com/q/49345665
has comment: http://stackoverflow.com/comment/85691175
has comment: http://stackoverflow.com/comment/85691531
has comment: http://stackoverflow.com/comment/85691696
has body: Try this :) {% csrf_token %} Log In {{ form.username }} {{ form.username.errors }} {{ form.password }} {{ form.password.errors }} Log In
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85691284
has comment: http://stackoverflow.com/comment/85691603
has comment: http://stackoverflow.com/comment/85691182

http://stackoverflow.com/a/49310125
has comment: http://stackoverflow.com/comment/85646271
has body: If you look at the signature of describe_images, you'll see that it accepts the arguments in the form of keyword args (commonly referred to as kwargs). With that signature and a bit of reading on expansion of iterables, you can dynamically build up the keyword args that you want to pass to the describe_images call. Here's a very simple example below of a function with the same signature that just echoes the keyword args it gets to give you insight into what the function call is actually receiving. def foo(**kwargs): print(kwargs) owners = None image_ids = None search_filters=['a', 'b'] describe_kwargs = {'ExecutableUsers':['all'], 'Filters':search_filters} foo(**describe_kwargs) # Now include image ids describe_kwargs['ImageIds'] = ['ami-26ebbc5c'] foo(**describe_kwargs) # Now include owners describe_kwargs['Owners'] = ['309956199498'] foo(**describe_kwargs) If you run this snippet, you'll see the following: {'ExecutableUsers': ['all'], 'Filters': ['a', 'b']} {'ExecutableUsers': ['all'], 'Filters': ['a', 'b'], 'ImageIds': ['ami-26ebbc5c']} {'ExecutableUsers': ['all'], 'Filters': ['a', 'b'], 'ImageIds': ['ami-26ebbc5c'], 'Owners': ['309956199498']} In your case, it sounds like you'd want to conditionally update the describe_kwargs dict with each of the Owners and ImageIds keys, based on whether "they are provided upstream".
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49307218
upvote count: 3
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49307218

http://stackoverflow.com/comment/85655533
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49326873
type: QuestionComment
has text: `addItem()` does not return anything so `x` will always be None.

http://stackoverflow.com/comment/85695141
comment on: http://stackoverflow.com/q/49347738
has text: I would suggest drawing Voronoi diagram, there should definitely be a python library for that.
type: Comment
type: QuestionComment
score: 1

selenium-chromedriver
tags question: http://stackoverflow.com/q/49292221
tags question: http://stackoverflow.com/q/49435873
tags question: http://stackoverflow.com/q/49298245
tags question: http://stackoverflow.com/q/49389789
tags question: http://stackoverflow.com/q/49290655
tags question: http://stackoverflow.com/q/49412238
tags question: http://stackoverflow.com/q/49325855
tags question: http://stackoverflow.com/q/49405337
tags question: http://stackoverflow.com/q/49436492
tags question: http://stackoverflow.com/q/49387548
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/49362476
tags question: http://stackoverflow.com/q/49323099
tags question: http://stackoverflow.com/q/49392693
tags question: http://stackoverflow.com/q/49345573
tags question: http://stackoverflow.com/q/49359146
tags question: http://stackoverflow.com/q/49404569
tags question: http://stackoverflow.com/q/49417445
tags question: http://stackoverflow.com/q/49368211
tags question: http://stackoverflow.com/q/49311344
tags question: http://stackoverflow.com/q/49411184
tags question: http://stackoverflow.com/q/49357755
tags question: http://stackoverflow.com/q/49434581
tags question: http://stackoverflow.com/q/49436756
type: Tag
tags question: http://stackoverflow.com/q/49402800
tags question: http://stackoverflow.com/q/49439807
tags question: http://stackoverflow.com/q/49289709
tags question: http://stackoverflow.com/q/49341172
tags question: http://stackoverflow.com/q/49439177

http://stackoverflow.com/comment/85594107
type: Comment
type: QuestionComment
has text: I am not sure if I've understood you. But to get frequent words, can't you just do nltk.tokenize, get count per word, sort it in descending order and get the top frequent words ?
comment on: http://stackoverflow.com/q/49295890
score: 0

http://stackoverflow.com/q/49342139
tagged with: sqlite
linked to: http://stackoverflow.com/q/3044580
tagged with: python
linked to: http://stackoverflow.com/q/4060772
type: Question
has body: I'm using a web API to call and receive data to build out an SQL database for historical energy prices. For context, energy prices are set at what are called "nodes", and each node has 20 years of historical data. I can receive the data in JSON or XML format. I need to do one operation with the received data before I put it into the SQL database. Namely, I need to convert each hour given in Eastern Daylight Time back to its Eastern Standard Time equivalent. Being brand new to Python (learned in last two weeks), I initially went down a path more intuitive to me: HTTP Request (XML format) -> Parse to XML object in Python -> Convert Datetime -> Place in SQL database The total size of the data I'm attempting to get is roughly 150GB. Because of this, I wanted to get the data in an asynchronous matter and format/put into SQL as it came in from hundreds of API calls (there's a 50000 row limit to what I can get at a time). I was using a ThreadPool to do this. Once the data was received, I attempted to use a ProcessPool to convert this data into the format I needed to place into my SQL database, but was unsuccessful. Looking at the process from a high level, I think this process can be a lot more efficient. I think I can do the following: HTTP Request (JSON Format) -> Parse to JSON object in Python -> Perform operation to convert datetime (map value using dictionary?) -> Place into SQL database I just discovered the OPENJSON library in Python. Is this all I need to do this? Another issue I need to look into are the limitations of SQLite3. Each node will have its own table in my database, so ideally I'd like to have as many instances of my program as possible getting, parsing, and putting data into my SQLite3 database. Any help would be much appreciated!
tagged with: api
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4748787
answer count: 1
has answer: http://stackoverflow.com/a/49350289
has title: Most efficient way to get HTTP Request Response into SQLite3 Database using Python?
tagged with: http
score: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/85741477
comment on: http://stackoverflow.com/q/49370023
type: Comment
type: QuestionComment
score: 0
has text: Also, even if you want to use a collection as a list, you may sometimes want to copy it to a set for some local operation. For example, the cost of making a temporary set of the elements of a list is linear; if that lets you turn a quadratic algorithm into a linear one, it's usually worth it.

http://stackoverflow.com/comment/85796924
type: QuestionComment
comment on: http://stackoverflow.com/q/49396531
type: Comment
score: 0
has text: Thanks for the help. Sorry if I didn't explain it properly. Everything I know about coding is pulled from stack exchange and vague recollections from a single college course.

http://stackoverflow.com/q/49399847
tagged with: keras
has answer: http://stackoverflow.com/a/49414179
has comment: http://stackoverflow.com/comment/85810285
downvote count: 1
favorite count: 0
type: Question
tagged with: python
score: -1
has body: I need of a RCNN structure to classify videos after extract frames with OpenCV. I've readed about and searched a lot for this structure, and reached this model in Keras: model = Sequential([ #Visual features learning TimeDistributed(Conv2D(units=128, kernel_size=5, strides=1, input_shape(28, 28, 1))), TimeDistributed(MaxPooling2D(pool_size=2)), Dropout(0.25), TimeDistributed(Conv2D(units=256, kernel_size=5, strides=1)), TimeDistributed(MaxPooling2D(pool_size=2)), Dropout(0.25), TimeDistributed(Conv2D(units=128, kernel_size=5, strides=1)), TimeDistributed(MaxPooling2D(pool_size=2)), Dropout(0.25), TimeDistributed(Conv2D(units=128, kernel_size=5, strides=1)), TimeDistributed(MaxPooling2D(pool_size=2)), Dropout(0.25), #Flatten TimeDistributed(Flatten()), #LSTM for sequence learning LSTM(units, activation, recurrent_activation, use_bias), #FC Dense(units=500, activation='relu'), Dropout(0.25), Dense(units=4, activation='softmax') ]) I could adapt this structure (or use it directly) to learn features from image data and time with the LSTM layer? If not, how i have to adapt this module correctly? OBS: The hyperparameters in this example is just for, obviously, an example. I still have to find a manner to parametrize the LSTM layer to make it work. Thanks for the support!
tagged with: recurrent-neural-network
has title: RCNN with TimeDistributed for Video Classification
upvote count: 0
has comment: http://stackoverflow.com/comment/85828664
type: UnansweredQuestion
answer count: 1
tagged with: machine-learning
tagged with: computer-vision

http://stackoverflow.com/q/49417328
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/51020940
type: UnansweredQuestion
has body: I have an excel sheet which contains calculations using formulas. It been manually updated each month but basically I working towards automating it. I have read a lot on how to use openpyxl but I wanted to read values not formulas which is why i found xlwings. Now I finding difficulty in finding coordintes of cell in xlwings. Its pretty straightforward in openpyxl cell.coordinate and want something similar to that. I am pretty new to python so plz dont mind my syntax. I have read the excel sheet into sheet1 variable and I am just trying to find the date in the first 50X50 matrix in the sheet. This is the for loop: for row in range(50): for col in range(50): if sheet1.range(row,col).value == '12/1/2017': print ((row,col)) Now I know .value in xlwings returns datetime and I am comparing it to a date and I found the workaround using something from the this -->http://docs.xlwings.org/en/stable/converters.html import datetime as dt sht.range('A1').options(dates=dt.date).value But I am not getting how should I implement it. At the end I am getting the error return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) This error doesnt seem to be related to what I think I am doing, but i cant seem to troubleshoot this problem.
tagged with: python
has title: xlwings - find a cell coordinate containing a value(a date)
tagged with: xlwings
score: 0

jupyter-notebook
tags question: http://stackoverflow.com/q/49421631
tags question: http://stackoverflow.com/q/49301857
tags question: http://stackoverflow.com/q/49361804
tags question: http://stackoverflow.com/q/49326860
tags question: http://stackoverflow.com/q/49296346
tags question: http://stackoverflow.com/q/49291335
tags question: http://stackoverflow.com/q/49320481
tags question: http://stackoverflow.com/q/49326410
tags question: http://stackoverflow.com/q/49408285
tags question: http://stackoverflow.com/q/49306907
tags question: http://stackoverflow.com/q/49300516
tags question: http://stackoverflow.com/q/49379200
tags question: http://stackoverflow.com/q/49306352
tags question: http://stackoverflow.com/q/49295824
tags question: http://stackoverflow.com/q/49404585
tags question: http://stackoverflow.com/q/49430316
tags question: http://stackoverflow.com/q/49282122
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/49287271
tags question: http://stackoverflow.com/q/49360888
tags question: http://stackoverflow.com/q/49393518
tags question: http://stackoverflow.com/q/49374308
tags question: http://stackoverflow.com/q/49332326
tags question: http://stackoverflow.com/q/49299392
tags question: http://stackoverflow.com/q/49311270
tags question: http://stackoverflow.com/q/49286228
tags question: http://stackoverflow.com/q/49435621
type: Tag
tags question: http://stackoverflow.com/q/49375620
tags question: http://stackoverflow.com/q/49397772
tags question: http://stackoverflow.com/q/49324569
tags question: http://stackoverflow.com/q/49373823
tags question: http://stackoverflow.com/q/49419672
tags question: http://stackoverflow.com/q/49365683
tags question: http://stackoverflow.com/q/49340776
tags question: http://stackoverflow.com/q/49319227
tags question: http://stackoverflow.com/q/49376612
tags question: http://stackoverflow.com/q/49316971
tags question: http://stackoverflow.com/q/49303168
tags question: http://stackoverflow.com/q/49428381
tags question: http://stackoverflow.com/q/49438070
tags question: http://stackoverflow.com/q/49336436
tags question: http://stackoverflow.com/q/49347477
tags question: http://stackoverflow.com/q/49436155

http://stackoverflow.com/a/49362805
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49362449
answers question: http://stackoverflow.com/q/49362449
has comment: http://stackoverflow.com/comment/85725703
downvote count: 0
has body: To answer your question with a similar approach to your example, and including your comment: Yes that works in this case, @internet_user also suggested this. But what if the indices I need are not consecutive, i.e. I need 0 and 2? The with...as... syntax is for context managers, which has a totally different use. However, a work-around is to use for-loop unpacking. var = [['x_A_B', 1], ['x_A_C', 1], ['x_B_A', 1], ['x_B_D', 1], ['x_C_A', 1], ['x_C_D', 1], ['x_D_B', 1], ['x_D_C', 1]] var2 = [(u, v) for item in var for _, u, v in (item[0].split("_"), )] print(var2)
upvote count: 1
score: 1

http://stackoverflow.com/a/49314607
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85666996
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49307866
type: AcceptedAnswer
downvote count: 0
has body: You've got the equation there. If c_i = (i, j, k) is the center cell in the Hough space S, and normally you'd just increase S[i, j, k] += 1, now you do: S[i + di, j + dj, k + dk] += exp( -(di**2 + dj**2 + dk**2)/(2*(sigma**2)) ) for all values of di, dj and dk in the range [-2,2]. Of course, you would use the pre-computed values for speed. I'm sure you can use slicing in some way: S[i-2:i+3, j-2:j+3, k-2:k+3] = S[i-2:i+3, j-2:j+3, k-2:k+3] + gauss_weights To avoid having to check for out-of-bounds indexing in the above (which complicates code and slows things down) I recommend that you expand your Hough space by two cells on all sides. If you need periodic boundary conditions (e.g. for the angle axis) then you can, after computing the Hough space, take the 2-cell margin on either side of that dimension and add it to the opposite side: S[:, :, 2:4] = S[:, :, 2:4] + S[:, :, -2:] S[:, :, -4:-2] = S[:, :, -4:-2] + S[:, :, 0:2]
answers question: http://stackoverflow.com/q/49307866
has comment: http://stackoverflow.com/comment/85665888

http://stackoverflow.com/a/49385878
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49385748
has body: How about sum(map(lambda n: (C(36,n))*((-1)**(n+1))*0,23*(0,29**(n-1)), range(1, 36+1)))?
type: Answer

http://stackoverflow.com/comment/85603926
type: QuestionComment
has text: I don't understand why `'service': 'A 2000 B 3000'`?
score: 0
comment on: http://stackoverflow.com/q/49300970
type: Comment

http://stackoverflow.com/a/49328253
has comment: http://stackoverflow.com/comment/85658419
accepted answer of: http://stackoverflow.com/q/49328171
has body: I think the most used example of closure is for caching functions with a decorator. def cache_decorator(f): cache = {} def wrapper(*args): if args not in cache: cache[args] = f(*args) return cache[args] return wrapper @cache_decorator def some_function(*args): ... This way the cache cannot be referenced from anywhere, since you do not want your users to tamper with it.
downvote count: 0
has comment: http://stackoverflow.com/comment/85658567
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85658596
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/85658462
has comment: http://stackoverflow.com/comment/85658376
answers question: http://stackoverflow.com/q/49328171
type: Answer

http://stackoverflow.com/q/49281224
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49281476
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/49281348
has answer: http://stackoverflow.com/a/49281476
has body: I have loaded my data into pandas dataframe and one of the columns in my dataframe has values like the following. I need to count each fruits count and pass on its value to a dataprovider for plotting a graph. ************************ Data in the Dataframe ************************ orange apple grapes mango orange orange orange mango apple For example, I wanted to pass the values into the dataProvider in the below format. "dataProvider": [{ "flavor": "orange", "count": 4 }, { "flavor": "apple", "count": 2 }, { "flavor": "grapes", "count": 1 }, { "flavor": "mango", "count": 2 }], Basically what I wanted to get is the following format from the above data. [{ "flavor": "orange", "count": 4 }, { "flavor": "apple", "count": 2 }, { "flavor": "grapes", "count": 1 }, { "flavor": "mango", "count": 2 }]
has answer: http://stackoverflow.com/a/49281348
downvote count: 1
favorite count: 0
type: Question
has title: Formatting Pandas Dataframe for Plotting a Graph

http://stackoverflow.com/q/49283575
has title: Django channels 'No application configured for scope type 'websocket''
favorite count: 0
type: Question
downvote count: 0
tagged with: django-channels
has body: I am trying to implement a chat with Django and channels according to this tutorial (http://channels.readthedocs.io/en/latest/tutorial/part_2.html). I add channels and a chat app to installed apps. I make the following routings for a project: # mysite/routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # (http-&gt;django views is added by default) }) Basically, I did exactly the steps from the tutorial. But after runserver I am still getting ValueError: No application configured for scope type 'websocket', after going to a specific chat room. Can please someone help me?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85570268
answer count: 1
accepted answer: http://stackoverflow.com/a/49284073
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/85570118
score: 3
has answer: http://stackoverflow.com/a/49284073

http://stackoverflow.com/q/49325168
accepted answer: http://stackoverflow.com/a/49406287
tagged with: parallel-processing
tagged with: pyomo
type: AnsweredQuestion
has title: Pyomo parallel processing to solve an instance
answer count: 2
tagged with: mathematical-optimization
downvote count: 0
possible better answer: http://stackoverflow.com/a/67270976
has comment: http://stackoverflow.com/comment/85679711
has comment: http://stackoverflow.com/comment/85652676
score: 1
upvote count: 1
has body: I'm following the steps here in order to use all my computing power (10-core Intel i9 CPU) and solve a one-instance abstract Pyomo model. However, it seems that the solver is just using one CPU core and it takes more than 2 days to return a solution for a 50-node input (with 10 nodes it just takes seconds.) any help about making Pyomo model run in all available CPU cores? Thanks
has answer: http://stackoverflow.com/a/67270976
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85681798
has comment: http://stackoverflow.com/comment/85661514
has comment: http://stackoverflow.com/comment/85653572
tagged with: python
has answer: http://stackoverflow.com/a/49406287

http://stackoverflow.com/q/49415031
has title: Showing duplicates in columns of csv files
has comment: http://stackoverflow.com/comment/85831908
tagged with: python
has comment: http://stackoverflow.com/comment/85831727
has comment: http://stackoverflow.com/comment/85833087
tagged with: python-3.x
has body: I am trying to read a particular column ("Labels") of any .csv file in a path. Then I want to print each duplicate and the number of times that duplicate appeared. import os import csv from collections import Counter items = [] directory = os.path.join("c:\\","Users\Bob\Desktop\CSVs") for root,dirs,files in os.walk(directory): for file in files: if file.endswith(".csv"): with open(file) as csvFile: reader = csv.DictReader(file) for row in reader: items.append(row["Labels"]) print(row) counted = dict(Counter(items)) print(counted) I get the following error File "C:/Users/Bob/Desktop/CSVs/Dupe Check.py", line 14, in &lt;module&gt; items.append(row["Labels"]) KeyError: 'Labels' The labels column is always the second column of the csv files.
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49417269
has comment: http://stackoverflow.com/comment/85831939
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85832259

http://stackoverflow.com/q/49362719
possible better answer: http://stackoverflow.com/a/49362870
tagged with: nsregularexpression
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49362870
has answer: http://stackoverflow.com/a/49362780
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85725494
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/49362780
answer count: 2
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85725870
has body: I am trying to know a position of a string (word) in a sentence. I am using the function below. This function is working perfectly for most of the words but for this string GLC-SX-MM= in the sentence I have a lot of GLC-SX-MM= in my inventory list there is no way to get the match. I tryied scaping - and = but not works. Any idea? I cannot split the sentence using spaces because sometimes I have composed words separated by space. import re def get_start_end(self, sentence, key): r = re.compile(r'\b(%s)\b' % key, re.I) m = r.search(question) start = m.start() end = m.end() return start, end
has title: Searching for a whole word that contains leading or trailing special characters like - and = using regex in python

http://stackoverflow.com/comment/85833873
comment on: http://stackoverflow.com/q/49415878
score: 1
type: Comment
has text: I don't see a duplication problem; I just see a naming problem.
type: QuestionComment

http://stackoverflow.com/comment/85664177
has text: @DanielRoseman We do not know if it is a valid JSON string. If it is not, then regex is the only option.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49331077
type: Comment

http://stackoverflow.com/q/49284015
has title: How to check if folder is empty with Python?
has answer: http://stackoverflow.com/a/70285710
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85570976
has answer: http://stackoverflow.com/a/70697160
has comment: http://stackoverflow.com/comment/85571321
has answer: http://stackoverflow.com/a/54034774
upvote count: 89
has answer: http://stackoverflow.com/a/66391830
tagged with: python
has comment: http://stackoverflow.com/comment/85571809
answer count: 11
linked to: http://stackoverflow.com/q/25675352
has answer: http://stackoverflow.com/a/49284243
has answer: http://stackoverflow.com/a/49284330
tagged with: python-2.7
linked to: http://stackoverflow.com/q/59268696
has comment: http://stackoverflow.com/comment/85570956
has answer: http://stackoverflow.com/a/59050548
has body: I am trying to check if a folder is empty and do the following: import os downloadsFolder = '../../Downloads/' if not os.listdir(downloadsFolder): print "empty" else: print "not empty" Unfortunately, I always get "not empty" no matter if I have any files in that folder or not. Is it because there might be some hidden system files? Is there a way to modify the above code to check just for not hidden files?
score: 88
has answer: http://stackoverflow.com/a/72442010
has answer: http://stackoverflow.com/a/70763308
downvote count: 1
has answer: http://stackoverflow.com/a/66481406
favorite count: 0
has answer: http://stackoverflow.com/a/49284171
type: Question

http://stackoverflow.com/q/49412132
tagged with: reticulate
tagged with: http://stackoverflow.com/tag/r
answer count: 2
upvote count: 1
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49440928
possible better answer: http://stackoverflow.com/a/49440928
has title: R, python, reticulate, and limmbo: cast array 'float64' to 'int64' error
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I am trying to use the python module limmbo (https://github.com/HannahVMeyer/limmbo) with R via the reticulate R package. I have successfully installed limmbo with Anaconda2. I'm now trying to use the function limmbo$core$vdbootstrap$LiMMBo$runBootstrapCovarianceEstimation, as in my code below. When I run the code below, I get an error about converting a float64 to an integer64. ```{r} library(reticulate) import("limmbo") -&gt; limmbo ``` I then run the python code: ```{python} import numpy from numpy.random import RandomState from numpy.linalg import cholesky as chol from limmbo.core.vdsimple import vd_reml from limmbo.io.input import InputData random = RandomState(15) N = 100 S = 1000 P = 3 snps = (random.rand(N, S) &lt; 0.2).astype(float) kinship = numpy.dot(snps, snps.T) / float(10) y = random.randn(N, P) pheno = numpy.dot(chol(kinship), y) pheno_ID = [ 'PID{}'.format(x+1) for x in range(P)] samples = [ 'SID{}'.format(x+1) for x in range(N)] datainput = InputData() datainput.addPhenotypes(phenotypes = pheno, phenotype_ID = pheno_ID, pheno_samples = samples) datainput.addRelatedness(relatedness = kinship, relatedness_samples = samples) ``` The problem arises when I try to run the R function limmbo$core$vdbootstrap$LiMMBo$runBootstrapCovarianceEstimation: ```{r} (limmbo$core$vdbootstrap$LiMMBo(py$datainput, timing = TRUE, iterations = 100, S = 2) -&gt; foo) limmbo$core$vdbootstrap$LiMMBo$runBootstrapCovarianceEstimation(foo, cpus = 1, seed = 12345) ``` Error in py_call_impl(callable, dots$args, dots$keywords) : TypeError: Cannot cast array from dtype('float64') to dtype('int64') according to the rule 'safe' Detailed traceback: File "/Users/frederickboehm/anaconda2/lib/python2.7/site-packages/limmbo/core/vdbootstrap.py", line 96, in runBootstrapCovarianceEstimation minCooccurrence=minCooccurrence) File "/Users/frederickboehm/anaconda2/lib/python2.7/site-packages/limmbo/core/vdbootstrap.py", line 353, in __generateBootstrapMatrix rand_state = np.random.RandomState(s…
tagged with: python
has answer: http://stackoverflow.com/a/49439257
accepted answer: http://stackoverflow.com/a/49439257

http://stackoverflow.com/a/49331792
answers question: http://stackoverflow.com/q/49331782
has comment: http://stackoverflow.com/comment/85667692
has comment: http://stackoverflow.com/comment/85666653
has body: The following answer is true only for "old-style" Python-2.7 identifiers; "validVariable".isidentifier() #True "992variable".isidentifier() #False Since you changed your question after I posted the answer, consider writing a regular expression: re.match(r"[_a-z]\w*$", yourstring,flags=re.I)
has comment: http://stackoverflow.com/comment/85667281
type: Answer
has comment: http://stackoverflow.com/comment/85668330
has comment: http://stackoverflow.com/comment/85665661
has comment: http://stackoverflow.com/comment/85665706
downvote count: 0
has comment: http://stackoverflow.com/comment/85665687
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/85665747
has comment: http://stackoverflow.com/comment/85665723

http://stackoverflow.com/comment/85649157
score: 0
comment on: http://stackoverflow.com/q/49323740
has text: @AnkushRathi Thanks, I will look into this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49439055
has comment: http://stackoverflow.com/comment/85880122
tagged with: pandas
has comment: http://stackoverflow.com/comment/85880199
has title: Depreciation Warning with Dateutil _timelex
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85880140
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: time-series
type: Question
has body: So I have been using a function to merge time series data, and just yesterday I started seeing this depreciation error when using it: C:\Users\user\PycharmProjects\Hydrostats_tests\venv1\lib\site- packages\dateutil\parser\__init__.py:46: DeprecationWarning: _timelex is a private class and may break without warning, it will be moved and or renamed in future versions. warnings.warn(msg, DeprecationWarning) The code I am running is below, and I am using a package that I made. import os import hydrostats.data as hd sim_dir = r'C:\Users\user\Documents\Data\interim_raw_data' obs_dir = r'C:\Users\user\Documents\Data\recorded_raw_data' sim_path = [os.path.join(sim_dir, d) for d in os.listdir(sim_dir)] obs_path = [os.path.join(obs_dir, d) for d in os.listdir(obs_dir)] visual_df = hd.merge_data(sim_path[0], obs_path[0]) Here is the merge data function: def merge_data(predicted_file_path, recorded_file_path, interpolate=None, column_names=['Simulated', 'Observed'], predicted_tz=None, recorded_tz=None, interp_type='pchip'): if predicted_tz is None and recorded_tz: print('Either Both Timezones are required or neither') elif predicted_tz and recorded_tz is None: print('Either Both Timezones are required or neither') elif predicted_tz is None and recorded_tz is None and interpolate is None: # Importing data into a data-frame df_predicted = pd.read_csv(predicted_file_path, delimiter=",", header=None, names=[column_names[0]], index_col=0, infer_datetime_format=True, skiprows=1) df_recorded = pd.read_csv(recorded_file_path, delimiter=",", header=None, names=[column_names[1]], index_col=0, infer_datetime_format=True, skiprows=1) # Converting the index to datetime type df_recorded.index = pd.to_datetime(df_recorded.index, infer_datetime_format=True) df_predicted.index = pd.to_datetime(df_predicted.index, infer_datetime_format=True) return pd.DataFrame.join(df_predicted, df_recorded).dropna() The error occurs at these two lines df_recorded.index=pd.to_datetime(df_recorded.index,infer_da…
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85880232

http://stackoverflow.com/a/49415956
type: Answer
has comment: http://stackoverflow.com/comment/85846021
answers question: http://stackoverflow.com/q/49413588
has comment: http://stackoverflow.com/comment/85849761
score: 0
has body: Rename src to myPythonProject. Pyramid is one example that follows this convention. Another example is explained in this issue for Pyramid and examples in hupper and pyramid_retry. However, you'll still have MyPythonProject/src/MyPythonProject, which although more unwieldly might not be as unsightly. Ultimately whatever you name the directory that is the immediate parent that contains your package shall become the first part of the method's Python dotted name.

http://stackoverflow.com/q/49348921
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/86208416
has comment: http://stackoverflow.com/comment/85697609
has title: youtube-dl error outdated python
tagged with: python
tagged with: youtube-dl
has body: when i try to download content from vrtnu.be, youtube-dl always returns the same error. Can somebody help me? youtube-dl -v --username janvankerckhoven@gmail.com --password xxxxxx -fmp4 https://www.vrt.be/vrtnu/a-z/een-kwestie-van-geluk/seizoen-1/een-kwestie-van-geluk-d20180121-sseizoen-1a1/ [debug] System config: [] [debug] User config: [] [debug] Custom config: [] [debug] Command-line args: [u'-v', u'--username', u'PRIVATE', u'--password', u'PRIVATE', u'-fmp4', u'https://www.vrt.be/vrtnu/a-z/een-kwestie-van-geluk/seizoen-1/een-kwestie-van-geluk-d20180121-sseizoen-1a1/'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2018.03.14 [debug] Python version 2.7.5 (CPython) - Darwin-13.4.0-x86_64-i386-64bit [debug] exe versions: ffmpeg 3.4.2, ffprobe 3.4.2 [debug] Proxy map: {} [VrtNU] Logging in [VrtNU] Requesting a token [VrtNU] een-kwestie-van-geluk-d20180121-sseizoen-1a1: Downloading webpage ERROR: Unable to download webpage: &lt;urlopen error [Errno 1] _ssl.c:504: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure&gt; (caused by URLError(SSLError(1, '_ssl.c:504: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure'),)) File "/usr/local/bin/youtube-dl/youtube_dl/extractor/common.py", line 519, in _request_webpage return self._downloader.urlopen(url_or_request) File "/usr/local/bin/youtube-dl/youtube_dl/YoutubeDL.py", line 2199, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open response = self._open(req, data) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open '_open', req) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/usr/local/bin/youtube-dl/youtube_dl/utils.py", line 1101, in https_open …
score: 0

http://stackoverflow.com/a/49435131
has comment: http://stackoverflow.com/comment/109193305
has body: While there are probably ways to do this within the python ecosystem such as watchdog/watchmedo ( https://github.com/gorakhargosh/watchdog ), and maybe even linux scripting options with inotifywait ( https://linux.die.net/man/1/inotifywait ), for me, the easiest solution by far was... to just use nodemon! What I didn't know is that although the github tagline of nodemon is "Monitor for any changes in your node.js application and automatically restart the server - perfect for development" actually nodemon is a delicously generic tool and knows that .py files should be executed with python for example. Here's where I think the magic happens: https://github.com/remy/nodemon/blob/c1211876113732cbff78eb1ae10483eaaf77e5cf/lib/config/defaults.js End result is that the command line below totally works. Yay! $ nodemon hello.py [nodemon] starting `python hello.py`
has comment: http://stackoverflow.com/comment/118153338
has comment: http://stackoverflow.com/comment/118196104
type: AcceptedAnswer
score: 171
type: Answer
has comment: http://stackoverflow.com/comment/109254992
has comment: http://stackoverflow.com/comment/118087765
has comment: http://stackoverflow.com/comment/137761523
has comment: http://stackoverflow.com/comment/118183180
has comment: http://stackoverflow.com/comment/137897966
accepted answer of: http://stackoverflow.com/q/49355010
downvote count: 1
has comment: http://stackoverflow.com/comment/139058861
upvote count: 172
answers question: http://stackoverflow.com/q/49355010
has comment: http://stackoverflow.com/comment/118195032

http://stackoverflow.com/comment/85790904
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49380884
has text: Just for kicks, try `img.compression="lzw"` to see if it has an effect.

http://stackoverflow.com/comment/85777999
has text: Hi thank you for this: you are right about the memory: when I try your code on my own data- at the step where broadcasted array is created I immediately get a 'MemoryError' (and my computer is also quite powerful). I will have to split the whole thing into intervals... Would this be possible with 'Dask' i.e. make a function out of your code and then use `dd.delayed(function)(i) for i in split_data` or is there a better way of doing this?
type: AnswerComment
comment on: http://stackoverflow.com/a/49386724
type: Comment
score: 0

http://stackoverflow.com/q/49307970
has title: How to test QtQuick Qml in Python
tagged with: python
has body: I'm using PyQt to integrate QtQuick into my Python app. I'm trying to figure out the best way to test my QtQuick Qml pages within a Python unittest framework. I'd like to pass a list of Qml files to some test function that makes sure no errors/exceptions exist for any of these files. Currently I'm trying to load a page into QQmlComponent and check for errors, but I haven't been able to get this working: def test_qml(self): app = QApplication(sys.argv) engine = QQmlApplicationEngine() rel = "/gui/QT/Page1.qml" c = QQmlComponent(engine, QUrl.fromLocalFile(SRC_PATH + os.path.normpath(rel))) print(c.errors()) Moreover from what I've read I think to get show errors with QQmlComponent I should catch a signal onStatusChange and then check so this seems like the wrong approach for me. What is the best way to go about trying to test qml pages in Python?
type: Question
accepted answer: http://stackoverflow.com/a/49308363
tagged with: pyqt
downvote count: 0
answer count: 1
tagged with: pyqt5
upvote count: 1
favorite count: 0
tagged with: qt
type: AnsweredQuestion
tagged with: qml
score: 1
has answer: http://stackoverflow.com/a/49308363

http://stackoverflow.com/comment/85620026
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49308718
has text: @chepner, there is no requirement to change the sequence for it to be monotonically increasing.

http://stackoverflow.com/comment/85790067
has text: I'm now getting " Cannot find reference 'zeros' ". Tried importing numpy again and confirmed it's already imported
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49393055
type: Comment

http://stackoverflow.com/comment/85622198
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49309927
has text: Do you understand how this would be done in pure C? I don't see how the introduction of python would introduce any problems here.
score: 0

http://stackoverflow.com/q/49327416
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has comment: http://stackoverflow.com/comment/85662186
favorite count: 0
type: Question
has title: Checkbox filter in python/django
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85661407
has body: I have two div's in my code. Left div has category names and right div has category names, title, and description. Right div values are coming from DB. I am basically trying to build a checkbox filter functionality in python/django when you click on a category on the left, right div shows the category selected with all the information. By default it shows all the categories and all details. Here is the code that I have: HTML FILE {% for category in Categories %} {% if 'Sr' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'At' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'Inter' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'TRN' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'OTP' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'FIE' in category.label_name %} {{category.label_name}} {{category.name}} {% elif 'DEL' in category.label_name %} {{category.label_name}} {{category.name}} {% endif %} {% endfor %} {% for model in Data %} {{model.name}} {{model.sub_name}} {% if "At" in model.label_name %} {{model.label_name}} {% elif "Sr" in model.label_name %} {{model.label_name}} {% elif "OTP" in model.label_name %} {{model.label_name}} {% elif "DEL" in model.label_name %} {{model.label_name}} {% endif %} {{model.description}} {% if "Ats" in model.name %} {{model.link1_name}} {{model.link2_name}} {{model.link3_name}} {% elif "CC" in model.name %} {{model.link1_name}} {{model.link3_name}} {% elif "Plan" in model.name %} {{model.link1_name}} {{model.link3_name}} {% elif "Corr" in model.name %} {{model.link1_name}} {{model.link2_name}} {{model.link3_name}} {% elif "RED" in model.name %} {{model.link3_name}} {% elif "Penr" in model.name %} {{model.link1_name}} {{model.link2_name}} {{model.link3_name}} {% endif %} {% endfor %} views.py FILE from django.http import HttpResponse from django.shortcuts import render from abcd.models import …
score: 1

http://stackoverflow.com/comment/85823983
score: 0
type: Comment
has text: BTW, what are your thoughts on whether it would be fair/accurate to retitle this "*Is a context manager needed to force a close() if a program will exit right after the write?*"? I'd argue that that's a title that better communicates the question to its wider audience of Python developers writing short-lived programs -- the content of the question isn't really specific to JSON (that it's `json.write(prefs, prefs_file)` doing the writes vs `prefs_file.write("whatever")` is effectively immaterial for purposes of whether/when a flush is guaranteed to take place).
comment on: http://stackoverflow.com/q/49410886
type: QuestionComment

http://stackoverflow.com/q/49328313
favorite count: 0
type: Question
tagged with: self-organizing-maps
has body: I am trying to group things together, using a self organising map (SOM), and U-matrix that look like the following things: Fig 1: Self organising map (SOM) of light curves Fig 2: U-matrix for the above SOM Fig 3: local maxima for above U-matrix Figure 3 is drawn using plt.imshow, and is made of a 2D array of values between 0 and 1 to define colour. I want to interpolate and extrapolate the lines in Fig 3 to join up, allowing the graph to be separated into 6 regions. I am a bit stuck on how I might do this, and was wondering if anybody has any ideas? I'm not necessarily looking for code, I would mostly like an idea of how to get started. For anyone interested in the background of what I am doing here are some bits and pieces, but this is not necessary for my question. The things are light curves Stuff on what a SOM is and how it's made What is a U-matrix, and how is it made
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85658853
has title: Interpolating/Extrapolating values in 2D array to lines
tagged with: python
tagged with: extrapolation
score: 2
tagged with: interpolation
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/85706998
type: AnswerComment
has text: It's common to see super used to inherit some attributes and then also set some additional attributes that don't come along with the parent class. So in this case, you'd be indifferent between order.
type: Comment
comment on: http://stackoverflow.com/a/49353263
score: 0

http://stackoverflow.com/comment/85670338
type: Comment
type: QuestionComment
has text: I am not sure I understand your goal. Do you know all the parent OIDs already? So you want to run GETNEXT for each of the parent OIDs to fetch all sub-OIDs per each parent OID in parallel?
score: 1
comment on: http://stackoverflow.com/q/49307045

http://stackoverflow.com/comment/85576825
comment on: http://stackoverflow.com/a/49283519
type: AnswerComment
score: 0
type: Comment
has text: OK..I set my levels in intervals of 5 though and the colorbar labels are in intervals of 15. Any way to force that to intervals of 10? I tried a couple of things that I found on here but no luck yet.

http://stackoverflow.com/q/49346792
has comment: http://stackoverflow.com/comment/85698216
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85693372
tagged with: django
type: Question
has body: I am trying to overwrite a method, however, it does not take request as parameter. Basically, I want to add a condition depending on the request user and I can add a small example: def has_to_be_overwritten(queryset=None, *args, **kwargs): if request.user.is_superuser: do magic else: no magic Is this possible or should I look for a different solution?
has comment: http://stackoverflow.com/comment/85693312
tagged with: python
has comment: http://stackoverflow.com/comment/85693495
has comment: http://stackoverflow.com/comment/85693503
has comment: http://stackoverflow.com/comment/85693450
score: 0
has title: Using request when it is not passed as parameter
answer count: 0

http://stackoverflow.com/a/56131441
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49413005
has body: Function to replace multiple values in pandas Series: def replace_values(series, to_replace, value): for i in to_replace: series = series.str.replace(i, value) return series Hope this helps someone

http://stackoverflow.com/q/49384608
answer count: 3
upvote count: 1
downvote count: 3
tagged with: web
has answer: http://stackoverflow.com/a/50530935
has body: I am trying to run the code using python(scrapy) but there is no output. I am also tyring to login to a webpage, let me know if there are any errors The code i am using is this: class MySpider(Spider): def init(self, login, password): link = "http://freeerisa.benefitspro.com" self.login = login self.password = password self.cj = cookielib.CookieJar() self.opener = urllib2.build_opener( urllib2.HTTPRedirectHandler(), urllib2.HTTPHandler(debuglevel=0), urllib2.HTTPSHandler(debuglevel=0), urllib2.HTTPCookieProcessor(self.cj) ) self.loginToFreeErissa() self.loginToFreeErissa() def loginToFreeErissa(self): login_data = urllib.urlencode({ 'MainContent_mainContent_txtEmail' : self.login, 'MainContent_mainContent_txtPassword' : self.password, }) response = self.opener.open(link + "/login.aspx", login_data) return ''.join(response.readlines()) def after_login(self, response): if "Error while logging in" in response.body: self.logger.error("Login failed!") else: url = [link + "/5500/plandetails.aspx?Ein=042088633", link + "/5500/plandetails.aspx?Ein=046394579"] for u in url: g_data =soup.find_all("span") for item in g_data: return item.text I tried calling the function and this is the error I received: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\ProgramData\Anaconda3\lib\site-packages\scrapy\spiders_init_.py",line 30, in init raise ValueError("%s must have a name" % type(self).__name__) ValueError: MySpider must have a name
has title: python scrapy code not giving any output
tagged with: scrapy
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/49384816
tagged with: python
has answer: http://stackoverflow.com/a/50530681

http://stackoverflow.com/comment/85701261
has text: @BobSingh In this case it looks like you're trying to access something inside of an object you expect to be a container (list, tuple, etc), but the object has been defined as None.
comment on: http://stackoverflow.com/a/49328156
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85638828
score: 0
has text: oh yes sorry it's non-alpha only. Thanks for your link, could you explain what is \1 ? why does it match the 'd' of the first 'word' ?
comment on: http://stackoverflow.com/q/49318551
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85857545
score: 0
type: Comment
type: QuestionComment
has text: There is no such way. You need to either import modules (zeromq would probably help but there are others) or you need to loop somewhere. You can only decide what your loop actually does - are you checking for multiple queues or pipes, or are you managing your internal task list and executing tasks from it or shutting them down. The killer here is the need to interrupt a task. Without this it would be a typical use case for a `Pool()` but as you need to intervene with a running task, this is out. You need to write your own version of pool with this functionality.
comment on: http://stackoverflow.com/q/49426565

http://stackoverflow.com/comment/85580205
has text: Thank you so much for your answer, I just tried on it and there is still some problem, I added the code to my question if you could take a look at it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49288131
type: Comment

http://stackoverflow.com/comment/85725365
type: AnswerComment
score: 1
has text: @timgeb Sorry for that, I just stumble upon this problem multiple times, and I was interested in a very general solution. But I admit the current example I gave is an easier one.
comment on: http://stackoverflow.com/a/49362594
type: Comment

http://stackoverflow.com/comment/85829499
comment on: http://stackoverflow.com/q/49413944
type: Comment
type: QuestionComment
has text: show your code as text.
score: 0

http://stackoverflow.com/comment/85862196
has text: @BaileyParker "unless you're compiling against a python implementation and manually calling into" - that is what a library looks like (think about shared objects, dll-s, whatever). "presumably undocumented APIs" - why would it be undocumented? https://docs.python.org/3/extending/embedding.html - it is completely official and documented.
comment on: http://stackoverflow.com/q/49429412
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85723685
has text: @MarkRotteveel, I install _libfbclient2_ already, but still the error is displayed.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49360384
type: QuestionComment

http://stackoverflow.com/comment/85768660
comment on: http://stackoverflow.com/q/49383601
type: Comment
type: QuestionComment
has text: that's okay! just edit it and people would be able to answer you better :) also look at https://stackoverflow.com/help/how-to-ask
score: 0

http://stackoverflow.com/q/49319715
has title: Run Python in background of NodeJS
type: AnsweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/23450534
tagged with: node.js
type: Question
accepted answer: http://stackoverflow.com/a/49320175
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49320175
has body: I'm not sure what I'm trying to do is possible, but I'm trying to write a NodeJS application that needs to call some Python functions, the way I'm going to use Python functions is similar to How to call Python function from NodeJS by using child_process If the python script had a few imports that had a slight delay when running the script, if you were calling the python script often surely it would cause problems for the applications running time. Is there a way to get around to constantly keep a child process python call open and then call a function whenever it's needed? Thanks

http://stackoverflow.com/q/49290238
type: Question
has title: Count and sort pandas dataframe
accepted answer: http://stackoverflow.com/a/49290255
has answer: http://stackoverflow.com/a/49290255
has body: I have a dataframe with column 'code' which I have sorted based on frequency. In order to see what each code means, there is also a column 'note'. For each counting/grouping of the 'code' column, I display the first note that is attached to the first 'code' df.groupby('code')['note'].agg(['count', 'first']).sort_values('count', ascending=False) Now my question is, how do I display only those rows that have frequency of e.g. >= 30?
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49290277
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49290277
answer count: 2
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85590212
comment on: http://stackoverflow.com/a/49292601
score: 0
type: Comment
type: AnswerComment
has text: @nj2337 It worked for me now for all the cases. I have a query, what if I want to equate two letters as one of the case. Say k=q as in "cake" and "caqe" is 0. Is there a specific function for that?.

http://stackoverflow.com/comment/85812491
type: QuestionComment
comment on: http://stackoverflow.com/q/49403624
score: 0
has text: That link has instructions for connecting to SQL Server, not Access. The error message suggests that you working on a Windows machine. Is that correct?
type: Comment

http://stackoverflow.com/comment/85704432
has text: Hello, I'm sure it is because I am not getting this, but I replaced for tag in tags: print(tag.get('href')) with the above and received the error: AttributeError: 'NoneType' object has no attribute 'startswith'
comment on: http://stackoverflow.com/a/49344505
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49350370
has comment: http://stackoverflow.com/comment/85700503
tagged with: python
has body: How would you define the header in CSV in Panda. Then after analyzing the data push it into a new file. How would you include the header into the new CSV file Input: John Apple &lt;-- Header Start 9/21/2005 Duration: 00:00:06 &lt;-- Header End Time Body_Temp Thermistor &lt;-- Index 00:00:00 0.00 00:00:01 88.07 00:00:02 88.07 00:00:03 83.90 00:00:04 104.35 00:00:05 85.43 00:00:06 85.43 Output File: John Apple &lt;-- Header Start 9/21/2005 Duration: 00:00:06 &lt;-- Header End Time Body_Temp Thermistor &lt;-- Index 00:00:00 0.00 00:00:01 88.07 00:00:02 88.07 00:00:03 83.90 00:00:04 104.35 &lt;--Points this is above 100 00:00:05 85.43 00:00:06 85.43 My Code so far: from pandas import DataFrame, read_csv import csv import pandas as pd import numpy as np file = r'Alpha.csv' df = pd.read_csv(file) uncommon = df.loc[(df['Temp'] &gt;= 100)] #can only figure out to find any temp above 100 and print it into a new CSV uncommon.to_csv('Dummy.csv',sep='\t')
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49350469
upvote count: 3
accepted answer: http://stackoverflow.com/a/49350469
downvote count: 0
has comment: http://stackoverflow.com/comment/85700566
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/24168507
has title: Put Header and Dataframe into a new CSV

http://stackoverflow.com/comment/85873927
type: AnswerComment
has text: I tested the your autoencoder with small changes on your data. What I changed was the activation function from sigmoid to tanh and loss to mean squared error. To me it looked to perform fine.
type: Comment
comment on: http://stackoverflow.com/a/49373684
score: 0

http://stackoverflow.com/comment/85768211
has text: Also your question is rather unclear. What is 'accuracy' here, and what do you mean by "i want to execute only that model which as highest accuracy" ?
comment on: http://stackoverflow.com/q/49383494
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49437136
has title: Hyperparameters optimization using GridSearch
score: 0
has comment: http://stackoverflow.com/comment/85876234
has body: So I have been trying to optimize my keras model's parameters using Grid search and for most parts it works just fine but whenever I am trying to optimize each layer's parameters the model just hangs. I was wondering if someone could look into it and tell me what's happening or if there is something I am doing wrong. def create_model(dense_layers=2, dense_size_1=6, dense_size_2=7, init_mode_1='uniform', init_mode_2='uniform', gd='adam', transfer_1='relu', transfer_2='relu'): K.clear_session() model = Sequential() for i in range(0, dense_layers+1): if i == 1: model.add(Dense(dense_size_1,input_dim=8,activation=transfer_1, kernel_initializer=init_mode_1)) if i == 2: model.add(Dense(dense_size_2, activation=transfer_2, kernel_initializer=init_mode_2)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer=gd, metrics= ['accuracy']) return model model = KerasClassifier(build_fn=create_model, epochs=10, batch_size=10, verbose=1) dense_size_1 = [1, 5, 10, 15, 20, 25, 30] dense_size_2 = [1, 5, 10, 15, 20, 25, 30] init_mode_1 = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'] init_mode_2 = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'] gd = ['adam', 'sgd'] transfer_1 = ['relu', 'tanh'] transfer_2 = ['relu', 'tanh'] param_grid = dict(dense_size_1=dense_size_1, dense_size_2=dense_size_2, init_mode_1=init_mode_1, init_mode_2=init_mode_2, transfer_1=transfer_1, transfer_2=transfer_2) grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1 grid_result = grid.fit(X, y) It perfectly works good and fine if I just use parameters like hidden neurons for each layer, optimizer, epochs and batch size but it hangs if I make it more complex like separate activation function for neurons in each hidden layer or separate kernel initializer for neurons in each hidden layer. What could be possibly going wrong in this?
has comment: http://stackoverflow.com/comment/85886107
type: UnansweredQuestion
answer count: 1
tagged with: scikit-learn
tagged with: keras
type: Question
has answer: http://stackoverflow.com/a/67701071
tagged with: neural-network
tagged with: grid-search
tagged with: python
has comment: http://stackoverflow.com/comment/85877419

http://stackoverflow.com/q/49411263
has comment: http://stackoverflow.com/comment/85824209
upvote count: 1
has answer: http://stackoverflow.com/a/49411399
tagged with: string
accepted answer: http://stackoverflow.com/a/49411399
downvote count: 1
has title: How to change type of list to str?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49411412
possible better answer: http://stackoverflow.com/a/49411412
duplicate of: http://stackoverflow.com/q/36209980
tagged with: http://stackoverflow.com/tag/json
tagged with: python
linked to: http://stackoverflow.com/q/36209980
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/85824310
has body: I am extracting a list from html of a web page in the format lst = '["a","b","c"]' # (type &lt;str&gt;) The data type of the above is str and I want it to convert to a python list type , somthing like this lst = ["a","b","c"] #(type &lt;list&gt;) I can obtain the above by lst = lst[1:-1].replace('"','').split(',') But as the actual value of a,b &amp;c is quite long and complex(contains long html text), I can't be dependent on the above method. I also tried doing it with json module and using json.loads(lst) , that is giving the below exception Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/local/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python2.7/json/decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded Any way of converting to list in Python? Edit: The actual value of the list is: ['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable','reqlistitem.title','reqlistitem.contestnumber','reqlistitem.contestnumber','reqlistitem.description','reqlistitem.description','reqlistitem.primarylocation','reqlistitem.primarylocation','reqlistitem.otherlocations','reqlistitem.jobschedule','reqlistitem.jobschedule','reqlistitem.jobfield','reqlistitem.jobfield','reqlistitem.displayreferfriendaction','reqlistitem.no','reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.a…

http://stackoverflow.com/comment/85618728
type: Comment
type: QuestionComment
has text: Nope, that's not causing your bug—although it probably still is a bug, and I wouldn't be surprised if it bites you after fixing this one.
score: 0
comment on: http://stackoverflow.com/q/49308261

http://stackoverflow.com/q/49305124
duplicate of: http://stackoverflow.com/q/33837918
has comment: http://stackoverflow.com/comment/85612961
tagged with: type-hinting
tagged with: circular-reference
has body: I'm writing two classes, Parent and Child, so that the parent contains several children and each child contains a reference to the parent to eventually invoke its method(). Since I use type hinting (PIP 484, mainly for clarity and readability of the code), I come up with the error: ValueError: Circular reference detected due to the fact that example/child.py imports Parent already defined in example/parent.py. Does anyone know how to get rid of this error? My Parent (in example/parent.py) is as follows: from typing import List from example.child import Child class Parent(object): def __init__(self, children: List[Child] = None) -&gt; None: self._children = \ {child.name: child for child in children} if children else {} @property def children(self) -&gt; List[Child]: return list(self._children.values()) @children.setter def children(self, value: List[Child] = None) -&gt; None: self._children = {child.name: child for child in value} if value else {} def new_child(self, name: str) -&gt; Child: child = Child(self, name) self._children[name] = child return child def method(self) -&gt; bool: return len(self._children) % 2 == 0 My Child (in example/child.py), instead, is as follows: from typing import TYPE_CHECKING, List if TYPE_CHECKING: from example.parent import Parent class Child(object): def __init__(self, parent: 'Parent', name: str) -&gt; None: if parent is None: raise ValueError("'parent' is invalid: &lt;%s&gt;" % parent) if name is None or not str(name).strip(): raise ValueError("'name' is invalid: &lt;%s&gt;" % name) self._parent = parent self._name = str(name).strip() @property def parent(self) -&gt; 'Parent': return self._parent @property def name(self) -&gt; str: return self._name def method(self) -&gt; None: print('we are even' if self._parent.method() else 'we are odd') Notice that I already introduced the trick which consists in using the TYPE_CHECKING variable, but in this case it doesn't help. Thanks in advance!
type: Question
has comment: http://stackoverflow.com/comment/85612481
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85612690
has title: Avoiding circular reference in Python on type hinting for classes referencing each other
linked to: http://stackoverflow.com/q/33837918
tagged with: circular-dependency
has comment: http://stackoverflow.com/comment/85612644
has comment: http://stackoverflow.com/comment/85612740
score: 0
answer count: 0

decode
tag name: decode
tags question: http://stackoverflow.com/q/49379532
tags question: http://stackoverflow.com/q/49358708
tags question: http://stackoverflow.com/q/49381873
type: Tag
tags question: http://stackoverflow.com/q/49411664

http://stackoverflow.com/comment/85689603
has text: @rpg711 I am sure this is not a duplicate question. Please refer this link https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.random.choice.html
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49344715

build
tag name: build
tags question: http://stackoverflow.com/q/49327445
type: Tag
tags question: http://stackoverflow.com/q/49378486

http://stackoverflow.com/q/49286393
has body: I have the following code. It is a hash function that turns a word into a hashed number: def myHash (string): solution = 5 alphabet = 'abcdegjkmnoprstuvwyz' for carac in string: solution = solution * 21 + alphabet.find(carac) return solution test = 'mytest' print (myHash(test)) How would I do the opposite way? From a hashed number and I have to guess the string.
has comment: http://stackoverflow.com/comment/85575759
has comment: http://stackoverflow.com/comment/85576993
tagged with: hash
has comment: http://stackoverflow.com/comment/85576259
tagged with: function
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/85576211
has answer: http://stackoverflow.com/a/49287296
has answer: http://stackoverflow.com/a/49302607
answer count: 2
has comment: http://stackoverflow.com/comment/85575682
has comment: http://stackoverflow.com/comment/85576212
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/85577304
favorite count: 0
type: Question
has title: Hash/Unhash function

http://stackoverflow.com/comment/85797345
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49397720
type: QuestionComment
has text: I'm on Windows 10 x64, Python 3.6.4, and by console I indeed meant Terminal : ) . Thank your for your interest in my question.

http://stackoverflow.com/a/49409767
type: Answer
score: 0
has body: IIUC duplicated df.duplicated('flight_id',keep=False) Out[473]: 0 False 1 False 2 True 3 False 4 False 5 True dtype: bool Or using groupby df.groupby('flight_id').transform('nunique').gt(1).any(1) Out[482]: 0 False 1 False 2 True 3 False 4 False 5 True dtype: bool
answers question: http://stackoverflow.com/q/49409592

http://stackoverflow.com/q/49421040
has comment: http://stackoverflow.com/comment/85843196
has title: Python websocket library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85843415
tagged with: python
has body: I'm trying to make a webpage that uses websockets to connect to a Python script. I'm currently using the websocket_server library which works fine when viewing the page from my computer or phone browser but doesn't work when viewing on my TV. I've noticed the request sent from my TV is a bit different from other browsers. The request from my computer looks like: b'GET / HTTP/1.1\r\nHost: 192.168.0.153:5001\r\nConnection: Upgrade\r\nPragma: no-cache\r\nCache-Control: no-cache\r\nUpgrade: websocket\r\nOrigin: http://192.168.0.153:5555\r\nSec-WebSocket-Version: 13\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36\r\nAccept-Encoding: gzip, deflate\r\nAccept-Language: en-US,en;q=0.9\r\nSec-WebSocket-Key: /1Tw64u1Zd5SSvJd56hQeA==\r\nSec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n' and from the TV: b'GET / HTTP/1.1\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nHost: 192.168.0.153:5001\r\nOrigin: http://192.168.0.153:5555\r\nSec-WebSocket-Key1: 1_7236`8 \ 86d[1 w?0\r\nSec-WebSocket-Key2: W 38 0 5o P 4 7]0 7 50\r\n\r\n\xdb{x\x9f\xa3\x12\!' It has 2 Sec-WebSocket-Key sections and neither are base64 encoded. Is this an older version of the websocket protocol or is the implementation in the TV just borked? If it is an older version, are their any Python libraries that support it or perhaps some kind of work around? Thanks. edit: Python version 3.6 The TV is an LG 47lm6200-ue, I can't find any info about the OS it uses or anything about the browser it's using. It's from 2012 so I believe it's before LG switched to webOS. I'm creating the socket in JavaScript by doing: var ws = new WebSocket("ws://192.168.0.153:5001/");
score: 0
answer count: 0
tagged with: websocket
has comment: http://stackoverflow.com/comment/85843449
type: Question

http://stackoverflow.com/a/49394262
has body: By running that nested loop, you're going to do a lot of unnecessary processing, it'd make more sense to append all of the matches from the first file into a list, then check against that list with the matches from the second file. This is an approximation of the process here using two local lists: import re input1 = ['1.1.1.1', '233.123.4.125'] input2 = ['1.1.1.1/123', '123.55.2.235/236'] pattern = ('^(\d{1,3}\.?){4}') matchlist = [] for line in input1: p1 = re.match(pattern, line) matchlist.append(p1.group(0)) print(matchlist) for item in input2: p2 = re.match(pattern, item) t = p2.group(0) if t in matchlist: print t
score: 1
answers question: http://stackoverflow.com/q/49394017
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85767060
has text: Entry `self.delayent` is not returning the value, which I am storing in `self.delayentry` and at later point I would use this to appear on text field
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49382761

http://stackoverflow.com/comment/85740996
type: Comment
type: QuestionComment
score: 0
has text: One more thing: You should _look at_ the entire exception. After the part you cut off, it actually gives you a hint: `Use a.any() or a.all()`.
comment on: http://stackoverflow.com/q/49369836

http://stackoverflow.com/comment/85802164
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to run a script in PySpark](https://stackoverflow.com/questions/40028919/how-to-run-a-script-in-pyspark)
comment on: http://stackoverflow.com/q/49399648
score: 0

http://stackoverflow.com/comment/85602757
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49300023
has text: Ok found it, just had to add parenthesis around each test !
type: Comment

http://stackoverflow.com/q/49421088
score: 0
has comment: http://stackoverflow.com/comment/85843793
has comment: http://stackoverflow.com/comment/85845340
tagged with: loss-function
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
has title: ValueError: None values not supported. - Keras Custom Loss Function
tagged with: keras
has body: Im getting this error on my custom loss function : ValueError: None values not supported. The output is a 2d array of binary digits (2000,2). I need to calculate the accuracy on certain entries only (selected by the NN), not the entire set. Here's my loss function and how i did it: def getBalance(x_true, x_pred): ##Selected entries for calculation x_pred = K.tf.round(x_pred) trade_index = K.tf.not_equal(x_pred[:,1], 0 ) x_true_tradeable = K.tf.boolean_mask(x_true[:,0], trade_index) x_pred_tradeable = K.tf.boolean_mask(x_pred[:,0], trade_index) Accuracy = K.mean(K.equal(x_true_tradeable, x_pred_tradeable)) return Accuracy Here is my model for reference: model = Sequential() model.add(Dropout(0.4, input_shape=(train_input_data_NN.shape[1], train_input_data_NN.shape[2]))) model.add(LSTM(30, dropout=0.4, recurrent_dropout=0.4, return_sequences=False)) model.add(Dense(2, activation='sigmoid')) model.compile(loss='getBalance', optimizer='adam') history = model.fit(train_input_data_NN, outputs_NN, epochs=50, batch_size=64, verbose=1, validation_data=(test_input_data_NN, outputs_NN_test))
tagged with: tensorflow

http://stackoverflow.com/comment/85867532
has text: Not sure on what basis you are eliminating some rows?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49432582

http://stackoverflow.com/comment/85577325
type: QuestionComment
has text: @rayryeng Yes, however it is done using nested for loops, something I did make explicit that I don't want to do. My question is simply whether there is an elegant solution for this using numpy or scipy to get the nice speed benefits of those.
type: Comment
comment on: http://stackoverflow.com/q/49286903
score: 0

http://stackoverflow.com/q/49320170
has comment: http://stackoverflow.com/comment/85641364
has comment: http://stackoverflow.com/comment/85641465
tagged with: timezone
tagged with: utc
linked to: http://stackoverflow.com/q/12165691
has body: I have what seems like a simple question but for which I can find no straightforward answer. I would like to write a function that takes two strings as input and gives an integer as output. In R, the function would be as simple as: utc_seconds = function(date_string, tz) as.integer(as.POSIXct(date_string, tz = tz)) I am in control of date_string and know the format will always be proper, e.g. 2018-02-11 00:00:00, and I also know that tz will always be in Olson format. Example input/output: utc_seconds('2018-02-11 00:00:00', tz = 'Asia/Singapore') # 1518278400 I've looked at various combinations/permutations of datetime, pytz, time, etc, to no avail. This table looked promising, but ultimately I couldn't figure out how to use it. I've managed a "hack" as follows, but this feels inane (adding extraneous information to my input string): from dateutil.parser import parse from dateutil.tz import gettz parse("2018-02-01 00:00:00 X", tzinfos={'X': gettz('Asia/Singapore')}) # datetime.datetime(2018, 2, 11, 0, 0, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Singapore')) But I can't get that to UTC time either.
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85641286
possible better answer: http://stackoverflow.com/a/49320512
downvote count: 0
upvote count: 1
score: 1
tagged with: datetime
has answer: http://stackoverflow.com/a/49320512
has answer: http://stackoverflow.com/a/49320760
accepted answer: http://stackoverflow.com/a/49320760
favorite count: 0
type: Question
answer count: 2
has title: Convert datetime string, timezone to epoch seconds

http://stackoverflow.com/q/49333496
tagged with: cluster-analysis
accepted answer: http://stackoverflow.com/a/49334698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49334698
score: 0
has title: Within Cluster Similarity Kmeans
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85668716
has body: I am trying to cluster a 2 dimensional user data using kmeans in sklearn python. I used the elbow method (point where the increase in cluster no. does not bring significant dip in the sum of square errors) to identify the correct no. of clusters as 50. Post applying kmeans, i wish to understand the similarity of datapoints within each cluster. Since i have 50 clusters, is there a way to get a number (something like variance within each cluster) which could help me understand how close or datapoints within each of them. A number like 0.8 would mean that the records have high variance within each cluster while a 0.2 would mean they are closely "related". So to summarize, is there any way to get a single number to identify how "good" each cluster in kmeans is? We can argue that goodness is relative, but lets consider that i am more interested in the within cluster variance to identify how good a particular cluster is.
type: Question
has comment: http://stackoverflow.com/comment/85668958
has comment: http://stackoverflow.com/comment/85670872
has comment: http://stackoverflow.com/comment/85671825
tagged with: k-means

http://stackoverflow.com/a/49287849
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85578849
answers question: http://stackoverflow.com/q/49287830
type: Answer
has body: Pass positional indexers to iat: df.iat[0, 0] = 'j' Or, pass labels to at: df.at[0, 'A'] = 'j' df A B C 0 j d f 1 3 5 3 2 4 4 5 3 6 6 6
accepted answer of: http://stackoverflow.com/q/49287830
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49403700
tagged with: python
has comment: http://stackoverflow.com/comment/85811034
has comment: http://stackoverflow.com/comment/85808988
has comment: http://stackoverflow.com/comment/85810107
has comment: http://stackoverflow.com/comment/85809084
has answer: http://stackoverflow.com/a/49405668
score: 2
has title: How to find byte sequence in file?
answer count: 1
linked to: http://stackoverflow.com/q/13435922
has comment: http://stackoverflow.com/comment/85808566
has body: I have a binary file, in which I need to change certain bit. That bit's byte's address is relative to some byte sequence (some ASCII string): content = array('B') with open(filename, mode="r+b") as file: content.fromfile(file, os.fstat(file.fileno()).st_size) abc = [ord(letter) for letter in "ABC"] i = content.index(abc) // ValueError: array.index(x): x not in list content[i + 0x16] |= 1 content.tofile(file) However as I must confess to my shame, that after Googling far and wide, I couldn't find the method to get the index of that "ABC" string... Sure, I can write a function that does it with loops, but I can't believe there is no one-liner (OK, even two...) that accomplishes it. How can it be done?
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85810896
downvote count: 0

http://stackoverflow.com/q/49426485
downvote count: 1
has body: I tried to filter some signal with fft. The signal I am working on is quite complicated and im not really experienced in this topic. That's why I created a simple sin wave 3Hz and tried to cut off the 3 Hz. and so far, so good import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fftfreq, irfft, rfft t = np.linspace(0, 2*np.pi, 1000, endpoint=True) f = 3.0 # Frequency in Hz A = 100.0 # Amplitude in Unit s = A * np.sin(2*np.pi*f*t) # Signal dt = t[1] - t[0] # Sample Time W = fftfreq(s.size, d=dt) f_signal = rfft(s) cut_f_signal = f_signal.copy() cut_f_signal[(np.abs(W)&gt;3)] = 0 # cut signal above 3Hz cs = irfft(cut_f_signal) fig = plt.figure(figsize=(10,5)) plt.plot(s) plt.plot(cs) What i expected What i got I don't really know where the noise is coming from. I think it is some basic stuff, but i dont get it. Can someone explain to to me? Edit Just further information Frequency yf = fft(s) N = s.size xf = np.linspace(0, fa/2, N/2, endpoint=True) fig, ax = plt.subplots() ax.plot(xf,(2.0/N * np.abs(yf[:N//2]))) plt.xlabel('Frequency ($Hz$)') plt.ylabel('Amplitude ($Unit$)') plt.show()
favorite count: 0
tagged with: fft
type: Question
tagged with: filtering
upvote count: 9
has title: Filtering signal frequency in Python
has answer: http://stackoverflow.com/a/49428127
tagged with: python
tagged with: ifft
score: 8
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49428127
tagged with: signals
possible better answer: http://stackoverflow.com/a/49430690
has answer: http://stackoverflow.com/a/49430690

http://stackoverflow.com/comment/85689834
comment on: http://stackoverflow.com/a/49339722
type: Comment
score: 0
has text: thank you.. I think your opinion is right. but, The same problem still arises. Perhaps, there is another problem.
type: AnswerComment

http://stackoverflow.com/q/49324970
downvote count: 0
has answer: http://stackoverflow.com/a/49324995
score: 4
type: AnsweredQuestion
tagged with: pandas
has title: Pandas Merge returning NaN?
answer count: 1
tagged with: python
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/85651329
accepted answer: http://stackoverflow.com/a/49324995
has body: I have 2 dataframes: df1= State Code Alabama AL Alaska AK American Samoa AS Arizona AZ Arkansas AR df2= State PREVAILING_WAGE CALIFORNIA 102170.0 DELAWARE 97531.0 SOUTH CAROLINA 96824.0 WASHINGTON 89586.0 OREGON 88234.0 Now when I try to merge both if them using: df1.merge(df2,left_on='State',right_on='State',how='left') I get NaN values in the merged table like this: State PREVAILING_WAGE Code CALIFORNIA 102170.0 NaN DELAWARE 97531.0 NaN SOUTH CAROLINA 96824.0 NaN WASHINGTON 89586.0 NaN OREGON 88234.0 NaN I checked the dtypes too, and both of them are objects or str. How do I solve this? Thanks EDIT: The dataframes contain all states names, so they have common stuff to match.

type-conversion
tags question: http://stackoverflow.com/q/49395851
tags question: http://stackoverflow.com/q/49318427
tags question: http://stackoverflow.com/q/49349824
tags question: http://stackoverflow.com/q/49400780
tags question: http://stackoverflow.com/q/49292456
tags question: http://stackoverflow.com/q/49309679
tag name: type-conversion
type: Tag
tags question: http://stackoverflow.com/q/49415432

http://stackoverflow.com/a/49419735
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49413295
has body: This needs more coding. However I will explain the logic approach. You may want to vary the coding approach a little. Load the string into a dictionary. Fixed string json_out = '{"count":16,"name":"Report Name","columnNames":["Connection","Complete Name","Login ID","Login Time","Logout Time","IP Direction"],"rows":[["PGALICHI","Robert The IT Guy","3205","2018-01-25 08:52:23","2018-01-25 15:00:50","201.255.56.151"],["PGALICHI","Lucas The other IT Guy","3204","2018-01-25 08:52:21","2018-01-25 15:00:51","201.255.56.151"]],"links":[{"rel":"self","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"canonical","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/analyticsReportResults"},{"rel":"describedby","href":"https://web--tst1.custhelp.com/services/rest/connect/v1.4/metadata-catalog/analyticsReportResults","mediaType":"application/schema+json"}]}' dic_json = json.loads(json_out) Convert the rows into a dictionary Login Time is used as value as we will need it for sorting later. Use datetime for converting string to date from datetime import datetime rows_list = dic_json['rows'] d = dict() for x in rows_list: datetime_object = datetime.strptime(x[4], '%Y-%m-%d %H:%M:%S') d[x.__str__()] = datetime_object Note : Since login time may or not be unique I chose whole list to be key Even not sure login id is unique here. Use collections.OrderedDict for sorting on time.; i.e import collections # sort by time i.e dictionary values od2 =collections.OrderedDict(sorted(d.items(), key=lambda t: t[1])) Filter values based on date-time condition. Input_time date_time_req = datetime.strptime('2018-01-25 08:52:23', '%Y-%m-%d %H:%M:%S') for y in od2.keys(): if od2[y] &lt;= date_time_req: print(y) This output is string , you can trim and convert it back to a list.

http://stackoverflow.com/comment/85753026
type: QuestionComment
score: 0
has text: @juanpa.arrivillaga If we make it a class with normal methods, I feel that it is strange to have to instantiate the class first before accessing the method
comment on: http://stackoverflow.com/q/49375744
type: Comment

http://stackoverflow.com/a/49413762
answers question: http://stackoverflow.com/q/49413650
has body: Rather than using product from the itertools module, use combinations_with_replacement. That does what you want in one line without any massaging afterward: list1 = [list(i) for i in combinations_with_replacement(range(4),3)] The result of print(list1) after that is [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 2], [0, 2, 3], [0, 3, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]] Note that your conversion of the range object to a tuple is not necessary.
accepted answer of: http://stackoverflow.com/q/49413650
score: 5
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85616325
comment on: http://stackoverflow.com/q/49306996
score: 0
type: Comment
type: QuestionComment
has text: The error is telling you you don't have a module named "mysite.wsgi". Do you have a module named that? Where is your wsgi.py file in fact?

http://stackoverflow.com/q/49284154
has comment: http://stackoverflow.com/comment/85571226
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
answer count: 1
has body: Write a python program to calculate sum of all elements in a list excluding the numbers between 5 and 8. Take the list as l1=[1,5,3,6,8,9,19,17,14]
has comment: http://stackoverflow.com/comment/85571464
favorite count: 0
has answer: http://stackoverflow.com/a/49284221
has title: How to calculate sum of all elements of a list excluding few numbers?
tagged with: python
has comment: http://stackoverflow.com/comment/85571121
has comment: http://stackoverflow.com/comment/85571095
type: Question

http://stackoverflow.com/comment/85619704
has text: Are you using a IDE like _Pycharm_? Because if you are, the default settings are to create a virtual environment for your project. Using pip will install the module globally but that won't affect your virtual environment. If that's the case, you might want to check this page: https://docs.python.org/3/tutorial/venv.html
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49308693
score: 1

http://stackoverflow.com/a/49426861
downvote count: 1
has body: result = [my_list.index(l) for l in my_list] print(result) [0, 1, 2, 0, 0, 2] list.index() returns the index of first occurrence as required for your task. For more details check list.index()
type: Answer
has comment: http://stackoverflow.com/comment/85855592
score: 0
answers question: http://stackoverflow.com/q/49426546
upvote count: 1

http://stackoverflow.com/a/49354689
score: 0
has body: I am trying to determine if all letters in myString are found in myList. You can use a combination of the built-in functions any and all to accomplish this: &gt;&gt;&gt; def findLetters(myList,myString): return all(any(c in word for word in myList) for c in myString) &gt;&gt;&gt; findLetters(["hello","world"],"old") True &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/49354618
type: Answer

powerpoint
tags question: http://stackoverflow.com/q/49384134
type: Tag
tags question: http://stackoverflow.com/q/49279998
tags question: http://stackoverflow.com/q/49321115
tag name: powerpoint

http://stackoverflow.com/q/49381189
score: 2
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/48830795
has body: Is there an equivalent to itertools.chain(*iterables) that works with async iterators? One key requirement would be to get available data from an async iterator as soon as it's available (i.e. no naive chaining). Update: Note that one key difference to the duplicate question, is that the answer below lets you identify the triggering async generator.
favorite count: 0
has title: How do I chain multiple async generators / iterators in parallel?
type: Question
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: async-await
tagged with: python
has answer: http://stackoverflow.com/a/49381190
upvote count: 2
duplicate of: http://stackoverflow.com/q/48830795

http://stackoverflow.com/a/70763308
answers question: http://stackoverflow.com/q/49284015
score: 1
type: Answer
upvote count: 1
downvote count: 0
has body: You can use the following to validate that no files exist inside the input folder: import glob if len(glob.glob("input\*")) == 0: print("No files found to Process...") exit()

http://stackoverflow.com/q/49290124
type: UnansweredQuestion
has title: Django- How to test image returned in httpresponse
tagged with: django
tagged with: python
has body: I have a django test method that checks to see if an image returned as an httpresponse equals the image as it was opened before the http request was sent to the view: def test_uploaded_file(self): c = Client() originalFilePath = '../static_cdn/test_img.jpg' image_data = open(originalFilePath, "rb") with open(originalFilePath, "rb") as fp: response = c.post('/', {'image': fp}) self.assertEqual(image_data,response) For some reason, the test is returning this error: AssertionError: &lt;open file u'../static_cdn/test_img.jpg', mode 'rb' at 0x7fed326b6a50&gt; != &lt;HttpResponse status_code=200, "image/jpg"&gt; I think the issue has to do with the fact that the image returned from the view is an httpresponse and while the other image being opened in the test method is not. Why could this test be failing? Can the image be extracted from the response?
score: 0
has answer: http://stackoverflow.com/a/49290386
tagged with: django-views
answer count: 1
tagged with: http
tagged with: unit-testing
type: Question

http://stackoverflow.com/q/49424089
type: Question
tagged with: numpy
has body: #code source import numpy as np import pandas as pd from sklearn.datasets import make_classification X, y = make_classification(n_samples=50, n_features=6, n_informative=3, n_classes=2, random_state=10, shuffle=True) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) values = [i for i,x in enumerate(df['Class']) if x == 0] print(values) The output is [5, 6, 9, 11, 13, 14, 17, 18, 20, 21, 23, 24, 25, 26, 27, 31, 32, 34, 41, 42, 44, 45, 46, 47, 49] I am trying to group the above output based on the condition that numbers come in concurrent value . Such as the output should be: Group 1: 5,6 Group 2: 9 Group 3: 11 Group 4: 13,14 .. .. Group n: 23,24,25,26,27 I am grouping them to have an understanding of the gaps in the column, instead of having a slab of values following each other in a list.
tagged with: python
type: AnsweredQuestion
has title: Python: Group output of Column based on a condition
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/49424142
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49424142
favorite count: 0

http://stackoverflow.com/comment/85869151
score: 1
has text: @ealeon: a client certificate is used by the client to authenticate itself against the server if the server requires so. You need to have certificate and private key to do this. A CA certificate or a trust store like cacert.pem is used by the client to verify the servers certificate. It should only contain CA certificates and no private keys. To use `curl` with trust store use the `--cacert` option not `-E`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49433496
type: Comment

http://stackoverflow.com/q/49285804
answer count: 1
has title: Obtain saved_model.pb location for specific GCMLE model from within jupyter notebook
type: Question
tagged with: google-cloud-ml
tagged with: python
has body: I have a GCMLE model deployed as a model for GCMLE prediction service. In the GCP console UI I can navigate to the model name -> version and then I can view the Model location (ie gs://..../) which specifies the location of my saved_model.pb file. Is there any way to dynamically obtain this "model location" within a jupyter notebook/python script? I would like to be able to then use this model location to download the saved_model.pb locally so that I can load the model into a local session for debugging purposes on specific inference tasks. Currently, I can do all of this manually, but I'd like to be able to quickly flip between model versions without needing to manually track/download the saved_model.pb files.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49286118
score: 0
has answer: http://stackoverflow.com/a/49286118

http://stackoverflow.com/q/49338004
has comment: http://stackoverflow.com/comment/93730632
type: Question
has comment: http://stackoverflow.com/comment/85681714
tagged with: opencv
type: UnansweredQuestion
tagged with: python
has title: Straightening a tilted object in an image
has comment: http://stackoverflow.com/comment/85678444
answer count: 0
score: 0
tagged with: image-processing
has body: In the following image of a solar panel the panel appears to be tilted how can i straighten it ? Can this be done using hough transform ? Edit: cv2.Houghlines gives an array of (rho,theta) values how do I find out the number of votes got by each (rho,theta) value in the accumilator?

http://stackoverflow.com/comment/85862597
has text: Just press `Ctrl+Enter` instead of `Enter` to create a new line instead of executing. That way you can add more code to customize your plot.
comment on: http://stackoverflow.com/q/49425805
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85647623
has text: only $, @ and _ should be allowed in this case.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49322727

http://stackoverflow.com/q/49342077
answer count: 2
downvote count: 0
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/49343588
accepted answer: http://stackoverflow.com/a/49342953
possible better answer: http://stackoverflow.com/a/49343588
tagged with: python-3.x
tagged with: tree
type: AnsweredQuestion
tagged with: recursion
upvote count: 3
score: 3
has body: I'm trying to recurse over a dataset to find the highest level item, i.e. one that does not have a parent. The structure looks like this: ╔════════════╦════════════╗ ║ Item ║ Material ║ ╠════════════╬════════════╣ ║ 2094-00003 ║ MHY00007 ║ ║ 2105-0001 ║ 2105-0002 ║ ║ 2105-0002 ║ 2105-1000 ║ ║ 2105-1000 ║ 2105-1003 ║ ║ 2105-1003 ║ 7547-122 ║ ║ 7932-00001 ║ 7932-00015 ║ ║ 7932-00002 ║ 7932-00015 ║ ║ 7932-00010 ║ MHY00007 ║ ║ 7932-00015 ║ 7932-05000 ║ ║ 7932-05000 ║ MHY00007 ║ ╚════════════╩════════════╝ So, for example, if I select 7547-122, the function will return 2105-0001. So the function has recursively followed the tree upwards, 7547-122 -> 2105-1003 -> 2105-1000 -> … -> 2105-0001. When I run my code, I can only get it to return one top level, as you can see from the MHY00007 case, some times there are multiple top levels. How can I return a list of all the top levels any given material has? My code: import pandas as pd class BillOfMaterials: def __init__(self, bom_excel_path): self.df = pd.read_excel(bom_excel_path) self.df = self.df'Item', 'Material' def find_parents(self, part_number): material_parent_search = self.df[self.df.Material == part_number] parents = list(set(material_parent_search['Item'])) return parents def find_top_levels(self, parents): top_levels = self.__ancestor_finder_([parents]) print(f'{parents} top level is {top_levels}') return {parents: top_levels} def __ancestor_finder_(self, list_of_items): for ancestor in list_of_items: print(f'Searching for ancestors of {ancestor}') ancestors = self.find_parents(ancestor) print(f'{ancestor} has ancestor(s) {ancestors}') if not ancestors: return ancestor else: highest_level = self.__ancestor_finder_(ancestors) return highest_level BOM = BillOfMaterials(bom_excel_path="Path/To/Excel/File/BOM.xlsx") ItemsToSearch = ['7547-122', 'MHY00007'] top_levels = [] for item in ItemsToSearch: top_levels.append(BOM.find_top_levels(item))
tagged with: python
has title: Recurse Over Excel File To Find Top Level Item From Tree Structure
type: Question
has answer: http://stackoverflow.com/a/49342953

http://stackoverflow.com/q/49302814
type: Question
has answer: http://stackoverflow.com/a/49645154
has title: How to fail a ShellCommandActivity on AWS Data pipeline
has comment: http://stackoverflow.com/comment/86272686
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86265680
has comment: http://stackoverflow.com/comment/86272584
tagged with: amazon-data-pipeline
type: UnansweredQuestion
has body: I am using AWS Data Pipeline and specifically the ShellCommandActivity object. This object calls a python script which extracts data via ftp, etc. There exists a chance that the file may not exist or the file may be of the wrong type and the pipeline can no longer run. If the python script errors out, or fails, the ShellCommandActivity object still gets marked as Finished, when I"m trying to get it to Failure. I have tried, in python, doing sys.exit(500) on failure, but the object still gets marked as Finished. How can I fail a ShellCommandActivity from a python script?
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85666084
comment on: http://stackoverflow.com/a/49331896
type: Comment
has text: Oh, I understand that now. Essentially though, the __init__ of bookcase does not get called via the class method but the cls's init gets called. But is'int the cls's init and the bookcase init the same. Also, I think subclasses are classes which inherit from parent classes
score: 0
type: AnswerComment

http://stackoverflow.com/q/49415175
has comment: http://stackoverflow.com/comment/88611525
type: Question
has body: I want to check if a user entered a number as percent format (18.06) instead of decimal format (0.1806), and always convert to decimal format. Currently, I check to see if the value > 1, and if so, divide by 100. This works in my use case, but I can imagine some edge cases where it doesn't work. Is there a better solution? UPDATE: let's assume it's a float, and therefore all strange characters, i.e. %s, have been removed.
has comment: http://stackoverflow.com/comment/85832102
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85904070
tagged with: python
has comment: http://stackoverflow.com/comment/85832320
has comment: http://stackoverflow.com/comment/85832065
tagged with: decimal
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49415302
has title: Python convert number expressed as percentage to decimal

http://stackoverflow.com/comment/86699978
comment on: http://stackoverflow.com/q/49418358
has text: Brett (Norwegian language) is the same as Board. The answer I got was correct. :)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/75804508
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49407659
upvote count: 3
downvote count: 0
has body: In fact, it is possible... but with huge restrictions. You can only delete the end/tail of the archive, not files at the beginning or in the middle of it. I just had a similar need for extracting files from a huge tar (450G) without enough space for both the tar and the extracted files. I had to extract files one at a time and remove them from the .tar as soon as they were extracted. The command tar -vf x.tar --delete a.txt does not solve that because it does not delete the a.txt from the x.tar (the x.tar remains the same size), it just removes it from the list of contained files (a.txt will not be extracted when untaring x.tar later). The only thing you can do with .tar files, because they are sequential, is to truncate them. So the only solution is to extract files from the end. First you get the list of all the members of the tar file: with tarfile.open(name=tar_file_path, mode="r") as tar_file: tar_members = tar_file.getmembers() Then you can extract the files you want from the end: with tarfile.open(name=tar_file_path, mode="r") as tar_file: tar_file.extractall(path = extracting_dir, members = tar_members[first_of_files_to_extract:]) You compute where to truncate the file (in bytes): truncate_size = tar_members[first_of_files_to_extract].offset Then you add "end of file" marker, i.e. two consecutive blocks of Nulls. Each block is 512 bytes long in .tar, so you need to have 1024 Null bytes at the end. Here, just for the record, you can add 512 bytes (one block) because the previous tar_member already finish by a 512 bytes Null block (marker of end of tar_member). new_file_size = truncate_size + 1024 # 2 blocs of 512 Null bytes And you finally do the truncations, first for removing last members, second for adding null bytes (here we do not open the .tar with tarfile.open() anymore, truncation is just regular file operation): with open(tar_file_path) as tar_file: tar_file.truncate(truncate_size) tar_file.truncate(new_file_size) Here you have extracted files from t…

http://stackoverflow.com/a/49393468
answers question: http://stackoverflow.com/q/49393300
score: 0
has body: I once had the same issue and fixed it by deleting the system pip cache. Check https://github.com/pypa/pip/issues/5079 for more info.
type: Answer

http://stackoverflow.com/q/49297194
type: Question
tagged with: tkinter
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85600168
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 2
has body: I'm trying to make a basic GUI in tkinter but I want it to be dynamic. The end goal is to have a nested dictionary populated by this GUI and that the user can add as many items as he/she want. I managed to enter a full single dictionary with some simple (and pretty repetetive) code: for example: Edit from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop() Now im looking for a way for the GUI to have a button (like a + sign) that will allow the user to open another single or a set of entries each time he/she presses the button and populate the dictionary accordingly. Any Ideas?
has answer: http://stackoverflow.com/a/49299801
accepted answer: http://stackoverflow.com/a/49299801
upvote count: 1
answer count: 1
has title: Dynamic dictionary entry tkinter
has comment: http://stackoverflow.com/comment/85597863
favorite count: 0

http://stackoverflow.com/q/49287398
score: 4
type: Question
tagged with: numpy
tagged with: binary
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85579039
has answer: http://stackoverflow.com/a/65403541
tagged with: matrix
has body: In factoring methods based on the quadratic sieve, finding the left null space of a binary matrix (values computed mod 2) is a crucial step. (This is also the null space of the transpose.) Does numpy or scipy have tools to do this quickly? For reference, here is my current code: # Row-reduce binary matrix def binary_rr(m): rows, cols = m.shape l = 0 for k in range(min(rows, cols)): print(k) if l &gt;= cols: break # Swap with pivot if m[k,l] is 0 if m[k,l] == 0: found_pivot = False while not found_pivot: if l &gt;= cols: break for i in range(k+1, rows): if m[i,l]: mi,k = mk,i # Swap rows found_pivot = True break if not found_pivot: l += 1 if l &gt;= cols: break # No more rows # For rows below pivot, subtract row for i in range(k+1, rows): if m[i,l]: m[i] ^= m[k] l += 1 return m It is pretty much a straightforward implementation of Gaussian elimination, but since it's written in python it is very slow.
has title: Finding null space of binary matrix in python
tagged with: python
upvote count: 4

http://stackoverflow.com/q/49290704
tagged with: http://stackoverflow.com/tag/html
tagged with: python-requests
downvote count: 1
has body: I have my own local HTML file open in my browser. When I click a certain button, the class to the button changes to "selected." What I want to do is have Python take the current updated HTML of the file in the browser and overwrite it as the original HTML file. The goal here is to save the changes that were updated from the browser as the new HTML file, so the next time I open this file, the changes don't need to be made again. Typically I would: send an HTTP request to a url turn the response into a BeautifulSoup object then save it as a string as myfile.html url = 'http://google.com' r = requests.get(url) soup = str(BeautifulSoup(r.content,'lxml')) file.write(soup) But I cannot send an HTTP request because it's a file currently open in my browser, not a web page on a server to be requested. So I'm not sure how to receive the structured HTML into Python for further processing.
favorite count: 0
has comment: http://stackoverflow.com/comment/85584524
tagged with: beautifulsoup
type: Question
upvote count: 0
has title: python - Save HTML from browser
has answer: http://stackoverflow.com/a/49290792
accepted answer: http://stackoverflow.com/a/49291356
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49291356
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49290792
tagged with: file-io

http://stackoverflow.com/comment/85852987
type: QuestionComment
comment on: http://stackoverflow.com/q/49425805
type: Comment
score: 1
has text: So you're using the internal ipython console? Does it show the figures in the actual console? If so, try typing `%matplotlib` or `%matplotlib qt` before doing `plt.hist(df.amount, bins=30)`.

http://stackoverflow.com/comment/85795359
type: QuestionComment
has text: Not sure your question, but you typically pass the primary key of a model instance you want celery to use and reload it from the DB in the celery task. Please update your question with your `tasks.py`
comment on: http://stackoverflow.com/q/49396292
type: Comment
score: 2

http://stackoverflow.com/comment/85577708
comment on: http://stackoverflow.com/q/49287331
score: 5
type: Comment
type: QuestionComment
has text: Does your (unknown) OS preserve that information for each file?

http://stackoverflow.com/q/49351165
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pytest
has answer: http://stackoverflow.com/a/49357637
accepted answer: http://stackoverflow.com/a/49357637
answer count: 1
has comment: http://stackoverflow.com/comment/85713024
type: Question
tagged with: python-3.x
has body: We are using python 2.7.4 in our project application code and planning to use pytest 3.4.2 version for unit testing. In future we might upgrade our application code to latest python 3.6.X. Given that pytest 3.4.X supports both python 2.7 and > 3.3 versions, the test code files ( Example: test_mymodule.py) has to be written in any python version or it has to be written on the python version used for the application code. To exactly pin point the question, Application code with python 2.7.x version --> the corresponding test code with pytest has to be written in 2.7.x compatible code or it can even be written with python 3.4 version compatible code?. Will pytest understand the test code accordingly and run the test files?.
has title: pytest 3.4.2 test py code has to be written in the respective application code python version only?
tagged with: python
has comment: http://stackoverflow.com/comment/85702126

http://stackoverflow.com/q/49355891
has body: How to calculate quarterly wise churn and retention rate with date column using python. with date column i want to group that quarterly using python. This is used to calculate the churn count groupby quarterly quarterly_churn_yes = out.loc[out['Churn'] == 'Yes'].groupby(out["Date"].dt.quarter).count() print(quarterly_churn_yes["Churn"]) Date 1 1154 2 114 3 68 4 69 Name: Churn, dtype: int64 This is used to calculate the churn rate groupby quarterly total_churn = out['Churn'].count() print(total_churn) quarterly_churn_rate = out.groupby(out["Date"].dt.quarter).apply(lambda x: quarterly_churn_yes["Churn"] / total_churn).sum() print(quarterly_churn_rate) Date 1 0.862159 2 0.085170 3 0.050803 4 0.051550 dtype: float64 The above code i have tried to the find churn rate grouped on date column querterly wise. I am getting 1,2,3,4 but i want year wise quarterly churn rate. For example , if i have four years in the dataframe like 2018,2014,2017 in that 2008 1 1154 2 114 3 68 4 69 2014 1 1154 2 114 3 68 4 69
downvote count: 3
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49359884
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85711926
score: -2
linked to: http://stackoverflow.com/q/49376781
tagged with: python
accepted answer: http://stackoverflow.com/a/49359884
has title: How to calculate quarterly wise churn and retention rate using python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49383494

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/49397437

http://stackoverflow.com/comment/85691973
has text: What specifically in the code? The model creation and compilation? And those graphs are of 50 epochs, the x-axis is the epochs. The problem is of image classification so I don't think there are all-zeros or zero divisions in the input.
score: 0
comment on: http://stackoverflow.com/q/49345671
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49385690
tagged with: python
answer count: 4
has body: I have a problem with creating a dataframe which holds a time interval where a measurement of temperature is in. As for now the dataframe has its index as time and another column as the measurements and i would like to have the time converted to an interval of 12 hours and the measurement to be the mean of the values in that timelapse. measurement time 2016-11-04 08:49:25 17.730000 2016-11-04 10:23:52 18.059999 2016-11-04 11:02:09 18.370001 2016-11-04 12:04:20 18.090000 2016-11-04 14:26:43 18.320000 so instead of having each time related to the measurement i want the mean of the value of let's say 12 hours like this: measurement time 2016-11-04 00:00:00 - 2016-11-04 12:00:00 17.730000 2016-11-04 12:00:00 - 2016-11-05 00:00:00 18.059999 2016-11-05 00:00:00 - 2016-11-05 12:00:00 18.370001 2016-11-05 12:00:00 - 2016-11-06 00:00:00 18.090000 2016-11-06 00:00:00 - 2016-11-06 12:00:00 18.320000 is there an easy way to do this with pandas? Later i would like to convert the measurements into intervals as well so that the data becomes boolean like this: 17.0-18.0 18.0-19.0 19.0-20 time 2016-11-04 00:00:00 - 2016-11-04 12:00:00 1 0 0 2016-11-04 12:00:00 - 2016-11-05 00:00:00 0 1 0 2016-11-05 00:00:00 - 2016-11-05 12:00:00 0 1 0 2016-11-05 12:00:00 - 2016-11-06 00:00:00 0 1 0 2016-11-06 00:00:00 - 2016-11-06 12:00:00 0 1 0 EDIT: I used a solution first posted by Coldspeed df = pd.DataFrame({'timestamp':time.values, 'readings':readings.values}) df = df.groupby(pd.Grouper(key='timestamp', freq='12H'))['readings'].mean() v = pd.cut(df, bins=[17,18,19,20,21,22,23,24,25,26,27,28], labels=['17-18','18-19','19-20','20-21','21-22','22-23','23-24','24-25','25-26','26-27','27-28']) I know that the bins and labels could have been done but a for loop but this is just a quick fix. the groupby function which groups the value of 'timestamp' in the frequency of 12 hours and gets the readings mean value in the timelapse. Then the cut function is used to categorize the means into their categori…
favorite count: 0
has comment: http://stackoverflow.com/comment/85772508
tagged with: boolean
downvote count: 0
linked to: http://stackoverflow.com/q/46803556
upvote count: 1
has answer: http://stackoverflow.com/a/49385969
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85772776
has answer: http://stackoverflow.com/a/49385755
has answer: http://stackoverflow.com/a/49385793
type: Question
has answer: http://stackoverflow.com/a/49386258
tagged with: pandas
has title: creating categorical data from 2 columns - Python Pandas
score: 1
tagged with: intervals

http://stackoverflow.com/comment/85785013
score: 0
type: Comment
type: QuestionComment
has text: I cannot reproduce this. The animation shows as expected.
comment on: http://stackoverflow.com/q/49391563

http://stackoverflow.com/comment/88175449
has text: Could you please paste full stack trace? It's hard to say without the error. In your comment, only object is printed...
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49826345

http://stackoverflow.com/comment/85648315
has text: @MuhammadHassan l=[df1 for _, df1 in s.groupby('New')] you can try
score: 0
comment on: http://stackoverflow.com/a/49322644
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85800198
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49349318
type: Comment
has text: yes in the templates folder with the other HTML pages

http://stackoverflow.com/comment/85783860
type: Comment
score: 0
type: AnswerComment
has text: Test the code before you state anything. I have been running that code on 100's of machines with variations and as long as you state `ECHO` first, it will display on screen.
comment on: http://stackoverflow.com/a/49390967

http://stackoverflow.com/comment/85870907
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49434077
has text: You can replace `count` with `size` and the `groupby` reference to `['z']` becomes unnecessary.

http://stackoverflow.com/a/49414628
has body: You could always check the OS default language, using getdefaultlocale(), and you could use that to guide how you parse dates: &gt;&gt;&gt;import locale &gt;&gt;&gt;locale.getdefaultlocale() ('en_US', 'cp1252') This wouldn't be exact, as I would enter dates the same way no matter what locale my computer is using, but it could give you a starting point.
has comment: http://stackoverflow.com/comment/85833720
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49414508

http://stackoverflow.com/q/49307346
type: Question
score: 0
has body: Can someone please help me to understand the structure of the data frame I am receiving from a function call and also share how can I access a particular cell value in that data frame? Following is the output when I print resultData.shape (0, 14) (22, 14) Following is the output when I print resultData (0, 14) Empty DataFrame Columns: [Symbol, Series, Prev Close, Open, High, Low, Last, Close, VWAP, Volume, Turnover, Trades, Deliverable Volume, %Deliverble] Index: [] (22, 14) Symbol Series Prev Close Open High Low Last \ Date 2018-01-01 ACC EQ 1758.40 1763.95 1763.95 1725.00 1731.40 2018-01-02 ACC EQ 1731.35 1736.20 1745.80 1725.00 1739.00 2018-01-03 ACC EQ 1743.20 1741.10 1780.00 1740.10 1780.00 2018-01-04 ACC EQ 1774.60 1779.95 1808.00 1770.00 1794.50 I need to access 'Open' price on 2018-01-01. Thanks in advance!
tagged with: pandas
has comment: http://stackoverflow.com/comment/85617940
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49883309
tagged with: quandl
has title: Accessing a cell value in Pandas DataFrame - nsepy
type: UnansweredQuestion
answer count: 1
tagged with: nsepy

http://stackoverflow.com/q/49384188
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85769990
tagged with: python
has comment: http://stackoverflow.com/comment/85769193
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85769458
tagged with: netsh
has title: How to execute 'netsh' command through subprocess.check_output()
has body: I am running a batch file which in turn runs a python file. I want to execute netsh command to change the IPv4 settings from static to dhcp and vice versa. When I run the below code it executes and returns without any error import subprocess cmd = "netsh interface ip show config" output = subprocess.check_output(cmd) print output But when I execute the this piece of code through a batch file the python file exits with exit status 1. import subprocess cmd = '''netsh interface ip set address "Local Area Connection 9" dhcp''' output = subprocess.check_output(cmd) print output And It throws an error Python: can't open file 'Update_DHCP.py': [Errno 2] No such file or directory The python file and the batch file are in same folder and as per my understanding of updating the dhcp Ip, requires admin rights. I am even running the .bat file as 'Run as Administrator' but got the error [Errno 2] I have also tried to create a task using task scheduler to grant admin rights to the .bat file and run it. But still, it din't work for me. Can any one help me execute the command using subprocess.check_output() as I want to use the output returned by the check_output() call. Any help would be appreciated. I am working on Windows and my python version is 2.7
type: Question
has comment: http://stackoverflow.com/comment/85769634

http://stackoverflow.com/comment/85665225
type: Comment
has text: @SirJohnson Because python dictionaries are hashed and by design are unordered, see here [Why is the order in dictionaries and sets arbitrary?](https://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49331535

http://stackoverflow.com/a/49312327
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49312298
answers question: http://stackoverflow.com/q/49312298
type: Answer
has comment: http://stackoverflow.com/comment/85626514
has body: Just split the second part of the array by ",". letters = open("letters.txt") alist = [] for line in favmovies: line = line.strip().split(":") line[0] = int(line[0]) line[1] = line[1].split(',') list.append(line) This gives me, with your example: [1, ['a', 'b', 'c']] [2, ['d', 'e', 'f']] And it preserves the overarching format of your original code.

http://stackoverflow.com/comment/85783500
type: Comment
type: QuestionComment
has text: `l2_minus_l1 = [x for x in list2 if x not in list1]`
comment on: http://stackoverflow.com/q/49390972
score: 1

http://stackoverflow.com/q/49315620
has answer: http://stackoverflow.com/a/49315661
possible better answer: http://stackoverflow.com/a/49315661
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: How to store default value when nothing is found or whois fails to get results in python
has answer: http://stackoverflow.com/a/49338782
accepted answer: http://stackoverflow.com/a/49338782
tagged with: python
tagged with: whois
has body: The code import whois domains = ['google.com', 'stackoverflow.com', 'hdtrcs.com' , 'facebook.com' ] w = [] i = 0 for data in domains: n = domains[i] print(n) i = i+1 data = whois.whois(n) if data != None: w.append(data['domain_name']) else: w.append('none') print (w) Expected to store w = ['GOOGLE.COM', 'STACKOVERFLOW.COM', 'none', 'facebook.com' ] The error is it cant find the domain and it stops checking next domains The output this code gives google.com stackoverflow.com hdtrcs.com Traceback (most recent call last): File "who.py", line 9, in &lt;module&gt; data = whois.whois(n) File "/usr/local/lib/python3.5/dist-packages/whois/__init__.py", line 41, in whois return WhoisEntry.load(domain, text) File "/usr/local/lib/python3.5/dist-packages/whois/parser.py", line 185, in load return WhoisCom(domain, text) File "/usr/local/lib/python3.5/dist-packages/whois/parser.py", line 283, in __init__ raise PywhoisError(text) whois.parser.PywhoisError: No match for "HDTRCS.COM". &gt;&gt;&gt; Last update of whois database: 2018-03-16T09:41:06Z &lt;&lt;&lt; NOTICE: The expiration date displayed in this record is the date the registrar's sponsorship of the domain name registration in the registry is currently set to expire. This date does not necessarily reflect the expiration date of the domain name registrant's agreement with the sponsoring registrar. Users may consult the sponsoring registrar's Whois database to view the registrar's reported date of expiration for this registration. TERMS OF USE: You are not authorized to access or query our Whois database through the use of electronic processes that are high-volume and automated except as reasonably necessary to register domain names or modify existing registrations; the Data in VeriSign Global Registry Services' ("VeriSign") Whois database is provided by VeriSign for information purposes only, and to assist persons in obtaining information about or related to a domain name registration record. VeriSign does not guarantee its…

http://stackoverflow.com/a/49424905
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49424733
downvote count: 0
has body: I think need filter column in both sides with replace only for filtered rows: mask = (df['key']=="A") &amp; (df['data1'] &gt; 1) df.loc[mask, 'data2']= df.loc[mask, 'data2'].str.strip().str.replace("A1","Bad") print (df) key data1 data2 0 A 0 A1 1 B 1 B1 2 C 2 C1 3 A 3 Bad 4 B 4 B1 5 C 5 C1 If need multiple replace use replace with dict: df = pd.DataFrame({'key': ['A', 'A', 'C', 'A', 'B', 'C'], 'data1': range(6), 'data2': ['A1', 'A2', 'C1', 'A1', 'B1', 'C1']}, columns = ['key', 'data1', 'data2']) mask = (df['key']=="A") &amp; (df['data1'] &gt; 0) df.loc[mask, 'data2']= df.loc[mask, 'data2'].str.strip().replace({"A1":"Bad", "A2":'Bad1'}) Or use regex: df.loc[mask, 'data2']= df.loc[mask, 'data2'].str.strip().str.replace(r'^A.*',"Bad") print (df) key data1 data2 0 A 0 A1 1 A 1 Bad1 2 C 2 C1 3 A 3 Bad 4 B 4 B1 5 C 5 C1

http://stackoverflow.com/a/49310525
answers question: http://stackoverflow.com/q/49310392
type: AcceptedAnswer
downvote count: 0
has body: One way to do this would be to plot your classes separately: x = np.random.rand(52,2) labels = np.ones(x.shape[0]) labels[0:8] = 1 labels[8:31] = 2 labels[31:] = 3 for i in np.unique(labels): plt.scatter(x[np.where(labels==i),0], x[np.where(labels==i),1], label=i) plt.legend() plt.show()
accepted answer of: http://stackoverflow.com/q/49310392
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/89401506

http://stackoverflow.com/q/49311098
possible better answer: http://stackoverflow.com/a/49311162
tagged with: python
tagged with: parameter-passing
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85624111
has body: I am writing a function that builds and populates a tree-like data structure, using the treelib library. You create a tree as follows: foo = Tree() ...and go from there, which is standard enough. Here is what I have, simplified: def make_special_tree(tree, arg1, arg2): tree = Tree() other_stuff = things(arg1) modify_tree(tree, other_stuff, arg2) return tree Here's the thing: let's say that I ultimately want a tree object called blah. If I do the following, the command runs without an error: make_special_tree('blah', foo, bar) ...but when I type blah afterward, I get back NameError: name 'blah' is not defined. If I do the following, the command also runs without an error: blah = make_special_tree('yoink', foo, bar) ...and when I type blah afterward, I get back &lt;treelib.tree.Tree object at 0x10e60db10&gt;, which is what I want to see. yoink meanwhile remains undefined, like blah in the previous version. Hence my question--and I can tell this is basic, but I cannot untangle this, in part because I am not sure how precisely to ask the question. As you can see, right now I have to create an instance of class Tree() and I think I have to feed my function an argument to do so. I think that blah = make_special_tree(args) is the correct way to format this, but how can I pass the variable blah as the name of the tree structure I'd like returned?
accepted answer: http://stackoverflow.com/a/49311212
has answer: http://stackoverflow.com/a/49311162
has comment: http://stackoverflow.com/comment/85624051
type: Question
has answer: http://stackoverflow.com/a/49311212
answer count: 2
has title: Variable name to be assigned as argument in a python function
tagged with: function

http://stackoverflow.com/comment/85795038
type: QuestionComment
comment on: http://stackoverflow.com/q/49396521
score: 0
has text: Just look at the answers
type: Comment

http://stackoverflow.com/q/49287690
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/25239933
tagged with: matplotlib
type: UnansweredQuestion
tagged with: python
has title: Creating subplots with matplotlib with different titles Python
duplicate of: http://stackoverflow.com/q/25239933
has answer: http://stackoverflow.com/a/49287877
score: 0
upvote count: 1
has body: I created a small program that does linear and polynomial regression. For now, both regressions are on the same graph. I want to put them to two different graphs (to make subplots), but also I want to have different titles (Linear regression and Polynomial regression). I do not know how to do this, can you please help me? import numpy as np import matplotlib.pyplot as plt import math X = np.array([1,2,3,5,6,7,4,7,8,9,5,10,11,7,6,6,10,11,11,12,13,13,14]) Y = np.array([2,3,5,8,11,14,9,19,15,19,15,16,14,7,13,13,14,13,23,25,26,27,33]) #_______________ polinomial ________________ koeficienti_polinom = np.polyfit(X, Y, 2) a=koeficienti_polinom[0] b=koeficienti_polinom[1] c=koeficienti_polinom[2] xval=np.linspace(np.min(X), np.max(X)) regression=a * xval**2 + b*xval + c predX = float(input("Enter: ")) predY = a * predX**2 + b*predX + c plt.scatter(X,Y, s=20, color="blue" ) plt.scatter(predX, predY, color="red") plt.plot(xval, regression, color="black", linewidth=1) print("Polynomial: ",round(predY,2)) #________________ linear _________________ koeficienti_linear = np.polyfit(X, Y, 1) a1=koeficienti_linear[0] b1=koeficienti_linear[1] xval1=np.linspace(np.min(X), np.max(X)) regression1=a1 * xval1 + b1 predY1 = a1 * predX+ b1 plt.scatter(predX, predY1, color="red") plt.subplot(2,2,2) plt.plot(xval1, regression1, color="black", linewidth=1) plt.xlabel("Size") plt.ylabel("Costs") plt.title("Cost Prediction Graph") plt.grid() print("Linear: ", round(predY1,2)) plt.show()
answer count: 1
downvote count: 1

http://stackoverflow.com/a/49377135
has comment: http://stackoverflow.com/comment/85778721
has comment: http://stackoverflow.com/comment/85778581
has comment: http://stackoverflow.com/comment/85777807
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85778667
has comment: http://stackoverflow.com/comment/85778266
has body: Fortunately, according to the documentation, you can access the complete state of the numpy random number generator using get_state and set it again using set_state. The generator itself uses the Mersenne Twister algorithm (see the RandomState part of the documentation). This means you can do anything you want, though whether it will be good and efficient is a different question entirely. As abarnert points out, no matter how you share the parent's state—this could use Alex Hall's method, which looks correct—your sequencing within each child will depend on the order in which each child draws random numbers from the MT state machine. It would perhaps be better to build a large pool of pseudo-random numbers for each child, saving the start state of the entire generator once at the start. Then each child can draw a PRNG value until its particular pool runs out, after which you have the child coordinate with the parent for the next pool. The parent enumerates which children got which "pool'th" number. The code would look something like this (note that it would make sense to turn this into an infinite generator with a next method): class PrngPool(object): def __init__(self, child_id, shared_state): self._child_id = child_id self._shared_state = shared_state self._numbers = [] def next_number(self): if not self.numbers: self._refill() return self.numbers.pop(0) # XXX inefficient def _refill(self): # ... something like Alex Hall's lock/gen/unlock, # but fill up self._numbers with the next 1000 (or # however many) numbers after adding our ID and # the index "n" of which n-through-n+999 numbers # we took here. Any other child also doing a # _refill will wait for the lock and get an updated # index n -- eg, if we got numbers 3000 to 3999, # the next child will get numbers 4000 to 4999. This way there is not nearly as much communication through Manager items (MT state and our ID-and-index added to the "used" list). At the end of the process, it's possible to see which children…
has comment: http://stackoverflow.com/comment/85778964
has comment: http://stackoverflow.com/comment/85758835
has comment: http://stackoverflow.com/comment/85776371
has comment: http://stackoverflow.com/comment/85778903
has comment: http://stackoverflow.com/comment/85758794
answers question: http://stackoverflow.com/q/49372619
type: Answer

http://stackoverflow.com/comment/85766237
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49382766
has text: you are missing an iterator
score: 1

http://stackoverflow.com/comment/85794269
comment on: http://stackoverflow.com/a/49395852
score: 0
has text: Maybe they only do it on class-based objects, as in the ones declared in python with a class keyword.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85780960
comment on: http://stackoverflow.com/a/49389648
type: Comment
has text: What do you mean?
type: AnswerComment
score: 0

http://stackoverflow.com/a/49310780
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49309527
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49309527
has body: This can also be done nicely with a generator. This generator yields the key item pair if it doesn't have to be squashed, and if it has, it saves the items till the last entry, and then yields it, with a new key and the saved items joined. With the generator a new OrderedDict can be constructed. from collections import OrderedDict def sqaushDict(d, ind, new_key): """ Takes an OrderedDictionary d, and yields its key item pairs, except the ones at an index in indices (ind), these items are merged and yielded at the last position of indices (ind) with a new key (new_key) """ if not all(x &lt; len(d) for x in ind): raise IndexError ("Index out of bounds") vals = [] for n, (k, i), in enumerate(d.items()): if n in ind: vals += [i] if n == ind[-1]: yield (new_key, " ".join(vals)) else: yield (i, k) d = OrderedDict([ ("Sample Code", "Vendor Sample ID"), ("Donor ID", "Vendor Subject ID"), ("Format", "Material Format"), ("Sample Type", "Sample Type"), ("Age", "Age"), ("Gender", "Gender"), ]) t = OrderedDict(squashDict(d, [2, 3], "Random")) print(t)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85626451
downvote count: 0

http://stackoverflow.com/comment/85796828
has text: cool. This gets me what I asked. But, can I have the attributes of the function and the overview about what is happening in the function?
type: Comment
comment on: http://stackoverflow.com/a/49397511
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85843352
score: 0
has text: Use a `dict` to keep track of the numbers of wins per player as you iterate through all matches. Hint: `n_wins = defaultdict(int)` (from `collections`), within loop + logic: `n_wins[winner] += 1`
type: Comment
comment on: http://stackoverflow.com/q/49421113
type: QuestionComment

plaintext
tag name: plaintext
tags question: http://stackoverflow.com/q/49418377
type: Tag

http://stackoverflow.com/comment/85766859
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49382761
has text: I can't tell what the problem is. Which part of this program does something unexpected?
type: Comment

http://stackoverflow.com/comment/85728457
comment on: http://stackoverflow.com/a/49363921
type: Comment
type: AnswerComment
has text: Parameters should be reversed g.checkout( row[2], force=True)
score: 0

http://stackoverflow.com/q/49419339
type: Question
has body: I create emails using an HTML template, and I attach an image to each email. Before sending my emails out I would like to first save them on a disk for a review and then have a separate script to send the saved emails out. Currently, I generate and send emails the following way. from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.MIMEImage import MIMEImage from email.MIMEBase import MIMEBase from email import Encoders fileLocation = 'C:\MyDocuments\myImage.png' attachedFile = "'attachment; filename=" + fileLocation text = myhtmltemplate.format(**locals()) msg = MIMEMultipart('related') msg['Subject'] = "My subject" msg['From'] = 'sender@email.com' msg['To'] = 'receiver@email.com' msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) part = MIMEBase('application', "octet-stream") part.set_payload(open(fileLocation, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', attachedFile) msg.attach(part) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) msgText = MIMEText(text, 'html') msgAlternative.attach(msgText) fp = open(fileLocation, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID msgImage.add_header('Content-ID', '&lt;image1&gt;') msg.attach(msgImage) smtpObj = smtplib.SMTP('my.smtp.net') smtpObj.sendmail(sender, receiver, msg.as_string()) smtpObj.quit() How can I save exactly the same emails to a disk instead of sending them right away?
tagged with: python
has title: Python: how to save emails generated with MIME to disk
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/49419531
answer count: 1
accepted answer: http://stackoverflow.com/a/49419531
favorite count: 0

http://stackoverflow.com/comment/85836847
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49417259
has text: just one more question : what if i have some products with 2 underscore , for example "Biscuit_Plain_Ord". How can i include this in the above code please
score: 0

http://stackoverflow.com/q/49420719
upvote count: 0
tagged with: raspberry-pi
has title: Connect Adafruit_PCA9685- I2C interface in Raspberry pi Python
tagged with: servo
score: -2
tagged with: i2c
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85842552
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85842586
tagged with: python
has answer: http://stackoverflow.com/a/49421620
accepted answer: http://stackoverflow.com/a/49421620
has body: How to Connect Adafruit_PCA9685- I2C using Raspberry Pi and Python?
has comment: http://stackoverflow.com/comment/85842498
type: Question

http://stackoverflow.com/comment/85848274
score: 0
type: Comment
type: QuestionComment
has text: So `OrderSupplierRow` has more than 1 foreign key relationships to `Detail`? All this would be a lot easier if you'd provide the tables you're trying to map against, or analogues that reproduce the error.
comment on: http://stackoverflow.com/q/49412460

http://stackoverflow.com/q/49374323
has body: So I have this piece from html XS 10 x 10 cm 5 300 Ft And I want to get that '5 300' out of it. My code to get that: print(item.find('label',{'for':'productX'}).find('span', attrs={'class': 'p'}).find('span')) but it only prints out this: I hope somebody can help Edit: already tried to write .text to the end but it gives nothing ' '.
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49374497
tagged with: python
has comment: http://stackoverflow.com/comment/85750688
has comment: http://stackoverflow.com/comment/85750389
type: Question
answer count: 3
upvote count: 2
type: UnansweredQuestion
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49374536
has comment: http://stackoverflow.com/comment/85749987
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85773857
has answer: http://stackoverflow.com/a/49374369
has comment: http://stackoverflow.com/comment/85750177
has title: Get number from span which is inside span with beautifulsoup

http://stackoverflow.com/q/49344251
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85688740
has comment: http://stackoverflow.com/comment/85700845
favorite count: 0
type: Question
tagged with: beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85688704
has body: I am new to BeautifulSoup, but I am trying to use the simplest html.parser, however it fails, I have checked the version I am running is BeautifulSoup4 and I am on python 3.6. (Besides, I tried html5lib and lxml both installed but did not work for me) Is there anything I miss out here? import urllib.request import html from BeautifulSoup.bs4 import BeautifulSoup webpage = "https://www.tradingview.com/markets/currencies/rates-major/" websource = urllib.request.urlopen(webpage) soup = BeautifulSoup(websource.read(),'html.parser') FeatureNotFound Traceback (most recent call last) in () 7 websource = urllib.request.urlopen(webpage) 8 ----> 9 soup = BeautifulSoup(websource.read(),'html.parser') 10 11 print(soup) FeatureNotFound: Couldn't find a tree builder with the features you requested: html.parser. Do you need to install a parser library?
has title: BeautifulSoup failed on html.parser
tagged with: python
has answer: http://stackoverflow.com/a/65766692
downvote count: 0

http://stackoverflow.com/comment/127996257
type: AnswerComment
comment on: http://stackoverflow.com/a/49295674
type: Comment
has text: Works as of Django 3.2
score: 0

http://stackoverflow.com/comment/85583863
has text: You could use `df.iat[x, df.columns.get_loc('A')]`, although I'd like to know what it is you're trying to do.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49290347

http://stackoverflow.com/comment/85595017
type: QuestionComment
has text: This might help: https://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49296202

http://stackoverflow.com/comment/138721404
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53961885
has text: I encountered this issue when I was using a version of PyTorch higher than 2.0.1 on my Mac. I could solve the issue after reading this reply. Thanks!

http://stackoverflow.com/a/49288575
has comment: http://stackoverflow.com/comment/85580400
has comment: http://stackoverflow.com/comment/85580420
answers question: http://stackoverflow.com/q/49288533
has comment: http://stackoverflow.com/comment/85580532
type: Answer
has body: Generate pairwise products and flatten them using itertools' product and chain functions (respectively): from itertools import chain, product t = [list(chain.from_iterable(i)) for i in product(a, b)] print(t) [[1, 2, 'a', 'b'], [1, 2, 'c', 'c'], [3, 4, 'a', 'b'], [3, 4, 'c', 'c'], [5, 6, 'a', 'b'], [5, 6, 'c', 'c']] This solution will generalise to any number of lists: x = [a, b, c, ...] t = [list(chain.from_iterable(i)) for i in product(*x)]
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49288533

http://stackoverflow.com/comment/123781832
type: Comment
has text: Thanks! It wors! Is better to indicate a relative path like -> my_path/folder_1. Because with -> /home/my_user/my_path/folder_1 it shows problems.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49418910

http://stackoverflow.com/comment/89283449
type: Comment
type: QuestionComment
has text: I have the same error code. `Process finished with exit code -1073740791 (0xC0000409)`. Running TF/Keras with a Conda environment running Python 3.5
score: 3
comment on: http://stackoverflow.com/q/49432873

http://stackoverflow.com/comment/85812545
has text: If you think about it, stack_depth is incremented every time the find_in_tree() function is called in the recursion. And we are trying to find a particular node in the tree.So the worst cast would be when we have to search through all the nodes in the tree before we find it. Hence, 1,000,000?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49405672
type: AnswerComment

nested
tags question: http://stackoverflow.com/q/49434470
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/49403315
tags question: http://stackoverflow.com/q/49391821
tags question: http://stackoverflow.com/q/49435968
tags question: http://stackoverflow.com/q/49325796
tags question: http://stackoverflow.com/q/49367943
tags question: http://stackoverflow.com/q/49398208
tags question: http://stackoverflow.com/q/49404539
tags question: http://stackoverflow.com/q/49427002
tags question: http://stackoverflow.com/q/49389569
tags question: http://stackoverflow.com/q/49353986

http://stackoverflow.com/a/49416610
has comment: http://stackoverflow.com/comment/85843907
downvote count: 0
score: 1
upvote count: 1
has body: Flask sessions are handled by flask session interface. Flask-Login just check if the current session is fresh. from flask import session def login_fresh(): ''' This returns ``True`` if the current login is fresh. ''' return session.get('_fresh', False) def login_user(): ''' Your login code here ''' session['_fresh'] = True def logout_user(): ''' Your logout code here ''' if '_fresh' in session: session.pop('_fresh') The code snippet above is from Flask-Login source code,that can be accessed here. If you needs the user to login again, just check if his login is fresh.
has comment: http://stackoverflow.com/comment/85859279
has comment: http://stackoverflow.com/comment/85843768
answers question: http://stackoverflow.com/q/49408509
type: Answer

http://stackoverflow.com/comment/85586632
comment on: http://stackoverflow.com/q/49291984
has text: @vivek Kalyanarangam my strings are of equal length.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85592443
type: AnswerComment
comment on: http://stackoverflow.com/a/49293872
score: 0
type: Comment
has text: Thanks for the reply. So, at training time I make the decoder predict, from the batch of encoded inputs, a batch of outputs where the predicted sequences max length is the one of the longest element in the target batch? hoping that it will learn how to pad the outputs by itself? But then at inference time, when I do not work with batches anymore can i use the same net structure, just by initializing the hidden weights with a batch dimension of 1? Also, the dimension you added at the decoder state is the sequence_length dimension, right?

http://stackoverflow.com/q/49312914
downvote count: 0
tagged with: python
has body: I want to merge 2 csv file with a similar column but different header name. a.csv: id name country 1 Cyrus MY 2 May US b.csv: user_id gender 1 female 2 male What I need is, c.csv: id name country gender 1 Cyrus MY female 2 May US male But the result I get when I use the below code import csv import pandas as pd df1 = pd.read_csv('a.csv') df2 = pd.read_csv('b.csv') df3 = pd.merge(df1,df2, left_on=['id'],right_on=['user_id'], how='outer') df3.to_csv('c.csv',index=False) The result I get: id name country user_id gender 1 Cyrus MY 1 female 2 May US 2 male
favorite count: 0
has comment: http://stackoverflow.com/comment/85627545
has answer: http://stackoverflow.com/a/49313000
type: Question
has title: Pandas merge 2 csv with a similar column but different header name
tagged with: pandas
has answer: http://stackoverflow.com/a/49313029
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/49313000
possible better answer: http://stackoverflow.com/a/49313029
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/85680601
type: Comment
type: QuestionComment
has text: Use [**`fractions`**](https://docs.python.org/3/library/fractions.html)
comment on: http://stackoverflow.com/q/49340174
score: 0

http://stackoverflow.com/comment/86214840
type: Comment
comment on: http://stackoverflow.com/a/49344128
type: AnswerComment
score: 0
has text: Thank you for your advise, I'll Google the solution and rewrite the code in a different post.

http://stackoverflow.com/comment/85779646
type: QuestionComment
comment on: http://stackoverflow.com/q/49389054
score: 0
has text: Do you accept pandas method ?
type: Comment

jinja2
tags question: http://stackoverflow.com/q/49429940
tags question: http://stackoverflow.com/q/49395064
tags question: http://stackoverflow.com/q/49419199
tags question: http://stackoverflow.com/q/49308534
tags question: http://stackoverflow.com/q/49429336
tags question: http://stackoverflow.com/q/49425787
tags question: http://stackoverflow.com/q/49426042
tag name: jinja2
tags question: http://stackoverflow.com/q/49343619
tags question: http://stackoverflow.com/q/49380155
tags question: http://stackoverflow.com/q/49412229
tags question: http://stackoverflow.com/q/49316674
tags question: http://stackoverflow.com/q/49404599
tags question: http://stackoverflow.com/q/49366952
tags question: http://stackoverflow.com/q/49375141
type: Tag

http://stackoverflow.com/comment/85654872
comment on: http://stackoverflow.com/q/49324337
score: 0
type: Comment
type: QuestionComment
has text: None of them raise an exception, though sometimes the last coroutine wouldn't execute, I've fixed the problem now, using tasks = asyncio.gather(c1(), c2(), c3()) and then loop.ensure_future(*tasks)

http://stackoverflow.com/comment/85707711
score: 0
comment on: http://stackoverflow.com/q/49330402
type: Comment
has text: The forms are displaying as expected. But if I try to add questions dynamically they won't save and I get the error: ['ManagementForm data is missing or has been tampered with'] and Django requires "fields" argument for inline_formset. '__all__' gets all the fields from model class
type: QuestionComment

http://stackoverflow.com/a/49399801
has comment: http://stackoverflow.com/comment/85805458
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85807703
type: Answer
has comment: http://stackoverflow.com/comment/85806653
accepted answer of: http://stackoverflow.com/q/49388365
has comment: http://stackoverflow.com/comment/85807530
score: 2
answers question: http://stackoverflow.com/q/49388365
has comment: http://stackoverflow.com/comment/85807621
has body: You don't need to repeat that code 19 times. The only purpose of this code is to create 'train.txt' and 'test.txt' files that lists your image files and the label of each image. I don't know how you organize the images on your disk (you say you have a single folder with 4K images) but you should be able to tell what label/class (0..18) each image belongs to. Once you have these lists in the file 'train.txt' and 'test.txt' you can proceed to cread train and validation datasets using convert_imageset tool.
upvote count: 2

http://stackoverflow.com/comment/85832975
has text: Are you asking *how to send text messages* **or** *how run code at a scheduled time* **or** *how to retrieve times from Excel with Python*??
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49415590
type: Comment

http://stackoverflow.com/q/49372813
tagged with: initialization
favorite count: 0
has comment: http://stackoverflow.com/comment/85767278
type: Question
tagged with: numpy
upvote count: 2
has comment: http://stackoverflow.com/comment/85746976
type: UnansweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/85850928
has comment: http://stackoverflow.com/comment/85747330
has title: Why is Numpy faster at creating 3D arrays than 2D arrays?
tagged with: python
linked to: http://stackoverflow.com/q/44487786
score: 2
has comment: http://stackoverflow.com/comment/85749109
answer count: 0
has body: From timing the creation of Nx4096x4096 arrays, it appears Numpy does it much faster when N = 2 or 3 than N = 1: import numpy as np %timeit a = np.zeros((2, 4096, 4096), dtype=np.float32, order='C') 5.24 µs ± 98.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit a = np.zeros((4096, 4096), dtype=np.float32, order='C') 23.4 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) The difference is shocking. Why is that so and how to make the case when N = 1 at least as fast as when N > 1? Could the "%timeit" be simply wrong for timing this? Context: I need to create another single array of 4096 x 4096 with a different type (uint8), and I'm trying to get the fastest Pythonic (or Numpy-related) implementation. The Nx4096x4096 array wil be populated with non-zeros values from a 3-column array (read from a file) where the 1st column are 1D coordinates and 2nd and 3rd column are the intensity values for the 1st and 2nd image (hence the N=2 case). Using sparse matrix is for now not an option. There are 130 million of such files. So the above is happening as many times. [EDIT] This is under Python 3.6.4, numpy 1.14 under macOS Sierra. Same version under Windows do not reproduce the same behavior. The np.zeros() for the smaller array take half the time than the twice-larger array. From the comments and the mentionned duplicate question I understand this can be due to thresholds in memory allocations. This does however defeat the purpose of %timeit. [EDIT 2] Regarding the duplicate question, the question here should be now more about how to time this function properly, without having to write extra code that will access the variable so the OS actually allocates the memory. Wouldn't that extra code bias the result of the timing? Isn't there a simple way to profile this?
downvote count: 0

http://stackoverflow.com/q/49323439
score: 14
type: AnsweredQuestion
has body: I would like to plot the geometry contained in a single row of a geopandas dataframe, but I am having problems. Here an example import geopandas as gpd import numpy as np from shapely.geometry import Polygon p1 = Polygon([(0, 0), (1, 0), (1, 1)]) p2 = Polygon([(2, 0), (3, 0), (3, 1), (2, 1)]) p3 = Polygon([(1, 1), (2, 1), (2, 2), (1, 2)]) index = np.random.random(3) df = gpd.GeoDataFrame() df['index'] = index df['geometry'] = [p1,p2,p3] df = df.set_geometry('geometry') Now if I plot using the command df.plot() I get but if I try to plot only one row, df.loc[:,0].plot() I get the following error TypeError: Empty 'DataFrame': no numeric data to plot, while if if i try df.loc[:,'geometry'].plot() I get AttributeError: 'Polygon' object has no attribute 'plot' What is the correct way of doing this ?
has title: Plot the Geometry of one row of a GeoDataFrame
upvote count: 14
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49323656
tagged with: geopandas
tagged with: python
accepted answer: http://stackoverflow.com/a/49323656

http://stackoverflow.com/a/49450715
upvote count: 1
score: 1
has body: Problem solved, it was a question of the certificates that were being generated incorrectly, use some test certificates and that's it. These are the certificates that you use, you can see the server settings also in that repository. https://github.com/aggress/confluent-kafka-vagrant-ansible
type: Answer
answers question: http://stackoverflow.com/q/49433367
downvote count: 0

http
tags question: http://stackoverflow.com/q/49327478
tags question: http://stackoverflow.com/q/49291934
tags question: http://stackoverflow.com/q/49353242
type: Tag
tags question: http://stackoverflow.com/q/49290124
tags question: http://stackoverflow.com/q/49369356
tags question: http://stackoverflow.com/q/49396600
tags question: http://stackoverflow.com/q/49418617
tags question: http://stackoverflow.com/q/49392595
tags question: http://stackoverflow.com/q/49343095
tags question: http://stackoverflow.com/q/49369254
tag name: http
tags question: http://stackoverflow.com/q/49342139
tags question: http://stackoverflow.com/q/49289262

http://stackoverflow.com/comment/85761824
type: QuestionComment
comment on: http://stackoverflow.com/q/49323183
type: Comment
score: 0
has text: @Vino. hey, if you found my answer helpful, please consider accepting it.

http://stackoverflow.com/comment/85708859
has text: Do you have an example of what you've tried already?
type: QuestionComment
comment on: http://stackoverflow.com/q/49352561
type: Comment
score: 4

http://stackoverflow.com/a/49326143
has comment: http://stackoverflow.com/comment/85654322
answers question: http://stackoverflow.com/q/49325796
has comment: http://stackoverflow.com/comment/85654900
score: 1
has comment: http://stackoverflow.com/comment/85654972
type: Answer
has comment: http://stackoverflow.com/comment/85654720
has body: One way is to use try / except: n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135', '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121'] i = {'10.2.94.38': {'area': '0.0.1.8'}} def try_get_all(i, n): for j in n: try: yield i[j]['area'] except KeyError: yield 'NA' res = list(try_get_all(i, n)) # ['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '0.0.1.8', 'NA', 'NA']
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49325796
upvote count: 1

http://stackoverflow.com/comment/85564035
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49280161
score: 0
has text: I see that Weißenburg and Emetzheim are both in Bayern in that example. Would it be possible to show us all, or most, of the possibilities in the files with which the software would have to cope?

http://stackoverflow.com/comment/85724932
comment on: http://stackoverflow.com/a/49362247
type: Comment
has text: Spot on, makes sense. Thanks a bunch
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85862169
score: 0
type: Comment
type: QuestionComment
has text: That's different version and situation.
comment on: http://stackoverflow.com/q/49369702

http://stackoverflow.com/comment/85864438
comment on: http://stackoverflow.com/q/49428054
score: 1
type: Comment
type: QuestionComment
has text: http://www.statsmodels.org/devel/statespace.html#vector-autoregressive-moving-average-with-exogenous-regressors-varmax is already in 0.8, AFAIR, but doesn't have all the post-estimation extras yet

http://stackoverflow.com/comment/85563119
score: 0
comment on: http://stackoverflow.com/q/49280160
type: Comment
type: QuestionComment
has text: I don't think so, at least not without plugins.

http://stackoverflow.com/q/49348745
has title: Iterate list(a) through a bigger list(b) to give True/False values if items in list(a) exist in list(b)
tagged with: loops
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49348991
has comment: http://stackoverflow.com/comment/85697273
has body: I have two lists: a = ['A', 'B', 'C', 'D'] b = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] I would like to check list A against list B, so that if an item in list A exists in list B, I get a True result, and if not, False. i.e. c = [False, True, True, True] I've tried the following: c = [False for i in range(len(a))] for i in a: for j in b: if a[i] == b[j]: c[i] = True I get the error: TypeError: list indices must be integers, not str I've also tried: c = [True for i in a if i in b] which returns: c = [True, True] I would like the correct answer to be c = [False, True, True]
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49348783
answer count: 4
has answer: http://stackoverflow.com/a/49348784
score: 2
has answer: http://stackoverflow.com/a/49349454
has comment: http://stackoverflow.com/comment/85697232
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/49289283
has body: Issue is in your second command. Change it from PYTHONPATH=“${PYTHONPATH}:/Users/hunminpak/Documents/game/sound/ export PYTHONPATH” to two commands. First command (remove the trailing /): PYTHONPATH=“${PYTHONPATH}:/Users/hunminpak/Documents/game/sound" Hit enter and then type second command: export PYTHONPATH
score: 0
answers question: http://stackoverflow.com/q/49289216
type: Answer

http://stackoverflow.com/comment/85757177
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49378237
score: 0
has text: @ZhekaKoval... Sorry I dnt understand?

http://stackoverflow.com/q/49395512
type: AnsweredQuestion
has title: Finding out the position of an exception while processing a file
has comment: http://stackoverflow.com/comment/85792890
tagged with: exception
has body: I'm processing some semi-structured documents in Python and I have some code that reads the file into a tuple and loops through each line and performs a function. Is there a way of finding the exact line in the processed file where an error is encountered? c = tuple(open("file", 'r')) for element in c: if (condition is met): do something else: do something else The result should be: Error: in line # of "file"
score: 1
accepted answer: http://stackoverflow.com/a/49395552
tagged with: python
has answer: http://stackoverflow.com/a/49395552
possible better answer: http://stackoverflow.com/a/49395811
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49395811
upvote count: 2
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85792921

http://stackoverflow.com/a/49387072
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49308626
type: Answer
has body: From my understanding, you've got a source that updates once every day that you load to df1. Then you'd like to add that df1 to a df2 that stores all the values that you've seen in df1 so far. I'm basing my suggestion on a df1 with the same structure as yours, but with random values. Every time you run this code, it will append those values to a text file df2.txt stored in the folder c:\timeseries. Here we go: Add a folder C:/timeseries/ to your system. Then add an empty .txt file, enter the string dates,A,B,C, and save it as df2.txt. The following snippet will take the length of that textfile and use that to build on a daily index to mimic your situation. That index will be the date for your df1 that is otherwise filled with random numbers every time the snippet is run. And for each time the snippet is run, the data from df1 will be appended to df2. So, run this snippet once... # imports import os import pandas as pd import numpy as np os.chdir('C:/timeseries/') # creates df1 with random numbers df1 = pd.DataFrame(np.random.randint(0,10,size=(1, 3)), columns=list('ABC')) # Read your historic values (will be empty the first time you run it) df2 = pd.read_csv('df2.txt', sep=",") df2 = df2.set_index(['dates']) # To mimic your real life situation, I'm adding a timeseries with a datestamp # that starts where df2 ends. If df2 i empty, it starts from 01.01.2018 # Make a dummy datelist to mimic your situation datelist = pd.date_range(pd.datetime(2018, 1, len(df2)).strftime('%Y-%m-%d'), periods=1).tolist() df1['dates'] = datelist df1 = df1.set_index(['dates']) df1.index = pd.to_datetime(df1.index) df2 = df2.append(df1) df2.to_csv('df2.txt') print(df2) ... to get this output: A B C dates 2018-01-01 00:00:00 8.0 6.0 8.0 Those are the current values of df1 and df2 at the time being. I'm not using a random seed here, so your data will differ from mine. Run it ten times in a row and you'll get this: A B C dates 2018-01-01 00:00:00 8.0 6.0 8.0 2018-01-02 00:00:00 9.0 1.0 0.0 2018…

http://stackoverflow.com/q/49425805
has comment: http://stackoverflow.com/comment/85861703
has body: I am trying to build a plot using matplotlib.pyplot as plt. For example plt.hist(df.amount, bins = 30) But when I hit enter in the console it generates the graph. I want to apply xlim, ylim and title functions of plt but can't do this. Anyone familiar with this behavior? Should I change Spyder settings? Same behavior with Seaborn package.
tagged with: matplotlib
has title: Python 3.6 matplotlib.pyplot shows graph immediately without letting me apply other functions?
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85866935
has comment: http://stackoverflow.com/comment/85852987
accepted answer: http://stackoverflow.com/a/49432623
answer count: 1
has answer: http://stackoverflow.com/a/49432623
has comment: http://stackoverflow.com/comment/85855744
has comment: http://stackoverflow.com/comment/85862597
type: Question
tagged with: spyder

http://stackoverflow.com/q/49339890
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/85688190
upvote count: 1
has body: So I'm training my neural network on closing prices and volumes of a commodity. I'm fully aware the approach is incredibly naive, it's purpose is it's meant to be. However I'm getting strange results from model.predict. my results The blue line is the training data and the orange what the model predicts the training data is with model.predict_on_batch(training). It seems the model is trained well because the green line is the neural network running model.predict_on_batch(validation). However when I take the last value and run it through model.predict and then make a list by using the output of that as the next input for model.predict to make a future guess at stock prices I get the red line. It seems strange that's what the neural network predicts when it gets the validation set fairly right. Both model.predict and model.predict_proba give the same result. The main code is here: https://gist.github.com/anonymous/04f8f6022e93af0edad4cd6fbac118f2 How am I using the model.predict method wrong here?
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85680095
type: UnansweredQuestion
tagged with: neural-network
downvote count: 0
tagged with: machine-learning
tagged with: python
has title: How does Keras predict work?
has comment: http://stackoverflow.com/comment/85683386

http://stackoverflow.com/a/57039627
has body: Referring to this link helped me solve the problem. https://github.com/pyca/cryptography/issues/3489 Basically, by linking openssl in mac by $ brew link openssland installing cryptography==2.1.4, the problem was resolved.
answers question: http://stackoverflow.com/q/49375054
type: Answer
score: 0

http://stackoverflow.com/comment/85841502
type: QuestionComment
comment on: http://stackoverflow.com/q/49419931
has text: @chepner I am a little confused here. Are you suggesting to let the `Singleton` class be a subclass of `ABCMeta` instead of `type`? I am not familiar with the `abc` module, will appreciate an explanation
score: 0
type: Comment

http://stackoverflow.com/q/49286358
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85575598
tagged with: python
has title: Correct misspelled words with Python
has body: I need to clean the misspelling words in a query like "eat an appple", "eat an bannnna". I have tried the autocorrect function but it only works for single words. from autocorrect import spell spell("appple") it returns the correct word "apple". However, for the whole sentence, it does not work. I wonder if there is any easier way to automatically correct the misspelling words in a sentence without writing a loop.
score: 0
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/49286410
type: Question
tagged with: spell-checking
has comment: http://stackoverflow.com/comment/85575569

http://stackoverflow.com/comment/85614436
has text: How can I check it? I mean, there's no problem with that but I thought that MONEY is a basic one.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49306083
type: QuestionComment

http://stackoverflow.com/comment/85787020
type: AnswerComment
comment on: http://stackoverflow.com/a/49385562
type: Comment
score: 0
has text: I think the second option is what im looking for, as the prediction function is what i'm looking for, thanks!

http://stackoverflow.com/q/49388141
downvote count: 7
has comment: http://stackoverflow.com/comment/85777699
has answer: http://stackoverflow.com/a/49388234
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/49388234
tagged with: python
score: -6
favorite count: 0
type: Question
has body: data.json content { "response": { "numFound": 1, "data_block": [ { "Number": "11097", "ID": -61000, "Version": "18", "Sequence": [ "1", "2", "3" ], "Status": [ "Booked", "Canceled", "Canceled" ], "Name": "abc", "EmailAddress": "abc@test.com" } ] } } I am looking to get values in below format Number~Sequence~Status 11097~1|2|3~Booked|Canceled|Canceled Tried below, but getting KeyError: 'data_block' import json from pprint import pprint data = json.load(open('data.json')) pprint(data) data["data_block"][0]["Number"]
answer count: 1
has title: Json parsing Python
upvote count: 1

http://stackoverflow.com/comment/85862439
comment on: http://stackoverflow.com/a/49415959
has text: the {{ reqeust.user }} in the layout shows the loged in user name in the top of the page. If I click logout that disappears, and then if I go to the login page and input a valid username and password it re-appears. Plus I imported login_required and used that it still lets me go to the create_post page
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49378863
accepted answer of: http://stackoverflow.com/q/49374984
has comment: http://stackoverflow.com/comment/86949748
has comment: http://stackoverflow.com/comment/87035593
has body: As I read through the code I found the responsible code, which only retains the pre-trained model's weights if the shape of the layers between the newly-defined model and the pre-trained model match. So if I change the number of the class, the shape of the classifier layers change, and the pre-trained weights are not retained. https://github.com/tensorflow/models/blob/master/research/object_detection/utils/variables_helper.py#L133
has comment: http://stackoverflow.com/comment/87022922
has comment: http://stackoverflow.com/comment/86917974
downvote count: 0
has comment: http://stackoverflow.com/comment/86920481
answers question: http://stackoverflow.com/q/49374984
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87074634
has comment: http://stackoverflow.com/comment/87181947
has comment: http://stackoverflow.com/comment/87166169
has comment: http://stackoverflow.com/comment/86940046
has comment: http://stackoverflow.com/comment/86921900
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85892712
comment on: http://stackoverflow.com/a/49352066
score: 0
has text: @Fiver, as you wish! Perhaps @AndyS[eaborn] can give a formal proof, or there is something like such proof in articles of Claudio Gutierrez. BTW, it seems that there are some problems in SPARQL formal semantics (see e.g. section 2 in [this paper](https://arxiv.org/pdf/1606.01441.pdf)). Perhaps you could also ask you question at [public-sparql-dev](https://lists.w3.org/Archives/Public/public-sparql-dev/)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49416387
has title: Is resetting Python thread/process tasks by calling self.run() pythonic?
has comment: http://stackoverflow.com/comment/85836877
tagged with: multiprocessing
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49430345
has comment: http://stackoverflow.com/comment/85835229
accepted answer: http://stackoverflow.com/a/49430345
has body: Regarding the code below of the process class MyProcessClass, sometimes I want to rerun all of the self.run tasks. self.run(retry=True) is what I use to rerun the run(self) tasks within the class. It allows me rerun the tasks of the process class run(self) whenever I want to from wherever I want to from any class function. MyProcessClass(Process): def __init__(self): Process.__init__(self) #gets called automatically on class initialization #process.start(). #it also gets called when a class function calls #self.run(retry=True) def run(self,end=False,retry=False): if end==True: sys.exit() elif retry==True: redo_prep() do_stuff() #represents class functions doing stuff def do_stuff(): #stuff happens well return #stuff happens and need to redo everything self.run(retry=True) I don't want the thread/process to end, but I want everything to rerun. Could this cause problems because the run function is being called recursively-ish and I am running hundreds of these process class objects at one time. The box hits about 32GB of memory when all are running. Only objects that need to will be rerun. My goal is to rerun the self.run tasks if needed or end the thread if needed from anywhere in the class, be it 16 functions deep or 2. In a sense, I am resetting the thread's tasks, since I know resetting the thread from within doesn't work. I have seen other ideas regarding "resetting" threads from How to close a thread from within?. I am looking for the most pythonic way of dealing with rerunning class self.run tasks. I usually use try-catch throughout the class: def function(): while True: try: #something bad except Exception as e: #if throttle just wait #otherwise, raise else: return Additional Question: If I were to raise a custom exception to trigger a @retry for the retries module, would I have to re-raise? Is that more or less pythonic than the example above? My script had crapped out in a way I hadn't seen before and I worried that calling the self.run(retry=True) had cause…
has comment: http://stackoverflow.com/comment/85835506
tagged with: python
has comment: http://stackoverflow.com/comment/85861514
linked to: http://stackoverflow.com/q/4541190
type: Question
has comment: http://stackoverflow.com/comment/85834636
has comment: http://stackoverflow.com/comment/85836726
tagged with: multithreading
answer count: 1

http://stackoverflow.com/comment/85831898
type: Comment
type: QuestionComment
has text: Hi again. Could you please clarify... when you are grouping by the first name. What is the purpose of that? If for instance you have 1000 people named Jane, with different and similar last names, what output would you expect? Do you want to compare everybody with the same first name and similar last names?
comment on: http://stackoverflow.com/q/49356938
score: 0

http://stackoverflow.com/comment/85787044
type: AnswerComment
comment on: http://stackoverflow.com/a/49392721
score: 1
has text: `df.loc[(df["Before"] == "Injection") & (df["After"] == "Production"),'Output'] = ... ` is the widely known pandas way.
type: Comment

http://stackoverflow.com/a/49331917
type: Answer
has body: You could use a regular expression. For example: isValidIdentifier = re.match("[A-Za-z_](0-9A-Za-z_)*",identifier) Note that his only checks for alphanumeric characters. The actual standard supports other characters. See here: https://www.python.org/dev/peps/pep-3131/ You may also need to exclude reserved words such as def, True, False, ... see here: https://www.programiz.com/python-programming/keywords-identifier
answers question: http://stackoverflow.com/q/49331782
score: 0
has comment: http://stackoverflow.com/comment/85666386
has comment: http://stackoverflow.com/comment/85666364

http://stackoverflow.com/q/49339291
tagged with: string
tagged with: parameter-passing
favorite count: 0
has comment: http://stackoverflow.com/comment/85678779
tagged with: list
has comment: http://stackoverflow.com/comment/85678747
type: Question
downvote count: 3
tagged with: python
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/85680750
has answer: http://stackoverflow.com/a/49339378
has title: Python: How can I pass and use variable in function?
tagged with: function
has body: Is it possible to pass a variable (e.g. string) to function in python a later use it as a name of a list? How can I convert it? def compare(string_variable, filename): with open(filename) as fr: for line in fr: variable.writelines(line) compare(string_variable , filename) —— edit —— this isn't the full code, it's not even the actual code as I wanted to simplify it in order to make my question as narrow as possible. I see I made a stupid mistake writing string.writlines etc. Below is the corrected version in pseudo code made really fast, so sorry if I made any mistakes What I'm trying to do is pass a string variable to a function, use this variable as a list, append lines to it and save it in memory for later comparisons. this would be done thorugh a loop based on dict key: value, so I want my list to have the name like key value from the dict in order to generated a differently named list each time I go through a loop. something like: x = { key: value key2: value2 } def compare(key, filename): with open(filename) as fr: for line in fr.readlines(): key_but_as_list.append(line) for key in x.keys() compare(key, filename) Do you get my idea now?
has comment: http://stackoverflow.com/comment/85678667
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85678689

http://stackoverflow.com/a/49364954
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49364677
score: 1
has body: First, add a list attribute to your App object by adding: self.variable = list() # or [] inside __init__ in order to have access to the value in the scope the object exists. Then modify OnDoubleClick in order to append(as opposed to assigning) to the newly used self.variable. Replace: variable = operacion.calculo(item) with: self.variable.append(operacion.calculo(item))
downvote count: 0

http://stackoverflow.com/q/49388548
has comment: http://stackoverflow.com/comment/85817964
upvote count: 4
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: google-app-engine-python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85813488
tagged with: google-app-engine
has body: I use remote_api_shell.py frequently, and I'd like to automate adding the path to my vendored libraries. This is what I currently do: cat appengine_config.py This outputs: from google.appengine.ext import vendor vendor.add('lib') python ~/google-cloud-sdk/platform/google_appengine/remote_api_shell.py myapp Copy and paste the output of 1 into the shell. Is there a way to start remote_api_shell.py and have it automatically include vendored libs? Further, is there to execute a Python script that will be in the environment of remote_api_shell.py? I want to do some data processing locally that needs to be within the GAE sandbox.
tagged with: python
has title: Adding path to remote_api_shell.py automatically
score: 4
has comment: http://stackoverflow.com/comment/85797684

http://stackoverflow.com/comment/85598159
type: QuestionComment
has text: @Daniel F, I would say in practice A and B are no greater than dim(500). Eigendecomposition could work, but I can’t see how that would eliminate the loop/multiple calls to expm.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49290187

http://stackoverflow.com/comment/85579148
comment on: http://stackoverflow.com/q/49287957
type: QuestionComment
has text: What is xyz? Can you explain a bit more? Away from the mean of what?
score: 0
type: Comment

http://stackoverflow.com/a/49285005
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49284203
score: 3
accepted answer of: http://stackoverflow.com/q/49284203
has body: As I explained in EDIT2, I printed out the line that was giving me trouble, and saw that it did not end in a }, which every JSON Object should. I then went into the file, and checked the exact line that was giving me trouble by using a simple search, and I found that the line was not only truncated, but it was also the last line of my file as well. There was definitely an error when I was either downloading or extracting this file, and it seemed to cut it short. This in turn threw the error that I got with no solution seeming to work. To anyone who is having this error and .replace() solutions are not working: try to look through your data and make sure that there is in fact something there to replace or edit. In my case there was a truncating error during the download or extraction which made such solutions impossible. Big thanks to abarnert, Michael Robellard and Anton Kachurin
type: Answer

http://stackoverflow.com/a/49478614
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49396263
has body: def main2(): sw=17 GPIO.setmode(GPIO.BCM) GPIO.setup(sw, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setwarnings(False) GPIO.setup(2, GPIO.OUT) pwm_red = GPIO.PWM(2, 50) pwm_red.start(100) bright=100 state=-1 while True: swin=GPIO.input(sw) while swin == False: if state == 1 and bright !=100: bright+=5 pwm_red.ChangeDutyCycle(bright) print(bright) while GPIO.input(sw)==1: state *= -1 time.sleep(0.1) if bright == 100: state *=-1 time.sleep(0.3) if bright == 0: state *=-1 time.sleep(0.3) if state == -1 and bright !=0: bright-=5 pwm_red.ChangeDutyCycle(bright) print(bright) while GPIO.input(sw)==1: state *= -1 time.sleep(0.1)

http://stackoverflow.com/a/49301415
has comment: http://stackoverflow.com/comment/85604995
has comment: http://stackoverflow.com/comment/85605122
has comment: http://stackoverflow.com/comment/85604914
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85604663
has body: Used Pandas dataframe. aa=[{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'}, {'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'}, {'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}] df = pd.DataFrame(aa) def add_service(x): return " ".join(x) def add_charge(x): #results = map(int, x) # In py2 results = list(map(int, x)) #In py3: return sum(results) def add_comp(x): a = list(set(x)) return " ".join(a) grouped = df.groupby(['receipt_id']) ser = grouped['service'].agg(add_service) cha = grouped['charge'].agg(add_charge) com = grouped['company'].agg(add_comp) df_new = pd.DataFrame({"service": ser, "charge": cha, "company": com}) list(df_new.T.to_dict().values()) # To get json format
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49300970

http://stackoverflow.com/q/49303765
tagged with: numpy
has title: Append columns to numpy array
type: UnansweredQuestion
answer count: 1
tagged with: arrays
type: Question
score: 0
has answer: http://stackoverflow.com/a/49303843
linked to: http://stackoverflow.com/q/8486294
tagged with: python
duplicate of: http://stackoverflow.com/q/8486294
has body: If I set up a four column zeros array: X_large = np.zeros((X.shape[0], 4) And I have an array X as below: X = np.array([ [0, 1] [2, 2] [3, 4] [6, 5] ]) How can I get X_large to take X and have the last two columns show the first value of each row of the array squared and the second value of each row of the array cubed? Meaning: X_large = [ [0, 1, 0, 1], [2, 2, 4, 8], [3, 4, 9, 64], [6, 5, 36, 125] ] This is probably not too hard, but I'm a pretty novice programmer in general. Thanks!

http://stackoverflow.com/comment/85657365
score: 0
comment on: http://stackoverflow.com/q/49326588
type: Comment
type: QuestionComment
has text: @PauloAlmeida No they are not being deleted. I want to have control over these folders and specify which one get updated and which one get ignored.

http://stackoverflow.com/q/49348999
type: Question
has title: Dlib was compiled to use SSE41 instructions, but these aren't available on your machine
has comment: http://stackoverflow.com/comment/85698515
tagged with: sse
tagged with: linux
has comment: http://stackoverflow.com/comment/85700203
has comment: http://stackoverflow.com/comment/120828721
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/85743794
tagged with: python
tagged with: dlib
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85699446
has comment: http://stackoverflow.com/comment/120782232
has comment: http://stackoverflow.com/comment/120834650
has comment: http://stackoverflow.com/comment/85700834
has body: I installed Dlib(on Linux) for Python2.7 using : pip install dlib The installation was successful. However, when I enter the Python interactive mode and try to import dlib , It throws a (warning?) messages saying: Dlib was compiled to use SSE41 instructions, but these aren't available on your machine. Is this something related to the hardware? I'm not using a very new machine but everything else works just fine. Is there any other way in which I can install this? NOTE : I'm using virtualenvs. I tried using anaconda initially, where I was able to install dlib too, but I do not want to use that. Thanks in advance!

http://stackoverflow.com/comment/86333022
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49398948
has text: I posted a new question regarding ROC-curves from your function here: https://stackoverflow.com/questions/49661591/higher-roc-auc-and-f-1-scores-but-poor-looking-roc-curves
type: Comment

http://stackoverflow.com/q/49364409
has title: th convert.lua segmentation fault (core dumped)
answer count: 0
type: UnansweredQuestion
has body: I am trying to run a preprocessing part of a project of Neural Question Generation I am using Linux OS, and using the command line to run the commands appear in the GitHub project: "https://github.com/xinyadu/nqg". When I am writing the commend: "th convert.lua" there is a line: "array = npy4th.loadnpy("qg.src.840B.300d.npy")" after running this line, I get an error: "segmentation fault (core dumped)". I don't understand what I do wrong and what the error in this context means. It is my final project and hope you can help me!!
tagged with: neural-network
has comment: http://stackoverflow.com/comment/85733263
tagged with: segmentation-fault
tagged with: python
has comment: http://stackoverflow.com/comment/85731337
tagged with: lua
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85746999
tagged with: nlp
favorite count: 0
type: Question

http://stackoverflow.com/q/49418243
type: Question
possible better answer: http://stackoverflow.com/a/77144323
score: -2
tagged with: python
type: AnsweredQuestion
has title: Python Scoreboard global variable noob
answer count: 2
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/77144323
has body: I am receiving an error that the variable RedScore is not defined. Originally I created this using a keyboard for raw_input and have everything working, that is until I tried to include momentary switches to control everything. The error I am receiving is around the while statement at the end. that does not necessarily mean the rest of the program is working. I just know there is an error down there. Can someone find my noob mistake? import RPi.GPIO as GPIO import time from time import sleep import Adafruit_CharLCD as LCD # Raspberry Pi configuration: lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's lcd_en = 22 lcd_d4 = 25 lcd_d5 = 24 lcd_d6 = 23 lcd_d7 = 18 lcd_red = 4 lcd_green = 17 lcd_blue = 7 # Pin 7 is CE1 # Define LCD column and row size for 16x2 LCD. lcd_columns = 16 lcd_rows = 2 # Initialize the LCD using the pins above. lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue) lcd.clear() lcd.set_color(0.0,0.0,0.0) GPIO.setmode(GPIO.BCM) bluebutton = 5 blueresetbutton = 6 resetbutton = 13 redresetbutton = 19 redbutton = 26 global BlueScore global RedScore GPIO.setup(bluebutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(blueresetbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(resetbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(redresetbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(redbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP) def bluebutton(channel): global BlueScore BlueScore = BlueScore + 1 lcd.clear() lcd.set_color(1.0, 0.0, 0.0) lcd.message('Red: '+str(RedScore)+' Blue:'+str(BlueScore)) def blueresetbutton(channel): global BlueScore BlueScore = 11 lcd.clear() lcd.set_color(1.0, 0.0, 0.0) lcd.message('Red: '+str(RedScore)+' Blue:'+str(BlueScore)) def resetbutton(channel): global RedScore global BlueScore RedScore = BlueScore = 0 lcd.clear() lcd.set_color(1.0, 1.0, 0.0) lcd.message('NEW GAME!!!\nRed: '+str(RedScore)+'Blue:'+str(BlueScore)) …
has answer: http://stackoverflow.com/a/49418299
accepted answer: http://stackoverflow.com/a/49418299
favorite count: 0

http://stackoverflow.com/comment/85851906
comment on: http://stackoverflow.com/q/49396180
type: Comment
type: QuestionComment
has text: Just to make sure I got your idea right, you're looking for something like [this](https://i.sstatic.net/CBcLa.gif) vs. [this](https://i.sstatic.net/6st6Q.gif)?
score: 0

http://stackoverflow.com/q/49416016
has title: A Program That Shuffles A Deck of Cards?
upvote count: 1
has comment: http://stackoverflow.com/comment/85834125
has comment: http://stackoverflow.com/comment/85833943
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85834108
tagged with: python
has comment: http://stackoverflow.com/comment/85834232
has comment: http://stackoverflow.com/comment/85833986
accepted answer: http://stackoverflow.com/a/49416163
type: AnsweredQuestion
has body: For my intro to programming class, I need to create a program that randomly shuffles a deck of cards and then outputs the rank &amp; suit (shown as a unicode symbol) in a 4x13 grid. What I have so far is below. How do I get it to give a random output? It currently outputs the cards in order by rank and suit. How do I get it to output in a 4x13 grid? It currently outputs in a 13x4 grid. Here's an example of what my output is supposed to look like: example output (For the class, my prof wanted us to list both the separate tuples &amp; nested sequence which is why they're both there, sorry if it makes the code appear messy) import random #Cards SUITS = "\u2663","\u2665","\u2666","\u2660" PIPS = "A","2","3","4","5","6","7","8","9","10","J","Q","K" deck = [("A","\u2663"),("2","\u2663"),("3","\u2663"),("4","\u2663"), ("5","\u2663"),("6","\u2663"),("7","\u2663"),("8","\u2663"),("9","\u2663"), ("10","\u2663"),("J","\u2663"),("Q","\u2663"),("K","\u2663"),("A","\u2665"), ("2","\u2665"),("3","\u2665"),("4","\u2665"),("5","\u2665"),("6","\u2665"), ("7","\u2665"),("8","\u2665"),("9","\u2665"),("10","\u2665"),("J","\u2665"), ("Q","\u2665"),("K","\u2665"),("A","\u2666"),("2","\u2666"),("3","\u2666"), ("4","\u2666"),("5","\u2666"),("6","\u2666"),("7","\u2666"),("8","\u2666"), ("9","\u2666"),("10","\u2666"),("J","\u2666"),("Q","\u2666"),("K","\u2666"), ("A","\u2660"),("2","\u2660"),("3","\u2660"),("4","\u2660"),("5","\u2660"), ("6","\u2660"),("7","\u2660"),("8","\u2660"),("9","\u2660"),("10","\u2660"), ("J","\u2660"),("Q","\u2660"),("K","\u2660")] #Retrieve random card def deal_card(): for suit in SUITS: for pip in PIPS: print(suit + pip,end=" ") print() #Main Portion deal_card()
score: 0
has answer: http://stackoverflow.com/a/49416163
answer count: 1

http://stackoverflow.com/comment/85793809
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49395963
has text: You want the sum for each sublist in the list? That's just `[sum(sublist) for sublist in list]`. If you want to do that for each value in the dict, you can write a dict comprehension. If you don't understand comprehensions, try writing an explicit nested chain of `for` statements that build up a new dict by building up new lists out of sums of sublists.
score: 0

http://stackoverflow.com/q/49281323
tagged with: airflow
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 3
has title: apache airflow on virtualenv: ERROR - Failed to load fernet while encrypting value
has comment: http://stackoverflow.com/comment/85565314
has comment: http://stackoverflow.com/comment/85565763
downvote count: 0
has body: I'm trying to install Apache Airflow on virtualenv. Firstly I created and activated a new python virtual env, then i installed apache-airflow via pip. $ virtualenv $HOME/.p2env -p /usr/bin/python Running virtualenv with interpreter /usr/bin/python New python executable in /home/cass/.p2env/bin/python Installing setuptools, pip, wheel...done. $ source $HOME/.p2env/bin/activate (.p2env) $ pip install apache-airflow Then I try to initialize airflow metadata database i'm getting these errors: (.p2env) $ airflow initdb [2018-03-14 16:50:22,924] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt [2018-03-14 16:50:22,944] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt [2018-03-14 16:50:23,043] {__init__.py:45} INFO - Using executor SequentialExecutor DB: sqlite:////home/cass/airflow/airflow.db [2018-03-14 16:50:23,128] {db.py:312} INFO - Creating tables INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade -&gt; e3a246e0dc1, current schema INFO [alembic.runtime.migration] Running upgrade e3a246e0dc1 -&gt; 1507a7289a2f, create is_encrypted /home/cass/.p2env/local/lib/python2.7/site-packages/alembic/util/messaging.py:69: UserWarning: Skipping unsupported ALTER for creation of implicit constraint warnings.warn(msg) INFO [alembic.runtime.migration] Running upgrade 1507a7289a2f -&gt; 13eb55f81627, maintain history for compatibility with earlier migrations INFO [alembic.runtime.migration] Running upgrade 13eb55f81627 -&gt; 338e90f54d61, More logging into task_isntance INFO [alembic.runtime.migration] Running upgrade 338e90f54d61 -&gt; 52d714495f0, job_id indices INFO [alembic.runtime.migration] Running upgrade 52d714495f0 -&gt; 502898887f84, Adding extra to Log INFO [alembic.runtime.migration] Running upgrade 502898887f84 -&gt; 1b38cef5b76e, add dagrun INFO [alembic.…
answer count: 1
has comment: http://stackoverflow.com/comment/87546371
tagged with: virtualenv
accepted answer: http://stackoverflow.com/a/49300507
favorite count: 0
has answer: http://stackoverflow.com/a/49300507
type: Question
score: 3

http://stackoverflow.com/a/49318284
type: Answer
accepted answer of: http://stackoverflow.com/q/49307872
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85650580
has comment: http://stackoverflow.com/comment/85761036
has body: Take a look at this method of ir.model.data: @api.model def _get_id(self, module, xml_id): """Returns the id of the ir.model.data record corresponding to a given module and xml_id (cached) or raise a ValueError if not found""" return self.xmlid_lookup("%s.%s" % (module, xml_id))[0] It can be used to replace the functionality of self.env.ref. Call it from XMLRPC (send the module name and the XML ID as parameters), and it will return the ID in database of the record with that XML ID. Store that ID in a variable and use this variable to populate team_id. The XMLRPC code will vary depending on the programming language you're using (Pyhon, PHP, Ruby or Java). EDIT As @Naglis said, the method I suggested you is not going to work, as it's a private method. Use the public one, xmlid_to_res_id, to achieve what you need.
score: 2
answers question: http://stackoverflow.com/q/49307872

http://stackoverflow.com/q/49375579
tagged with: python
has comment: http://stackoverflow.com/comment/85752947
has title: Python - Convert the array in a tuple to just a normal array
score: 0
has comment: http://stackoverflow.com/comment/85752936
has comment: http://stackoverflow.com/comment/85752958
has comment: http://stackoverflow.com/comment/85752678
answer count: 1
has comment: http://stackoverflow.com/comment/85752449
has answer: http://stackoverflow.com/a/49376141
has comment: http://stackoverflow.com/comment/85752738
type: Question
linked to: http://stackoverflow.com/q/15112964
tagged with: numpy
type: UnansweredQuestion
has body: I have a signal where I want to find the average height of the values. This is done by finding the zero crossings and calculating the max and min between each zero crossing, then averaging these values. My problem occurs when I want to use np.where() to find where the signal is crossing zero. When I use np.where() I get the result in a tuple, but I want it in an array where I can count the amount of times zero is crossed. I am new to Python and coming from Matlab it is a bit confusing with all the different classes. As you can see, I get an error because nu = len(zero_u) gives 1 as a result, because the whole array is written in a tuple as one element. Any ideas how to go around this? The code looks like this: import numpy as np def averageheight(f): rms = np.std(f) f = f + (rms * 10**-6) # Find zero crossing fsign = np.sign(f) fdiff = np.diff(fsign) zero_u = np.asarray(np.where(fdiff &gt; 0)) + 1 zero_d = np.asarray(np.where(fdiff &lt; 0)) + 1 nu = len(zero_u) nd = len(zero_d) value_max = np.zeros((nu, 1)) value_min = np.zeros((nu, 1)) imaxvec = np.zeros((nu, 1)) iminvec = np.zeros((nu, 1)) if (nu &gt; 2) and (nd &gt; 2): if zero_u[0] &gt; zero_d[0]: zero_d[0] = [] nu = len(zero_u) nd = len(zero_d) ncross = np.fmin(nu, nd) # Find Maxima: for ic in range(0, ncross - 1): up = int(zero_u[ic]) down = int(zero_d[ic]) fvec = f[up:down] value_max[ic] = np.amax(fvec) index_max = value_max.argmax() imaxvec[ic] = up + index_max - 1 # Find Minima: for ic in range(0, ncross - 2): down = int(zero_d[ic]) up = int(zero_u[ic+1]) fvec = f[down:up] value_min[ic] = np.amin(fvec) index_min = value_min.argmin() iminvec[ic] = down + index_min - 1 # Remove spurious values, bumps and zero_d thr = rms/3 maxfind = np.where(value_max &lt; thr) for i in range(0, len(maxfind)): imaxfind = np.where(value_max == maxfind[i]) imaxvec[imaxfind] = 0 value_max[imaxfind] = 0 minfind = np.where(value_min &gt; -thr) for j in range(0, len(minfind)): iminfind = np.where(value_min == minfind[j]) value_min[…

http://stackoverflow.com/comment/85745942
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [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 can't get [it] to work" is not a problem specification. Tell us exactly what doesn't work for you, including actual and desired outputs.
comment on: http://stackoverflow.com/q/49372279
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/49380461
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49380416
downvote count: 0
has body: You can't pass two separate dictionaries to render. You need one dictionary with two elements: args = {'user_form': user_form, 'profile_form': profile_form} return render(request, 'accounts/edit_profile.html', args)

http://stackoverflow.com/a/49436644
accepted answer of: http://stackoverflow.com/q/49433896
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49433896
has comment: http://stackoverflow.com/comment/85917778
has comment: http://stackoverflow.com/comment/85933446
type: Answer
has body: Looking at setuptools' sources, the default code only does syntax validation of URLs in dependency_links, but all the errors occuring on actual file download attempt stop the script execution. In the example below, the default package index impl is overridden, so that besides the URL syntax validation, an attempt to download the target file is being made. If it fails, the process switches to the next URL. from distutils.errors import DistutilsError import os import tempfile from setuptools import setup from setuptools.command.easy_install import easy_install from setuptools.package_index import PackageIndex as PackageIndexOrig import faker class PackageIndex(PackageIndexOrig): def url_ok(self, url, fatal=False): if super().url_ok(url, fatal): try: tmpfile = os.path.join(tempfile.mkdtemp(prefix='url-ok-check-'), 'file.out') self._attempt_download(url, tmpfile) return True except Exception as ex: msg = 'Download error for %s: %s' % (url, ex) if fatal: raise DistutilsError(msg) self.warn(msg) return False f = faker.Faker() fake_urls = [f.url() + '#egg=django' for i in range(10)] urls = [fake_urls + ['https://github.com/django/django/archive/stable/2.0.x.zip#egg=django'] easy_install.create_index = PackageIndex setup( name='spam', packages=['spam'], install_requires=['django'], dependency_links=urls, ) Test it out: $ pip install faker $ python setup.py install --verbose running install ... Installed /Users/hoefling/.virtualenvs/stackoverflow/lib/python3.6/site-packages/spam-0.0.0-py3.6.egg Downloading https://harris.com#egg=django Download error for https://harris.com#egg=django: Unexpected HTML page found at https://harris.com#egg=django Downloading https://www.torres.com#egg=django Download error for https://www.torres.com#egg=django: Download error for https://www.torres.com#egg=django: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:777) Downloading https://smith.com/#egg=django Download error for https://smith.com/#egg=django: Download error for https://smith.com/…
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/49309147
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85623561
has comment: http://stackoverflow.com/comment/85622000
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85631127
tagged with: aws-step-functions
has comment: http://stackoverflow.com/comment/85620665
score: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/85647962
has title: AWS Lambda: Create archive from s3 files and store it in back on s3
has body: My service stored a lot of files on AWS S3. According to GDPR, I have to implement the possibility to create an archive of these files and store it on S3 as well (for downloading). Also, I have to filter these files. The best options as for me, it is run the lambda functions (as parts of step function) that filter files, extract the content of files, archive, and upload back to S3. I looked for something like Amazon Elastic Transcoder. This service transcodes media on the fly. I hoped to find anything for archiving files. In the worst case, I am going to run the EC2 virtual machine and host there custom service that will create and upload this archive for me. But it isn't the best solution because this functionality will be called time to time and FaaS is the best options for this. Is it possible to find more elegant solution?
tagged with: aws-lambda
type: Question

http://stackoverflow.com/a/49331896
has comment: http://stackoverflow.com/comment/85665996
upvote count: 2
answers question: http://stackoverflow.com/q/49331856
has comment: http://stackoverflow.com/comment/85665927
score: 1
has comment: http://stackoverflow.com/comment/85666035
has comment: http://stackoverflow.com/comment/85665992
downvote count: 1
has comment: http://stackoverflow.com/comment/85666205
has comment: http://stackoverflow.com/comment/85666022
has comment: http://stackoverflow.com/comment/85666241
has comment: http://stackoverflow.com/comment/85666080
has comment: http://stackoverflow.com/comment/85666084
has comment: http://stackoverflow.com/comment/85665958
has comment: http://stackoverflow.com/comment/85666248
has comment: http://stackoverflow.com/comment/85665835
type: Answer
has comment: http://stackoverflow.com/comment/85665968
has comment: http://stackoverflow.com/comment/85666164
has body: Inside create_bookcase, that cls(books) does call the __init__ method.* However, it calls the __init__ method of cls, not the __init__ method of Bookcase. What's the difference? class StoreBookcase(Bookcase): def __init__(self, book_list, backstock=None): super().__init__(book_list) self.backstock = backstock if backstock else [] Now if I call StoreBookcase.create_bookcase, when it does that cls(books), that cls is StoreBookcase. Of course StoreBookcase might want to override create_bookcase to take an optional backstock parameter. But in cases where there are no extra parameters in the subclass, or when you're happy with the default value, you can just use the base class's classmethod like this. So, classmethods can be used to create "alternate constructors" for an entire hierarchy. * Technically, it calls the __new__ method; the __init__ only gets called if __new__ returns an instance of cls, or of course if you explicitly call it. But most classes just use object.__new__, which returns an instance of cls, so __init__ gets called.

http://stackoverflow.com/q/49369778
tagged with: out-of-memory
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85744140
has body: I'm trying to count the occurrence of a large corpus of words in a large pool of documents using multiple threads in a MapReduce-like fashion. Each thread starts with a dictionary mapping every word in the corpus to zero and increments the counts as it goes over the documents. Once all threads are done I want to accumulate the counts. I load the first json file into memory and loop through the rest, summing the counts: def merge_counts(self): path = os.path.join(self.get_current_job_directory(), 'batch_0.json') with open (path, 'r') as json_file: kmers = json.load(json_file) batch = None for i in range(1, self.num_threads): path = os.path.join(self.get_current_job_directory(), 'batch_' + str(i) + '.json') with open (path, 'r') as json_file: batch = json.load(json_file) for kmer in batch: kmers[kmer] += batch[kmer] batch = None return kmers Here kmers is the eventual dictionary containing all the final counts. The number of keys inside kmers remains the same no matter how many batches are load as they all have the same keys only with different counts. Each json file is approx 3 gig large so the final result will also be around the same. I'm expecting this code to use as much memory as holding two such json files in memory (the consensus so far and the current batch) as dictionaries but the memory usage grows linearly with each batch until I eventually run out of memory. Why is that happening? Isn't the previous stuff referenced by the variable batch supposed to be garbage collected when I set it to None? Update: So I added gc.collect() at the end of each loop iteration and the memory still grows linearly with each iteration. Any ideas?
tagged with: garbage-collection
tagged with: python
has title: Python memory increases despite garbage collection
has answer: http://stackoverflow.com/a/58483405
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/85741666
answer count: 1
has comment: http://stackoverflow.com/comment/85740542
tagged with: memory
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85741591
linked to: http://stackoverflow.com/q/1316767

http://stackoverflow.com/comment/92056847
type: Comment
type: QuestionComment
has text: Having the same problem, how did you solve it?
score: 0
comment on: http://stackoverflow.com/q/49291015

http://stackoverflow.com/q/49305946
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49306783
has comment: http://stackoverflow.com/comment/85615181
has body: I am looking for a pythonic/elegant way to transform my list of dict (e.g. LD) into a aggregated list of dict (e.g. DD). The dict in LD have id, result, and count as keys, and there can be multiple dict's with the same id with different results. The resulting dict DD should aggregate the id's together and display all the results together (in results). Here is an example: LD = [ {'id':1, 'result': 'passed', 'count': 10}, {'id':1, 'result': 'failed', 'count': 20}, {'id':2, 'result': 'failed', 'count': 100} ] Here is the output I want DD = [ {'id':1, 'results': {'passed': 10, 'failed': 20}}, {'id':2, 'results': {'passed': 10}} ] I could create a for loop and a output dict to process each items in LD, but am wondering if this can be achieved in a one-liner using things like zip, etc. Thanks in advance!
upvote count: 6
has comment: http://stackoverflow.com/comment/85614187
has answer: http://stackoverflow.com/a/49306121
accepted answer: http://stackoverflow.com/a/49306121
tagged with: python
tagged with: dictionary
score: 4
has title: List of dict to aggregated list of dict
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85614365
downvote count: 2
has answer: http://stackoverflow.com/a/49306783
favorite count: 0

http://stackoverflow.com/a/49311841
has body: It should be named .travis.yml And not Travis.yml Place the file at the project root.
type: Answer
accepted answer of: http://stackoverflow.com/q/49311822
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49311822

http://stackoverflow.com/a/49352066
downvote count: 0
answers question: http://stackoverflow.com/q/49307502
accepted answer of: http://stackoverflow.com/q/49307502
has comment: http://stackoverflow.com/comment/85863601
type: Answer
has comment: http://stackoverflow.com/comment/85892712
score: 4
has body: I can't give a formal proof, but this looks impossible. This is not what property paths were designed for, and why some extensions exist (1, 2). Under certain commitments (e.g. with tree-like structures), it is possible to figure out something using FILTER NOT EXISTS, however, this is not a general solution. The idea is to do this in two queries. In essence, this is SELECT over CONSTRUCT. By the way, such SPARQL extension has already been proposed. Let's use rdflib on which Ontospy is based, because Ontospy does not offer any ontology-editing features, nor it can be used to interrogate a triplestore. Input (ontology.ttl) @prefix : &lt;http://www.example.org/ontology#&gt; . @prefix owl: &lt;http://www.w3.org/2002/07/owl#&gt; . @prefix rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; . @prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; . @base &lt;http://www.example.org/ontology&gt; . &lt;http://www.example.org/ontology&gt; rdf:type owl:Ontology . :hasPart rdf:type owl:ObjectProperty . :Country rdf:type owl:Class ; rdfs:subClassOf [ rdf:type owl:Restriction ; owl:onProperty :hasPart ; owl:someValuesFrom :State ] . :State rdf:type owl:Class ; rdfs:subClassOf [ rdf:type owl:Restriction ; owl:onProperty :hasPart ; owl:someValuesFrom :City ] . :City rdf:type owl:Class . Python code import rdflib g = rdflib.Graph() g.parse("ontology.ttl", format="n3") qres = g.update( """PREFIX : &lt;http://www.example.org/ontology#&gt; INSERT { ?c :hasSome ?p } WHERE { ?c rdfs:subClassOf [ owl:onProperty :hasPart ; owl:someValuesFrom ?p ] }""") qres = g.query( """PREFIX : &lt;http://www.example.org/ontology#&gt; SELECT ?a ?b WHERE {?a :hasSome+ ?b }""") for row in qres: print("%s :hasSome+ %s" % row) qres = g.update( """PREFIX : &lt;http://www.example.org/ontology#&gt; DELETE { ?s :hasSome ?o } WHERE { ?s :hasSome ?o }""") Output :Country :hasSome+ :State :State :hasSome+ :City :Country :hasSome+ :City If you don't want to modify initial RDFLib graph, just create another …
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/49405138
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49404966
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49404966
has comment: http://stackoverflow.com/comment/85812095
has comment: http://stackoverflow.com/comment/85811721
has body: Reshape B to include trailing singleton dimensions as many as there are dims in A - A + B.reshape(B.shape + tuple([1]*A.ndim)) # where A is generic ndarray Some of the NumPy ufuncs have outer method that takes care of all that work. So, for the additions, we could simply use - np.add.outer(B,A)
has comment: http://stackoverflow.com/comment/85811938
type: Answer
has comment: http://stackoverflow.com/comment/85814541
score: 1

http://stackoverflow.com/a/49348176
answers question: http://stackoverflow.com/q/49344643
downvote count: 0
has body: You're looking for {i - 1} there. i -= 1 is a statement which isn't allowed in f-strings. In addition to that, you shouldn't return from your function; that results in only the first iteration of the for loop executing. Instead, either print or create a list out the strings and join them. Finally, consider passing around the starting value of bottles to ninety_nine_bottles. All in all, use the following: def ninety_nine_bottles(n=99): for i in range(n, 0, -1): print(f'{i} bottles of beer on the wall, {i} of beer! You take one down, pass it around, {i-1} bottles of beer on the wall')
type: Answer
score: 8
upvote count: 8
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49344643

http://stackoverflow.com/a/49439467
score: 0
answers question: http://stackoverflow.com/q/49409902
type: Answer
has body: A List Comprehension is the best way to solve this problem but if you want to use a for loop here's some Python code for that: a = [[1,2,3], [2,1,9], [1,6,9], [5,6,7]] # Code def removeOneList(a): for item in a: if item[0] == 1: del item[:] return a print(removeOneList(a))

http://stackoverflow.com/comment/85619504
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49308534
has text: Please add your code

http://stackoverflow.com/comment/85831067
type: QuestionComment
has text: How many actual labels do you have? 10? This would only happen if the number of actual labels you had was 10, but the number of predicted labels is 5. This is why the confusion matrix is 0 for the right side of the matrix because the actual labels 5 through 9 don't map to any labels in the k-means output.
score: 0
comment on: http://stackoverflow.com/q/49413837
type: Comment

http://stackoverflow.com/q/49407172
has answer: http://stackoverflow.com/a/49407307
tagged with: python
possible better answer: http://stackoverflow.com/a/49412765
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85827248
answer count: 2
has body: So, I have a dataframe containing 3 columns each having 631 rows, so I am highlighting only the unique values under each column. df Segment Type Nature of Query Q1 PRIME Request 1 BUSINESS Complaint 2 PRIORITY Critical Request 3 4 5 Now, let's say under 'Segment Type' i want to group 'PRIME' with every row of 'NATURE OF QUERY' and 'Q1' and find size, min, max, mean So tried to use groupby func and i got this: df.groupby(['Segment Type','Nature of Query'])['Q1'].agg([pd.np.size, pd.np.min, pd.np.max, pd.np.mean]) And, i got this: Segment Type Nature of Query size amin amax mean BUSINESS Request 1 4 4 4.000000 PRIME Complaint 1 5 5 5.000000 Critical Request 3 1 2 1.666667 Request 31 1 5 3.387097 PRIORITY Critical Request 1 4 4 4.000000 Request 3 3 5 4.000000 What i wanted as output: Segment Type Nature of Query size amin amax mean BUSINESS Request 1 4 4 4.000000 Complaint 1 5 5 5.000000 Critical Request 3 1 2 1.666667 PRIME Complaint 1 5 5 5.000000 Critical Request 3 1 2 1.666667 Request 31 1 5 3.387097 PRIORITY Complaint 1 5 5 5.000000 Critical Request 1 4 4 4.000000 Request 3 3 5 4.000000 Ignore the size, mean, max etc it is calculated wrt Q1. My main problem is with the values of 'Segment Type' and 'Nature of Query'. If any solution possible, please let me know. Thanks!
tagged with: pandas-groupby
tagged with: pandas
score: 1
has title: To Group each value of one column with every value of other column using groupby in Python Pandas
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49412765
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49407307
has comment: http://stackoverflow.com/comment/85815494

http://stackoverflow.com/q/49297938
type: AnsweredQuestion
tagged with: performance
has body: I just started programming a couple of weeks ago. I'm working with 12 large data sets and need to make comparisons for values in specific columns of the tables. Each table contains x-coordinates (called 'X_IMA') and y-coordinates (called 'Y_IMA') as well as other data which isn't important for this comparison process. The data comes in 4 sets of 3 tables (which I will call table 11, table 12, table 13, for the tables of data set 1) For example, I wish to compare table 11 to table 12 and table 13 and check if there exists an x-coordinate that is equal to an x-coordinate in table 2 and table 3 (within some +- range). If so, I then want to check if the y-coordinate is equal and if that is the case, this is considered a match. Additional data is written to a new file based on the matches. I want to compare matches for all 4 data sets. I'm using nested for loops and if statements to compare; however, the code takes ~2 hours to run on a 20 core cluster which is terribly inefficient for debugging and ensuring that it actually works correctly. Is there anything I can do to clean up my code and shorten the runtime - either tidying up the loops to make them more efficient or is there another method of comparing large data sets in this way? Any input would be greatly appreciated :) Here is the code for just one set (of 4) of table comparisons: for x in range(0, len(table11)): for y in range(0, len(table12)): for z in range(0, len(table13)): if table12[y]["X_IMA"]-5&lt;=table13[z]["X_IMA"]&lt;=table12[y]["X_IMA"]+5 and table12[y]["Y_IMA"]-5&lt;=table13[z]["Y_IMA"]&lt;=table12[y]["Y_IMA"]+5 and table11[x]["X_IMA"]-5&lt;=table13[z]["X_IMA"]&lt;=table11[x]["X_IMA"]+5 and table11[x]["Y_IMA"]-5&lt;=table13[z]["Y_IMA"]&lt;=table11[x]["Y_IMA"]+5: for i in range(0,20):, if table11[x]["X_IMA"]-5&lt;=reglistx[i]&lt;=table11[x]["X_IMA"]+5 and table11[x]["Y_IMA"]-5&lt;=reglisty[i]&lt;=table11[x]["Y_IMA"]+5: rateavg1[i]=(np.mean([table11[x]["RATE"],table12[y]["RATE"],table13[z]["RATE"]])) r…
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49299677
has answer: http://stackoverflow.com/a/49299677
answer count: 1
downvote count: 0
has title: Increasing computation speed of my comparison code for large table values
score: 1
upvote count: 1

http://stackoverflow.com/q/49343748
accepted answer: http://stackoverflow.com/a/49353472
type: AnsweredQuestion
has title: tf.estimator wants label_data and batch_size for prediction Tensorflow
has answer: http://stackoverflow.com/a/49344036
answer count: 2
tagged with: tensor
has answer: http://stackoverflow.com/a/49353472
score: 1
tagged with: predict
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
has body: I have created a network using high level tf APIs such as tf.estimator. Training and evaluating work fine and produce an output. However when predicting on new data, get_inputs() requires label_data and batch_size. The error is: TypeError: get_inputs() missing 2 required positional arguments: 'label_data' and 'batch_size' How can I resolve this so I can make a prediction? Here is my code: predictTest = [0.34, 0.65, 0.88] predictTest is just a test and won't be my real prediction data. get_inputs(), this is where the error is thrown. def get_inputs(feature_data, label_data, batch_size, n_epochs=None, shuffle=True): dataset = tf.data.Dataset.from_tensor_slices( (feature_data, label_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(batch_size) features, labels = dataset.make_one_shot_iterator().get_next() return features, labels Prediction inputs: def predict_input_fn(): return get_inputs( predictTest, n_epochs=1, shuffle=False ) Predicting: predict = estimator.predict(predict_input_fn) print("Prediction: {}".format(list(predict)))
favorite count: 0
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/49344036

http://stackoverflow.com/q/49320399
has answer: http://stackoverflow.com/a/49320560
has answer: http://stackoverflow.com/a/49320506
tagged with: rest
answer count: 3
has comment: http://stackoverflow.com/comment/85642002
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/85641775
favorite count: 0
tagged with: curl
type: Question
has answer: http://stackoverflow.com/a/49320527
tagged with: api
type: UnansweredQuestion
score: -2
has body: I want to call a REST api and get some json data in response in python. curl https://analysis.lastline.com/analysis/get_completed -X POST -F “key=2AAAD5A21DN0TBDFZZ66” -F “api_token=IwoAGFa344c277Z2” -F “after=2016-03-11 20:00:00” I know of python request, but how can I pass key, api_token and after? What is -F flag and how to use it in python requests?
has title: Callling a REST API in python
upvote count: 1

http://stackoverflow.com/q/49329394
score: 5
has comment: http://stackoverflow.com/comment/85661894
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78959396
tagged with: django
has answer: http://stackoverflow.com/a/56504605
favorite count: 0
upvote count: 5
tagged with: factory-boy
has comment: http://stackoverflow.com/comment/85661125
has title: Factory boy yielding a "maximum recursion depth exceeded" error
tagged with: python
has comment: http://stackoverflow.com/comment/85662161
type: Question
has body: I'd like to defined two models, Company and Package. Each Package has only one Company, but a Company can have several Packages. However, each company can have only one default_package (which can be null). I've set this up as follows: class Company(models.Model): default_package = models.OneToOneField( 'dashboard.Package', on_delete=models.SET_NULL, blank=True, null=True, related_name='default_for_%(class)s') class Package(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) where dashboard is the app label. In order to simplify tests with these models, I've created test factories for them using factory_boy as follows: import factory from .models import Company, Package class CompanyFactory(factory.Factory): class Meta: model = Company default_package = factory.SubFactory('dashboard.test_factories.PackageFactory') class PackageFactory(factory.Factory): class Meta: model = Package company = factory.SubFactory(CompanyFactory) Now I'm trying two tests: class DefaultPackageTest(TestCase): def test_1(self): company = Company.objects.create() def test_2(self): company = CompanyFactory() The first one simply creates a Company, whereas the second one tries to do the same thing using the CompanyFactory. Strangely, however, the first test passes, whereas the second one fails: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 233, in recurse return builder.build(parent_step=self, force_sequence=force_sequence) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 272, in build step.resolve(pre) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 221, in resolve self.attributes[field_name] = getattr(self.stub, field_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 355, in __getattr__ declaration = self.__declarations…
answer count: 2

http://stackoverflow.com/comment/85570578
type: QuestionComment
comment on: http://stackoverflow.com/q/49283252
has text: thank you for your suggestions I'll look into it. @joaoavf apologies, please see the edits I've made.
score: 0
type: Comment

http://stackoverflow.com/q/49300192
type: AnsweredQuestion
score: 2
tagged with: pytest
linked to: http://stackoverflow.com/q/5142418
has title: Split a test in different functions with pytest
has body: I'm using pytest and have multiple tests to run to check an issue. I would like to split all tests into different functions like this: # test_myTestSuite.py @pytest.mark.issue(123) class MyTestSuite(): def test_part_1(): result = do_something() assert result == True def test_part_2(): result = do_an_other_something() assert result == 'ok' of course, I implemented issue in conftest.py # conftest.py def pytest_addoption(parser): group = parser.getgroup('Issues') group.addoption('--issue', action='store', dest='issue', default=0, help='') but I don't know how to hook once after testing MyTestSuite and check that all tests of MyTestSuite correctly passed. Does anyone have any ideas? PS: this is my first post on StackOverflow.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49300317
tagged with: testing
has answer: http://stackoverflow.com/a/49300317
upvote count: 2
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/a/49358682
has comment: http://stackoverflow.com/comment/96346718
downvote count: 0
has comment: http://stackoverflow.com/comment/85717648
has body: There's no difference in meaning between these notations. Reference: Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters The same goes for other prefixes. Now regarding VSCode behaviour: the first coloring (with yellow {2}) happens when the editor assumes you're writing a regular expression, the second one (with blue {2}) happens when the editor thinks you're writing a format string, something like "{0}, {1}!".format("Hello", "world"). This becomes more obvious when we add some more syntax: Now, looks like VSCode should treat R"literal" the same as r"literal", but instead it colors it the same as "literal", which is probably a tiny bug that nobody spotted because everyone writes lowercase r. Correction from comment: It's not a bug, it's a feature! VSCode's highlighter makes clever use of the fact that r and R prefixes are equivalent, and allows you, the developer, to have correct coloring by adopting a convention of using r for regex raw strings and R for non-regex raw strings. Raw strings are often interpreted as regular expressions. This is a bit of a problem, because depending on the application this may actually not be the most common case. (...) MagicPython follows a convention that a lower-case r prefix means a regexp string, but an upper-case R prefix means just a raw string with no special regexp semantics.
type: Answer
has comment: http://stackoverflow.com/comment/85717653
has comment: http://stackoverflow.com/comment/131181370
has comment: http://stackoverflow.com/comment/96150908
has comment: http://stackoverflow.com/comment/85717556
accepted answer of: http://stackoverflow.com/q/49358590
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49358590
score: 47
upvote count: 47

http://stackoverflow.com/comment/85654714
type: QuestionComment
has text: See this lovely [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) blog for help. Also, please look up "incremental programming". You've written several blocks of code before testing any of them; there are several errors in the code, and you now face the task of finding and fixing *each* of them before you can get your program to appear to do anything useful. Back up to just the input function, debug that, and don't add (or don't call) more code until you know that's working properly.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49326381

http://stackoverflow.com/comment/85884295
type: Comment
comment on: http://stackoverflow.com/q/49425288
type: QuestionComment
score: 0
has text: There's no way to do that, but I'm sure pycodestyle and pylint would be open to suggestions

http://stackoverflow.com/q/49432084
has body: How do I iterate over text files only within a directory? What I have thus far is; for file in glob.glob('*'): f = open(file) text = f.read() f.close() This works, however I am having to store my .py file in the same directory (folder) to get it to run, and as a result the iteration is including the .py file itself. Ideally what I want to command is either; "Look in this subdirectory/folder, and iterate over all the files in there" OR... "Look through all files in this directory and iterate over those with .txt extension" I'm sure I'm asking for something fairly straight forward, but I do not know how to proceed. Its probably worth me highlighting that I got the glob module through trial and error, so if this is the wrong way to go around this particular method feel free to correct me! Thanks.
type: AnsweredQuestion
answer count: 3
score: 1
tagged with: python
tagged with: loops
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49432211
has answer: http://stackoverflow.com/a/49432500
has comment: http://stackoverflow.com/comment/85865934
has answer: http://stackoverflow.com/a/49432211
has answer: http://stackoverflow.com/a/49432157
has title: Iterating over a text files in a subdirectory
linked to: http://stackoverflow.com/q/3964681
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/20638040
possible better answer: http://stackoverflow.com/a/49432500

http://stackoverflow.com/q/49381355
has comment: http://stackoverflow.com/comment/85763787
type: Question
has title: How to wait till element changes it type
type: UnansweredQuestion
has body: I want to get the value of an element which changes it type based on some condition. So, For checking the type of that element I am using the following code:- wait(driver, 15).until(EC.presence_of_element_located((By.ID, "incident.state"))) if( element_type != "text" ): select = Select(driver.find_element_by_id('incident.state')) selectval=select.first_selected_option.text else: select=driver.find_element_by_id('incident.state') selectval=select.get_attribute('value') Here the problem is I'm always getting the element as select and not text when sometimes the element is text. So, I used time.sleep(5) And it's working.But i don't want to use time.sleep as it's not a good practise. So, I tried with driver.implicitly_wait(10) But it's not waiting Can you tell me what should i use......
tagged with: python
has answer: http://stackoverflow.com/a/49382377
tagged with: webdriver
has comment: http://stackoverflow.com/comment/85767202
has comment: http://stackoverflow.com/comment/85763885
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/85766807
tagged with: selenium
has answer: http://stackoverflow.com/a/49385012

http://stackoverflow.com/q/49358306
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Nesting control dependencies contexts in tensorflow
tagged with: tensorflow
favorite count: 0
type: Question
type: AnsweredQuestion
has body: Running the test below from unittest import TestCase import tensorflow as tf class TestControl(TestCase): def test_control_dep(self): print(tf.__version__) a = tf.get_variable('a', initializer=tf.constant(0.0)) d_optim = tf.assign(a, a + 2) g_optim = tf.assign(a, a * 2) with tf.control_dependencies([d_optim]): with tf.control_dependencies([g_optim]): with tf.control_dependencies([g_optim]): op = tf.Print(a, [a]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(op) sess.run(op) sess.run(op) prints (for instance): 1.4.0 2018-03-18 16:58:08.943349: I C:\tf_jenkins\...\logging_ops.cc:79] [0] 2018-03-18 16:58:08.943349: I C:\tf_jenkins\...\logging_ops.cc:79] [2] 2018-03-18 16:58:08.943349: I C:\tf_jenkins\...\logging_ops.cc:79] [4] but I have also seen other outputs as in [2, 8, 10]. I would expect it to print [8, 40, 168] (actually I was wanting to make sure g_optim would execute twice which I was not sure it would). Why are not the prints deterministic and why does it not seem to always execute g_optim? NB: running this on an Ubuntu GPU server on EC2 (with tensorflow 1.6) produces 0 all the time: python3 -m unittest tf_test.TestControl.test_control_dep 1.6.0 2018-03-19 08:06:11.614220: ... 2018-03-19 08:06:12.282375: I tensorflow/core/common_runtime/gpu/gpu_device.cc:993] Creating TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 9610 MB memory) -&gt; physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7) [0] [0] [0] 0.0 . ---------------------------------------------------------------------- Ran 1 test in 0.833s OK Maybe related: Control dependencies and order of evaluation
linked to: http://stackoverflow.com/q/43916019
tagged with: python
accepted answer: http://stackoverflow.com/a/49371681
has answer: http://stackoverflow.com/a/49371681

http://stackoverflow.com/q/49425056
type: Question
type: UnansweredQuestion
has body: I can't save a keras model when using a lambda layer and shared variables. Here's a minimal code that gives this error : # General imports. import numpy as np # Keras for deep learning. from keras.layers.core import Dense,Lambda from keras.layers import Input from keras.models import Model import keras.backend as K n_inputs = 20 n_instances = 100 def preprocess(X,minimum,span): output = (X - minimum)/span return output inputs = Input(shape=(n_inputs,),name='input_tensor') maximum = K.max(inputs) minimum = K.min(inputs) span = maximum - minimum x = Lambda(preprocess,arguments={'minimum':minimum,'span':span})(inputs) x = Dense(units=100,activation='elu')(x) outputs = Dense(units=n_inputs,activation='elu')(x) model = Model(inputs=inputs,outputs=outputs) model.compile(optimizer='adam', loss='mse') x = np.array([np.random.randn(20) for i in range(n_instances)]) y = np.array([np.random.randn(20) for i in range(n_instances)]) model.fit(x,y,epochs=10) model.save('test.h5') # This line doesn't work. And here's the full error I am getting : Traceback (most recent call last): File "C:\Dropbox\HELMo_Gramme\M2\Stage\Programmation\Filter\sanstitre0.py", line 35, in &lt;module&gt; model.save('test.h5') # This line doesn't work. File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 2580, in save save_model(self, filepath, overwrite, include_optimizer) File "C:\ProgramData\Anaconda3\lib\site-packages\keras\models.py", line 111, in save_model 'config': model.get_config() File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 2421, in get_config return copy.deepcopy(config) File "C:\ProgramData\Anaconda3\lib\copy.py", line 150, in deepcopy y = copier(x, memo) File "C:\ProgramData\Anaconda3\lib\copy.py", line 240, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\ProgramData\Anaconda3\lib\copy.py", line 150, in deepcopy y = copier(x, memo) File "C:\ProgramData\Anaconda3\lib\copy.py", line 215, in _deepcopy_lis…
downvote count: 0
score: 6
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49425867
tagged with: python
has answer: http://stackoverflow.com/a/53805896
tagged with: keras
tagged with: lambda
upvote count: 6
linked to: http://stackoverflow.com/q/47066635
answer count: 3
has title: Keras Lambda layer and variables : "TypeError: can't pickle _thread.lock objects"
has answer: http://stackoverflow.com/a/55235934
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/49325552
has body: You could do this without a regex using zip() in a list comprehension: &gt;&gt;&gt; s = '552523' &gt;&gt;&gt; [a for a, b in zip(s, s[2:]) if a == b] ['5', '2']
answers question: http://stackoverflow.com/q/49325509
downvote count: 1
type: Answer
upvote count: 13
score: 12

http://stackoverflow.com/q/49331751
type: Question
has body: I have a csv file (say A.csv) with an index from 1980-01-01 to 2018-02-28 (increased by a day) and one data column (say everyday's stock price). I have another csv file (say B.csv) with an index from 1980-01 to 2018-02 (increased by a month) and one data column (say monthly trade balance). In such case, how do merge B.csv to A.csv (by maintaining daily index)? i.e., daily index + one column for daily stock price + another column for monthly trade balance (I need to expand monthly trade balance to daily trade balance by maintaining the same trade balance values for each days in a month).
has title: Pandas merging monthly data from one dataframe with daily data in another
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/49331813
accepted answer: http://stackoverflow.com/a/49331813
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85700925
type: QuestionComment
comment on: http://stackoverflow.com/q/49349079
score: 0
has text: Please add an example TSV file into your question and show what the resulting output file should look like.
type: Comment

http://stackoverflow.com/comment/85686626
has text: @TigerTV.ru Oh, in the while True? Does it conflict with the csv open function? And do you mind sharing your modified code so I can understand the difference you mentioned better?
comment on: http://stackoverflow.com/q/49342838
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49356645
accepted answer of: http://stackoverflow.com/q/49356592
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49356592
has body: That is not an error, it's just a deprecation warning (link). Use sheetnames instead of get_sheet_names(). import openpyxl wb = openpyxl.load_workbook('examples.xlsx') print(wb.sheetnames)
upvote count: 1

http://stackoverflow.com/comment/85789262
has text: Thank you for posting this, your answer did help me do more research as well as guide my own implementation(:
type: Comment
comment on: http://stackoverflow.com/a/49374973
score: 0
type: AnswerComment

http://stackoverflow.com/q/49332536
tagged with: python
has answer: http://stackoverflow.com/a/49332621
tagged with: regex
has answer: http://stackoverflow.com/a/49332646
has comment: http://stackoverflow.com/comment/85667030
has title: How to properly use placeholders in re module?
score: 0
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49332758
type: Question
has comment: http://stackoverflow.com/comment/85667014
has body: I had this simple code which uses python re module's placeholder.. (?P&lt;name&gt;...) My goal is to get the value(number) just before the "/" character. The value's length can range from 4 and so on... I have written this code below. import re s = "hello world 1234/book" x = r"^h.*(?P&lt;test&gt;[0-9].*)/.*$" y = re.search(x, s) print y.group('test') However it just returns: &gt;&gt;&gt; 4 My ideal result is: &gt;&gt;&gt; 1234 I would really appreciate any hint.

http://stackoverflow.com/a/49394996
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49394818
has body: Here's what it looks like with your small integers: &gt;&gt;&gt; hacked_immutable = ([1], [2]) &gt;&gt;&gt; hacked_immutable ([1], [2]) &gt;&gt;&gt; id(hacked_immutable) 139813228968072 &gt;&gt;&gt; id(hacked_immutable[0]) 139813228055688 &gt;&gt;&gt; id(hacked_immutable[0][0]) 139813227530592 &gt;&gt;&gt; id(hacked_immutable[1]) 139813228056008 &gt;&gt;&gt; id(hacked_immutable[1][0]) 139813227530624 &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; hacked_immutable[0][0] += 1 &gt;&gt;&gt; hacked_immutable ([2], [2]) &gt;&gt;&gt; id(hacked_immutable) 139813228968072 &gt;&gt;&gt; id(hacked_immutable[0]) 139813228055688 &gt;&gt;&gt; id(hacked_immutable[0][0]) 139813227530624 &gt;&gt;&gt; id(hacked_immutable[1]) 139813228056008 &gt;&gt;&gt; id(hacked_immutable[1][0]) 139813227530624 Note that there is only one, single 2 object. However, let's take a look with not-small integers: &gt;&gt;&gt; hacked_immutable = ([314159], [314160]) &gt;&gt;&gt; id(hacked_immutable) 139813228056200 &gt;&gt;&gt; id(hacked_immutable[0]) 139813228055688 &gt;&gt;&gt; id(hacked_immutable[0][0]) 139813228644176 &gt;&gt;&gt; id(hacked_immutable[1]) 139813228056008 &gt;&gt;&gt; id(hacked_immutable[1][0]) 139813228644528 &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; hacked_immutable[0][0] += 1 &gt;&gt;&gt; hacked_immutable ([314160], [314160]) &gt;&gt;&gt; id(hacked_immutable[0]) 139813228055688 &gt;&gt;&gt; id(hacked_immutable[0][0]) 139813229186864 &gt;&gt;&gt; id(hacked_immutable[1]) 139813228056008 &gt;&gt;&gt; id(hacked_immutable[1][0]) 139813228644528 The Python run-time system still creates a new integer object for the first element. 314160 exists in two places. This is from caching small integers, not from any property of the implementation of im/mutable objects.
type: Answer

http://stackoverflow.com/q/49316345
has comment: http://stackoverflow.com/comment/85637394
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85641128
tagged with: arrays
has comment: http://stackoverflow.com/comment/85634500
has title: unable to read IF in printing outputs
has comment: http://stackoverflow.com/comment/85634297
has comment: http://stackoverflow.com/comment/85634143
has body: For the following code, Python recommended me to use a.any. Now, according to my code what the outputs show is wrong. l is bigger than 1 but the out put is printing r instead of q=10. from numpy import * import numpy as np for i in range (1,3): r=np.random.uniform(0,3,i) x=np.random.uniform(0,9,i) h=np.random.uniform(0,1,i) l=r+x if (l&lt;1.0).any: q=r elif (l&gt;1.0).any: q=10 print("q= ",q,"l= ",l)
score: 0
tagged with: if-statement
has comment: http://stackoverflow.com/comment/85636860
has comment: http://stackoverflow.com/comment/85633950
has comment: http://stackoverflow.com/comment/85637779
tagged with: python
has comment: http://stackoverflow.com/comment/85636057
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49361503
tagged with: random

http://stackoverflow.com/a/49397259
downvote count: 0
has comment: http://stackoverflow.com/comment/85796392
answers question: http://stackoverflow.com/q/49397153
has comment: http://stackoverflow.com/comment/85796466
has comment: http://stackoverflow.com/comment/85796441
has comment: http://stackoverflow.com/comment/85798414
has comment: http://stackoverflow.com/comment/85796408
has comment: http://stackoverflow.com/comment/85796391
has comment: http://stackoverflow.com/comment/85796342
has comment: http://stackoverflow.com/comment/85796477
has comment: http://stackoverflow.com/comment/85796501
type: Answer
has comment: http://stackoverflow.com/comment/85815611
has comment: http://stackoverflow.com/comment/85796588
has comment: http://stackoverflow.com/comment/85798446
score: 3
accepted answer of: http://stackoverflow.com/q/49397153
has comment: http://stackoverflow.com/comment/85825877
has comment: http://stackoverflow.com/comment/85796353
upvote count: 3
has comment: http://stackoverflow.com/comment/85796511
has comment: http://stackoverflow.com/comment/85798176
has body: The way you test most things in Python is to try then and see whether you get an exception. That works fine for raise. If something isn't raisable, you will get a TypeError; otherwise, you will get what you raised (or an instance of what you raised). That will work for 2.6 (or even 2.3) just as well as 3.6. Strings as exceptions in 2.6 will be raisable; types that don't inherit from BaseException in 3.6 will be not raisable; etc.—you get the right result for everything. No need to check BaseException or handle old-style and new-style classes differently; just let raise do what it does. Of course we do need to special-case TypeError, because it'll land in the wrong place. But since we don't care about pre-2.4, there's no need for anything more complicated than an isinstance and issubclass test; there are no weird objects that can do anything other than return False anymore. The one tricky bit (which I initially got wrong; thanks to user2357112 for catching it) is that you have to do the isinstance test first, because if the object is a TypeError instance, issubclass will raise TypeError, so we need to short-circuit and return True without trying that. The other issue is handling any special exceptions that we don't want to accidentally capture, like KeyboardInterrupt and SystemError. But fortunately, these all go back to before 2.6. And both isinstance/issubclass and except clauses (as long as you don't care about capturing the exception value, which we don't) can take tuples with syntax that also works in 3.x. Since it's required that we return True for those cases, we need to test them before trying to raise them. But they're all BaseException subclasses, so we don't have to worry about classic classes or anything like that. So: def is_raisable(ex, exceptions_to_exclude=IGNORED_EXCEPTIONS): try: if isinstance(ex, TypeError) or issubclass(ex, TypeError): return True except TypeError: pass try: if isinstance(ex, exceptions_to_exclude) or issubclass(ex, exceptions_to_…
type: AcceptedAnswer

http://stackoverflow.com/q/49423324
type: AnsweredQuestion
tagged with: list
answer count: 1
downvote count: 1
has body: values/test/10/blueprint-0.png,2089.0,545.0,2100.0,546.0 values/test/10/blueprint-0.png,2112.0,545.0,2136.0,554.0 What I want to do is read a .txt file full of hundreds of values like the ones shared above, to create a dictionary who's key is the value of the first 2 numbers in it; my expected output: mydict = { '10-0': [[2089,545,2100,545,2100,546,2089,546], [2112,545,2136,545,2136,554,2112,554]], } to explain how we went from 4 numbers to 8 numbers let's see them as x1, y1, x2, y2 at first, and in the output they are combined as x1, y1, x2, y1, x2, y2, x1, y2 In the actual data I have hundreds of values so I will have different keys if the starting 2 elements are different. Let's say if the line in the .txt file starts with values/test/10/blueprint-1.png then the key is '10-1'. What I have tried: import re import itertools file_data = [re.findall('\d+', i.strip('\n')) for i in open('ground_truth')] print(file_data) final_data = [['{}-{}'.format(a, b), list(map(float, c))] for a, b, *c in file_data] new_data = {a: list(map(lambda x: x[-1], b)) for a, b in itertools.groupby(sorted(final_data, key=lambda x: x[0]), key=lambda x: x[0])} but instead I get ValueError: not enough values to unpack (expected at least 2, got 1) and I can't seem to fix my issue from a simple file with these 2 lines in it to the answer expected in mydict. Note that taking this line for example values/test/10/blueprint-0.png,2089.0,545.0,2100.0,546.0 we will find these numbers [10, 0, 2089, 0, 545, 0, 2100, 0, 546, 0] and the 0s in the elements 3, 5, 7 and 9 are irrelevant considering these numbers are in a list. These can be seen by printing file_data, as I did in the code above.
accepted answer: http://stackoverflow.com/a/49423432
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 5
tagged with: python
tagged with: dictionary
score: 4
has answer: http://stackoverflow.com/a/49423432
has title: How can I transform my data with numbers to a dictionary containing lists of lists?

http://stackoverflow.com/a/49422019
downvote count: 0
has body: I think need first convert to_datetime and then use dt.year and dt.month: df = pd.DataFrame({ 'Plan_Cancel_Date': ['2018-07-07','2019-03-05','2020-10-08'], 'Plan_Start_Date': ['2016-02-07','2017-01-05','2017-08-08'] }) #print (df) #if necessary convert to datetimes df.Plan_Start_Date = pd.to_datetime(df.Plan_Start_Date) df.Plan_Cancel_Date = pd.to_datetime(df.Plan_Cancel_Date) df['Lifetime'] = ((df.Plan_Cancel_Date.dt.year - df.Plan_Start_Date.dt.year)*12 + df.Plan_Cancel_Date.dt.month - df.Plan_Start_Date.dt.month) print (df) Plan_Cancel_Date Plan_Start_Date Lifetime 0 2018-07-07 2016-02-07 29 1 2019-03-05 2017-01-05 26 2 2020-10-08 2017-08-08 38
accepted answer of: http://stackoverflow.com/q/49421791
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49421791
type: AcceptedAnswer

http://stackoverflow.com/comment/85562833
has text: Can you show an actual example with `myList = ...` defined?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49279950
score: 1

http://stackoverflow.com/comment/85683764
comment on: http://stackoverflow.com/a/49341812
score: 0
type: AnswerComment
has text: @ArchivistG You might still need to clean your sentences (using regex, I've omitted this step for simplicity). There is nothing to list, just lemmatise words and write to your file.
type: Comment

http://stackoverflow.com/q/49333359
type: UnansweredQuestion
score: 0
tagged with: pywinauto
has comment: http://stackoverflow.com/comment/85669084
has title: pywinauto to control putty.exe
has body: How can I see the result of the 'msfconsole' command? app_Putty = Application().Start(cmd_line='putty -ssh user@10.10.10.10 ') app_Putty.top_window_().TypeKeys("password {ENTER}") time.sleep(5) command = 'msfconsole' app_Putty.top_window_().TypeKeys(command+"{ENTER}")
tagged with: python
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/85668791

http://stackoverflow.com/a/49399315
has body: If you have an aware datetime you can convert it to a unix epoch timestamp by subtracting a datetime at UTC epoch like: Code: import datetime as dt import pytz def aware_to_epoch(aware): # get a datetime that is equal to epoch in UTC utc_at_epoch = pytz.timezone('UTC').localize(dt.datetime(1970, 1, 1)) # return the number of seconds since epoch return (aware - utc_at_epoch).total_seconds() aware = dt.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')) print(aware_to_epoch(aware)) Results: 1521612302.341014
answers question: http://stackoverflow.com/q/49398493
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49398493

http://stackoverflow.com/comment/93822046
type: Comment
score: 0
type: AnswerComment
has text: @Primoz, `_output_shapes` is an attribute so it should be accessed like `shapes = node.attr['_output_shapes']` it gives another protobuf object that can be navigated down to integers like this: `shapes.list.shape[0].dim[0].size`. Probably there is more convenient way to access values, but I'm not aware of it.
comment on: http://stackoverflow.com/a/49422729

http://stackoverflow.com/a/68404113
type: Answer
has body: Adapted from @cs95's answer: a = pd.Series([-1, 2, 15, 3, 45, 5, 23, 0, 6, -4, -8, -5, 3, -9, -7, -36, -71, -2, 25, 47, -8]) def pos_neg_count(a): v = a.ge(0).ne(a.ge(0).shift()).cumsum() vals = v.groupby(v).count().values cols = ['pos', 'neg'] if a[0] &gt;= 0 else ['neg', 'pos'] try: result = pd.DataFrame(vals.reshape(-1, 2), columns=cols) except ValueError: vals = np.insert(vals, len(vals), 0) result = pd.DataFrame(vals.reshape(-1, 2), columns=cols) return result pos_neg_count(a) # neg pos # 0 1 8 # 1 3 1 # 2 5 2 # 3 1 0 I think, this would take care of cases where the array being reshaped has odd no. of elements.
score: 0
answers question: http://stackoverflow.com/q/49285232

http://stackoverflow.com/q/49313368
score: 0
has answer: http://stackoverflow.com/a/49313639
answer count: 1
tagged with: celery
type: Question
accepted answer: http://stackoverflow.com/a/49313639
has body: I have created a flask application to process GNSS data. There are certain functions which takes a lot of time to execute. Therefore i have integrated celery to perform those functions as Asynchronous tasks. First I have tested the app in localhost by adding message broker as rabbitmq app.config['CELERY_BROKER_URL']='amqp://localhost//' app.config['CELERY_RESULT_BACKEND']='db+postgresql://username:pssword@localhost/DBname' After fully tested the application in virtualenv I deployed It on heroku and added rabbitmq addon. Then I changed the app.config as follows. app.config['CELERY_BROKER_URL']='amqp://myUsername:Mypassowrd@small-fiver-23.bigwig.lshift.net:10123/FlGJwZfbz4TR' app.config['CELERY_RESULT_BACKEND']='db+postgres://myusername:Mypassword@ec2-54-163-246-193.compute-1.amazonaws.com:5432/dhcbl58v8ifst/MYDB' After changing the above I ran the celery worker celery -A app.celery worker --loglevel=info and get this error [2018-03-16 11:21:16,796: ERROR/MainProcess] consumer: Cannot connect to amqp://SHt1Xvhb:**@small-fiver-23.bigwig.lshift.net:10123/FlGJwZfbz4TR: timed out. How can I check whether my heroku addon is working from Rabbitmq management console
tagged with: python
has title: Cannot connect to rabbitmq message broker in flask-celery application
tagged with: rabbitmq
type: AnsweredQuestion

http://stackoverflow.com/comment/85670240
type: QuestionComment
has text: @SamuelMuiruri 1) I added from __future__ import absolute_import 2) I was running it from inside the t3 package. Came out of directory and ran python -m t3.run_tasks, which worked as expected.
score: 0
comment on: http://stackoverflow.com/q/49334159
type: Comment

http://stackoverflow.com/comment/85728497
type: AnswerComment
has text: I tried the code it gives the following error: ValueError: invalid literal for int() with base 10: '1 1.232'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49363716

http://stackoverflow.com/comment/137207754
type: QuestionComment
has text: I had a similar issue trying to do this on a Lambda via a ECR Image and it took me several days (including checking in this thread) to come to an easy answer here on stack overflow: https://stackoverflow.com/a/66594707/3460414 In particular, I implemented a fork of this repo that contains the all importand Dockerimage https://github.com/umihico/docker-selenium-lambda/ . I tried posting as an answer given it took me 5 days and a lot of wasted time scrolling around stackoverflow, but moderation does not allow links to similar answers. I genuinely hope it helps someone.
score: 0
comment on: http://stackoverflow.com/q/49323099
type: Comment

http://stackoverflow.com/q/49348613
tagged with: jira
type: Question
accepted answer: http://stackoverflow.com/a/49349115
has answer: http://stackoverflow.com/a/49349115
has title: Newly created issues (JIRA and python)
tagged with: python
has comment: http://stackoverflow.com/comment/85697780
has comment: http://stackoverflow.com/comment/85698631
type: AnsweredQuestion
score: 1
upvote count: 3
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85697075
has comment: http://stackoverflow.com/comment/85697102
has body: I am working on simple app that uses python to access Jira. I mange to get all the issues How to get the only newly created issues ? from jira import JIRA jira = JIRA(basic_auth=('username', 'password'), options={'server':'https://MY_JIRA.atlassian.net'}) got = 50 total = 0 while got==50: issues = jira.search_issues('project=JA', startAt = total) .... got = len(issues) total += got
has comment: http://stackoverflow.com/comment/85697500
favorite count: 0

http://stackoverflow.com/comment/85641354
score: 0
has text: @sciroccorics I need the whole number of `l` in a column and relevant `q` in another column. In addition I need to find minimum of `I` and its `q`
comment on: http://stackoverflow.com/q/49319204
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49429412
linked to: http://stackoverflow.com/q/23244418
has comment: http://stackoverflow.com/comment/85861138
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85862196
has body: When a script is invoked explicitly with python, the argv is mucked with so that argv[0] is the path to the script being run. This is the case if invoked as python foo/bar.py or even as python -m foo.bar. I need a way to recover the original argv (ie. the one received by python). Unfortunately, it's not as easy as prepending sys.executable to sys.argv because python foo/bar.py is different than python -m foo.bar (the implicit PYTHONPATH differs, which can be crucial depending on your module structure). More specifically in the cases of python foo/bar.py some other args and python -m foo.bar some other args, I'm looking to recover ['python', 'foo/bar.py', 'some', 'other', 'args'] and ['python', '-m', 'foo.bar', 'some', 'other', 'args'], respectively. I am aware of prior questions about this: how to get the ORIGINAL command line in python? with spaces, tabs, etc Full command line as it was typed But these seem to have a misunderstanding of how shells work and the answers reflect this. I am not interested in undoing the work of the shell (eg. evaluated shell vars and functions are fine), I just want to get at the original argv given to python. The only solution I've found is to use /proc/&lt;PID&gt;/cmdline: import os with open("/proc/{}/cmdline".format(os.getpid()), 'rb') as f: original_argv = f.read().split('\0')[:-1] This does work, but it is Linux-only (no OSX, and Windows support seems to require installing the wmi package). Fortunately for my current use case this restriction is fine. But, it would be nice to have a cleaner, cross platform approach. The fact that that /proc/&lt;PID&gt;/cmdline approach works gives me hope that python isn't execing before it runs the script (at least not the syscall exec, but maybe the exec builtin). I remember reading somewhere that all of this argument handling (ex. -m) is done in pure python, not C (this is confirmed by the fact that python -m this.does.not.exist will produce an exception that looks like it came from the runtim…
upvote count: 12
type: UnansweredQuestion
tagged with: command-line-arguments
tagged with: python
has title: Recovering original argv
has comment: http://stackoverflow.com/comment/85861754
has comment: http://stackoverflow.com/comment/85861578
has comment: http://stackoverflow.com/comment/85860972
has comment: http://stackoverflow.com/comment/85861855
has comment: http://stackoverflow.com/comment/85861911
linked to: http://stackoverflow.com/q/44862323
linked to: http://stackoverflow.com/q/667540
has answer: http://stackoverflow.com/a/49547858
linked to: http://stackoverflow.com/q/6184925
has comment: http://stackoverflow.com/comment/85862085
has comment: http://stackoverflow.com/comment/85861802
score: 12
has answer: http://stackoverflow.com/a/73929299
has comment: http://stackoverflow.com/comment/85861209
answer count: 3
linked to: http://stackoverflow.com/q/4867761
has comment: http://stackoverflow.com/comment/85860451
has comment: http://stackoverflow.com/comment/85860195
has comment: http://stackoverflow.com/comment/85861183
has answer: http://stackoverflow.com/a/49548274
has comment: http://stackoverflow.com/comment/85860295
linked to: http://stackoverflow.com/q/6600541
has comment: http://stackoverflow.com/comment/85860340
linked to: http://stackoverflow.com/q/28336431
has comment: http://stackoverflow.com/comment/85862608
downvote count: 0
has comment: http://stackoverflow.com/comment/85861526

http://stackoverflow.com/q/49349544
downvote count: 0
tagged with: python
favorite count: 0
tagged with: dijkstra
has title: Finding the shortest path in a cyclical graph using Dijkstra
score: 3
has comment: http://stackoverflow.com/comment/85706023
has comment: http://stackoverflow.com/comment/85745111
upvote count: 3
has comment: http://stackoverflow.com/comment/85702594
tagged with: graph-algorithm
has comment: http://stackoverflow.com/comment/85744995
type: Question
tagged with: python-3.x
has body: I have a cyclical directed graph. Below is the representation of the graph as a python dict graph = { 'A': {'B': 5, 'D': 5, 'E': 7 }, 'B': {'C': 4}, 'C': {'D': 8, 'E': 2}, 'D': {'C': 8, 'E': 6}, 'E': {'B': 3} } I have wrote a simple implementation of a Dijkstra's shortest path. Which seems to work for given two points. Below is my implementation. def shortestpath(self, start, end, visited=[],distances={},predecessors={}): # initialize a big number maxint = 10000 if start==end: path=[] while end != None: path.append(end) end=predecessors.get(end, None) return distances[start], path[::-1] # detect if it's the first time through, set current distance to zero if not visited: distances[start]=0 # process neighbors as per algorithm, keep track of predecessors for neighbor in self.graph[start]: if neighbor not in visited: neighbordist = distances.get(neighbor,maxint) tentativedist = distances[start] + self.graph[start][neighbor] if tentativedist &lt; neighbordist: distances[neighbor] = tentativedist predecessors[neighbor]=start # neighbors processed, now mark the current node as visited visited.append(start) # finds the closest unvisited node to the start unvisiteds = dict((k, distances.get(k,maxint)) for k in self.graph if k not in visited) closestnode = min(unvisiteds, key=unvisiteds.get) # now we can take the closest node and recurse, making it current return self.shortestpath(closestnode,end,visited,distances,predecessors) now this simple implementation seems to work. For example if I do somthing like this shortestpath('A', 'C') it will give me the path and shortest weight (9, ['A', 'B', 'C']) in this case. However, whenever I shortestpath('B', 'B') the program will break. Now there is a shortest path from B to B since it is a cyclic graph the path is B-C-E-B. I just don't know how to check for that and modify the Dijktra's algorithm accordingly to have it check for cyclic cases like this one. Any suggestion is greatly appreciated. Thanks :)
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85789968
score: 1
type: Comment
type: QuestionComment
has text: @Chris [check the form errors](https://docs.djangoproject.com/en/2.0/ref/forms/api/#django.forms.Form.errors) to determine what the errors you have with the submitted form data.
comment on: http://stackoverflow.com/q/49393181

http://stackoverflow.com/comment/85593257
comment on: http://stackoverflow.com/a/49295381
type: Comment
has text: I think you are right. Now that I think about it, suggesting ternary operators to someone just picking up python might not have been a good call in the first place. Thanks for spotting it.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49338517
has title: Convert phone letters to phone numbers
has answer: http://stackoverflow.com/a/49338750
accepted answer: http://stackoverflow.com/a/49338722
score: -1
has answer: http://stackoverflow.com/a/49338722
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
downvote count: 2
upvote count: 1
tagged with: python
has body: My code below works to convert phone letters to phone numbers, but I didn't know if there was a better way to do this: def phone_letter_converter(self): if not self.isdigit(): number_upper = self.upper() new_number = "" for ch in number_upper: if ch == 'A' or ch == 'B' or ch == 'C': new_number += '2' elif ch == 'D' or ch == 'E' or ch == 'F': new_number += '3' elif ch == 'G' or ch == 'H' or ch == 'I': new_number += '4' elif ch == 'J' or ch == 'K' or ch == 'L': new_number += '5' elif ch == 'M' or ch == 'N' or ch == 'O': new_number += '6' elif ch == 'P' or ch == 'Q' or ch == 'R' or ch == 'S': new_number += '7' elif ch == 'T' or ch == 'U' or ch == 'V': new_number += '8' elif ch == 'W' or ch == 'X' or ch == 'Y' or ch == 'Z': new_number += '9' else: new_number += ch return new_number
possible better answer: http://stackoverflow.com/a/49338750
type: AnsweredQuestion

http://stackoverflow.com/comment/85780726
score: 0
type: AnswerComment
has text: @ClsForCookies Oh I see! Thank you! :)
type: Comment
comment on: http://stackoverflow.com/a/49389602

http://stackoverflow.com/comment/85562121
type: Comment
has text: Please show a [mcve]. We can't debug code that we cannot see. The final height of the scrollbar is a factor both of how the scrollbar is configured, and how it is added to the window.
score: 3
comment on: http://stackoverflow.com/q/49279580
type: QuestionComment

http://stackoverflow.com/comment/85739456
type: QuestionComment
has text: I just added the code
comment on: http://stackoverflow.com/q/49368318
score: 0
type: Comment

http://stackoverflow.com/q/49322597
tagged with: pandas-groupby
tagged with: pandas
score: 2
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
has body: Suppose we have such df (user may have multiple rows on the same date): df = pd.DataFrame({"user_id" : ["A"] * 5 + ["B"] * 5, "hour" : [10] * 10, "date" : ["2018-01-16", "2018-01-16","2018-01-18","2018-01-19","2018-02-16","2018-01-16", "2018-01-16","2018-01-18","2018-01-19","2018-02-16"], "amount" : [1] * 10}) df['date'] = pd.to_datetime(df['date']) Output: amount date hour user_id 0 1 2018-01-16 10 A 1 1 2018-01-16 10 A 2 1 2018-01-18 10 A 3 1 2018-01-19 10 A 4 1 2018-02-16 10 A 5 1 2018-01-16 10 B 6 1 2018-01-16 10 B 7 1 2018-01-18 10 B 8 1 2018-01-19 10 B 9 1 2018-02-16 10 B I want to get agg rolling stats for amount by each user_id and hour. Currently I did it like that: def get_rolling_stats(df, rolling_interval = 7) : index_cols = ['user_id', 'hour', 'date'] grp = df.groupby(by = ['user_id', 'hour'], as_index = True, group_keys = False).rolling(window='%sD'%rolling_interval, on = 'date') def agg_grp(grp, func): res = grp.agg({'amount' : func}) res = res.reset_index() res.drop_duplicates(index_cols, inplace = True, keep = 'last') res.rename(columns = {'amount' : "amount_" + func}, inplace = True) return res grp1 = agg_grp(grp, "mean") grp2 = agg_grp(grp, "count") grp = grp1.merge(grp2, on = index_cols) return grp So it outputs: user_id hour date amount_mean amount_count 0 A 10 2018-01-16 1.0 1.0 1 A 10 2018-01-18 1.0 3.0 2 A 10 2018-01-19 1.0 4.0 3 A 10 2018-02-16 1.0 1.0 4 B 10 2018-01-16 1.0 1.0 5 B 10 2018-01-18 1.0 3.0 6 B 10 2018-01-19 1.0 4.0 7 B 10 2018-02-16 1.0 1.0 But I want to exclude the current date from rolling window. So I want output like that: user_id hour date amount_mean amount_count 0 A 10 2018-01-16 nan 0.0 1 A 10 2018-01-18 1.0 2.0 2 A 10 2018-01-19 1.0 3.0 3 A 10 2018-02-16 nan 0.0 4 B 10 2018-01-16 nan 0.0 5 B 10 2018-01-18 1.0 2.0 6 B 10 2018-01-19 1.0 3.0 7 B 10 2018-02-16 nan 0.0 I've read that rolling method has arg closed. But if I use it - it raises error : ValueError: closed only implemented for datetimelike and offset based windo…
type: Question
has title: Pandas groupby by rolling open window
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49323941

http://stackoverflow.com/comment/85719812
type: Comment
type: QuestionComment
has text: Well done, it really depends on how the DLL was created, There are cases where 1, 4 or 8 are used.
comment on: http://stackoverflow.com/q/49320099
score: 0

http://stackoverflow.com/a/49388885
score: 1
answers question: http://stackoverflow.com/q/49382504
downvote count: 0
has body: Quoting from this pull request https://github.com/numpy/numpy/pull/10670 I think the original rationale for this change was to allow the following change to not break this code from numpy import * def my_func(n): return sum(i*i for i in range(n)) Reasons to deprecate it: sum is the only function to do this, even though any and all also shadow builtins It's not documented It's not consistent with np.array(generator).sum(), which already fails.
type: Answer
upvote count: 1

http://stackoverflow.com/q/49348869
has answer: http://stackoverflow.com/a/49349029
tagged with: python
has answer: http://stackoverflow.com/a/49349867
has answer: http://stackoverflow.com/a/49348950
score: 0
answer count: 3
tagged with: pandas
has title: How to get a single value from pandas dataframe?
has body: I am new to pandas. I am trying to get a particular value based on the value in another column. However the output is coming as a list of values rather than just one value, while I can try and make do with this, I would like to understand what I am doing wrong. `prem_ce' OpenInterest Volume BidPrice OfferPrice StrikePrice prem_ratio 6 8,296,000 3,934 4.15 4.25 100.0 3.0 7 10,872,000 3,981 1.60 1.65 110.0 2.0 8 8,692,000 1,302 0.70 0.75 120.0 2.0 9 5,524,000 1,118 0.35 0.40 130.0 1.0 10 3,108,000 110 0.20 0.25 140.0 1.0 11 2,692,000 55 0.10 0.15 150.0 1.0 12 1,908,000 4 0.05 0.10 160.0 0.0 13 1,176,000 8 0.05 0.10 170.0 0.0 14 920,000 6 0.05 0.10 180.0 0.0 15 192,000 1 0.05 0.10 190.0 0.0 16 336,000 7 0.05 0.10 200.0 0.0 17 168,000 2 0.00 0.10 210.0 0.0 18 24,000 2 0.00 0.10 220.0 0.0 19 0 0 0.00 0.10 230.0 0.0 20 0 0 0.00 0.15 240.0 NaN I tried the following: for ratio in prem_ce['prem_ratio']: if ratio &gt;= 2 and ratio is not 'NaN': x = int(ratio) ratio_row = prem_ce.index[prem_ce['prem_ratio'] == ratio] ce_strike_sell = prem_ce['StrikePrice'][ratio_row].values print(ce_strike_sell) I get the following output: [ 100.] [ 110. 120.] [ 110. 120.] I have made the prem_ratio by prem_ce['prem_ratio'] = prem_ce['BidPrice'] / prem_ce['OfferPrice'].shift(-1) Now I am trying to put both the StrikePrice used to calculate prem_ratio into variables. I can't understand why I am getting a list and that the first list has only one value while the other two have 2 values. Edit-- I expected the program to loop through each row and give me 1 value when condition was satisfied. i.e. 100.0, 110.0, 120.0 in 3 loops. I expected the output to be, 1st loop: ce_strike_sell = 100.0 2nd loop: ce_strike_sell = 110.0 3rd loop: ce_strike_sell = 120.0 I am not sure if there is a way to do this as I am still very new to pandas
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49296620
has comment: http://stackoverflow.com/comment/85595158
tagged with: python
accepted answer: http://stackoverflow.com/a/49306067
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49306067
has body: I have a problem in my Selenium project (python language). In one of the test classes, he writes to the variable the address of the page where he is currently located. I need this variable to be invoked in a different class - the page has to be opened. class EditFirst(): def testFirst(self): url2 = self.browser.current_url and second class, when I should open url2 class EditSecond(): def testSecond(self): #uri2 The second class does not see the variable. Classes are in separate files.
has title: python selenium open browser in other file
has comment: http://stackoverflow.com/comment/85611394
score: 1
has comment: http://stackoverflow.com/comment/85604478
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
tagged with: webdriver
favorite count: 0
type: Question

http://stackoverflow.com/a/49451456
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49382370
type: Answer
score: 2
upvote count: 2
has body: The easiest way would be to create an additional job for the aggregation and adding a dependency on the job array. #SBATCH --dependendy=afterany=&lt;jobid of the job array&gt; See https://slurm.schedmd.com/job_array.html and https://slurm.schedmd.com/sbatch.html
answers question: http://stackoverflow.com/q/49382370
type: AcceptedAnswer

http://stackoverflow.com/a/49381309
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: You can set lowercase attribute to False count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu,lowercase=False) Here The Attributes of CountVectorizer CountVectorizer(analyzer=u'word', binary=False, charset=None, charset_error=None, decode_error=u'strict', dtype=&lt;type 'numpy.int64'&gt;, encoding=u'utf-8', input=u'content', lowercase=True, max_df=1.0, max_features=None, min_df=0, ngram_range=(1, 1), preprocessor=None, stop_words=None, strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b', tokenizer=None, vocabulary=None)
answers question: http://stackoverflow.com/q/49380998

http://stackoverflow.com/comment/85725598
has text: Why did you tag this question as a Python question? Do you have some Python code you are having a problem with?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49362328
type: Comment

http://stackoverflow.com/q/49345744
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85691300
answer count: 1
has title: Checking every character to the string via function! but I could not get "s", "i", "e" string true when I check
has comment: http://stackoverflow.com/comment/85691321
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49345794
has comment: http://stackoverflow.com/comment/85691285
has answer: http://stackoverflow.com/a/49345794
has body: def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' # Your code here if aStr == "": return False; elif len(aStr) == 1 and aStr!= char: return False; elif len(aStr) == 1 and aStr == char: return True; elif aStr[(len(aStr)//2)] == char: return True; else: # if char &lt; aStr[(len(aStr)//2)]: return isIn(char, aStr[:(len(aStr)//2)]) return isIn(char, aStr[(len(aStr)//2):]) print(isIn("s", "frostbite"))
tagged with: python

http://stackoverflow.com/comment/85626620
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49312403
has text: Search for "python read file" and "python get max number"
type: Comment

http://stackoverflow.com/a/49440066
answers question: http://stackoverflow.com/q/49439828
has comment: http://stackoverflow.com/comment/85885304
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/85901396
downvote count: 0
upvote count: 1
has body: Tried this one and it worked: [a-zA-Z-]*arch[a-zA-Z']*

http://stackoverflow.com/comment/85632494
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49314500
type: QuestionComment
has text: okay.. checking that

http://stackoverflow.com/comment/85690039
type: QuestionComment
has text: @RahulBharadwaj - even you change to `username` and `password` the error is the same
comment on: http://stackoverflow.com/q/49344994
score: 0
type: Comment

http://stackoverflow.com/comment/85848242
has text: EDITED: I tried using X_transformed.loc[[0]] rather than using X
score: 0
comment on: http://stackoverflow.com/a/49422506
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85797484
has text: Read then, those concepts are the ones that are being used @ indicates the inheritance. and children widgets that are not heirs or inherit, are being used as a composition. One thing is the children of the class inheritance and the other is the children by the hierarchy.
comment on: http://stackoverflow.com/a/49377086
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49408319
downvote count: 0
has comment: http://stackoverflow.com/comment/85824532
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Solution with np.insert should be very fast, but is necessary create index with non numeric columns first: #create index from `Name` column df = df.set_index('Name') #add first value to index idx = np.insert(df.index, 0, 'Total') #add columns and index parameters to DataFrame contructor and last reset index df = pd.DataFrame(np.insert(df.values, 0, df.sum(), axis=0), columns=df.columns, index=idx).reset_index() print (df) Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6
type: Answer
accepted answer of: http://stackoverflow.com/q/49407096
answers question: http://stackoverflow.com/q/49407096

http://stackoverflow.com/a/50458567
has body: in order to export object detection models I use the export_inference_graph.py code in research/object-detection. Here's an example of running the code: python3 export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path path/to/model.config \ --trained_checkpoint_prefix path/to/model.ckpt-CHECKPOINTNUMBER \ --output_directory path/to/frozen_inference_graph Then I use the created frozen_inference_graph.pb with a C++ code that is essentially the same as label_image with little modifications to run for a detection model rather than a classification one.
score: 0
has comment: http://stackoverflow.com/comment/89106741
answers question: http://stackoverflow.com/q/49283031
type: Answer

http://stackoverflow.com/a/49349263
answers question: http://stackoverflow.com/q/49349200
has body: Your second condition is subset of first condition, so if will never go in that block. Change the order of conditions, it will work for i in range(0, 101): if i % 5 == 0 and i % 3 == 0 and i != 0: print '{} FiveThree'.format(i) elif i % 3 == 0 and i != 0: print '{} Three'.format(i) else: print "{}".format(i)
type: Answer
score: 0

http://stackoverflow.com/comment/85746325
type: AnswerComment
has text: @ManishSaraswat I pulled out every trick I had to get you option 3
comment on: http://stackoverflow.com/a/49372271
score: 0
type: Comment

http://stackoverflow.com/q/49327312
has comment: http://stackoverflow.com/comment/85656862
score: 1
has answer: http://stackoverflow.com/a/49327632
answer count: 1
has comment: http://stackoverflow.com/comment/85656762
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85656564
type: UnansweredQuestion
tagged with: python
has title: Graphing, 2 conditions for x
has body: I am using pandas to plot a few graphs of data from a file regarding the Supreme Court, I need to create a bar graph that shows the the number of votes in each "direction" for each justice. There is a column in the file titled "direction" that consists of either 1 or 2 to indicate that the position was conservative or liberal. I would like the graph to show up with each value on the x axis as "(justiceName), 1.0" "(same justiceName),2.0" and the y value is total for each of those values, how do I go about setting two conditions for the x-axis? scdb_subset.groupby('justiceName')['direction'].nunique().plot(kind='bar') I currently have this written and this is what it returns
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/49425985
has title: Inserting NULL as default in SQLAlchemy?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85859566
downvote count: 0
score: 16
upvote count: 16
has body: I have the following column in SQLAlchemy: name = Column(String(32), nullable=False) I want that if no value is passed onto an insertion, it should enter a default value of either completely blank or if not possible, then default as NULL. Should I define the column as : name = Column(String(32), nullable=False, default=NULL) Because in python NULL object is actually None Any suggestions?
has answer: http://stackoverflow.com/a/49430457
has answer: http://stackoverflow.com/a/75755900
tagged with: models
tagged with: python
tagged with: sqlalchemy
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/85660875
has text: As I am in a virtualenv, so when I call pip, itis already linked with pip3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49327879
score: 0

http://stackoverflow.com/comment/85665777
type: QuestionComment
score: 0
has text: IDLE will display it only if you run code in interactive mode. Just run the source code directly.
type: Comment
comment on: http://stackoverflow.com/q/49331852

http://stackoverflow.com/comment/132632555
comment on: http://stackoverflow.com/a/49304912
type: Comment
type: AnswerComment
has text: Best used with the package `pillow` ;-)
score: 0

http://stackoverflow.com/a/49412832
answers question: http://stackoverflow.com/q/49320913
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49320913
type: Answer
has body: Thanks to all for their solutions. They were correct as per the example I posted, but my actual task was a bit more generic. I found a generic solution in Python, as the above mentioned response did not work perfectly(may be because my knowledge in bash is limited). My generic solution using Pythons is as follows: import re import os testFolder = "./Path" #Usage: Remove duplicate function block from one or more .txt files available in testFolder #Iterating through the list of all the files available for testFilePath in os.listdir(testFolder): if testFilePath.endswith(".txt"): #Extracting path for each text file found inputFile = open (testFolder + "/" + testFilePath, "r") #Creating a reduced folder in the output path outputPath = testFolder + "/Reduced" if not os.path.exists(outputPath): os.makedirs(outputPath) outputFile = open (outputPath + "/" + testFilePath, "w") #Reading all the content into a single string fileContent = inputFile.read() #Pattern for matching a Function block. Pattern matches multiple lines pattern = re.compile('(^FUNC(.|\n)*?\n})*',re.M) # Creating a list of function blocks funcList = pattern.findall(fileContent) #Creating a list of unique function block, thus removing duplicate data uniqueFuncList = set(funcList) #Writing each Function block to the output file separeted by a new line for element in uniqueFuncList: outputFile.write(element[0] + "\n\n") inputFile.close() outputFile.close()

http://stackoverflow.com/comment/86117549
comment on: http://stackoverflow.com/q/49395904
has text: I saw so all the answers in it and I guess there was a pretty solution to this problem. You just need to loop over whole list checking if the next element is greater than current one and if next is lesser than that element needs to be removed. But even after that element being found you will need to check if any other element does same. It will run in O(n). No?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49427254
score: 3
has body: As suggested by @mikey, you can use np.unique, as below: import numpy as np my_list = ['CatA', 'CatB', 'CatC', 'CatA', 'CatA', 'CatC'] res = np.unique(my_list, return_inverse=True)[1] Result: [0 1 2 0 0 2]
type: Answer
accepted answer of: http://stackoverflow.com/q/49426546
upvote count: 3
answers question: http://stackoverflow.com/q/49426546
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85855555

http://stackoverflow.com/comment/85793935
type: Comment
has text: The shape of im_flat seems wrong, TF expects you to give it [?,1,418400,3], and you are giving it [1,418400,3]. The ? dimension allows you to train with multiple data points in a single go. You could just put your existing instance in a singleton list to fix this issue.
comment on: http://stackoverflow.com/q/49372585
score: 0
type: QuestionComment

http://stackoverflow.com/q/49282683
tagged with: loops
has body: I have an array containing strings. I have a text file. I want to loop through the text file line by line. And check whether each element of my array is present or not. (they must be whole words and not substrings) I am stuck because my script only checks for the presence of the first array element. However, I would like it to return results with each array element and a note as to whether this array element is present in the entire file or not. #!/usr/bin/python with open("/home/all_genera.txt") as file: generaA=[] for line in file: line=line.strip('\n') generaA.append(line) with open("/home/config/config2.cnf") as config_file: counter = 0 for line in config_file: line=line.strip('\n') for part in line .split(): if generaA[counter]in part: print (generaA[counter], "is -----&gt; PRESENT") else: continue counter += 1
type: AnsweredQuestion
score: 0
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49283686
has title: How do you check for the presence of a string in a text file based on the elements of an array?
has answer: http://stackoverflow.com/a/49283686
possible better answer: http://stackoverflow.com/a/49282769
type: Question
has answer: http://stackoverflow.com/a/49282769
answer count: 3
has answer: http://stackoverflow.com/a/49283038
tagged with: python

http://stackoverflow.com/comment/85565467
comment on: http://stackoverflow.com/a/49281306
type: AnswerComment
score: 0
has text: @uwain12345 Well, yeah, I suppose the OP’s only real requirement is “I want to meet my teacher’s strange requirements so I pass the assignment”. But I think it’s worth pointing out why, outside this assignment, you would actually want to use a `while` here.
type: Comment

http://stackoverflow.com/comment/86219586
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49502189
has text: I don't understand why you link to a question that was about reading in 1000's of small files, when you have just 1 large file. So you're saying your solution is to pre-process your one large file into a bunch of smaller ones (with a separate thread), then later run code as in the one you linked, to read those small files back in? That's more complicated because it's more lines of code to debug and now you need to keep two copies of your data, and adds a lot of extra disk overhead so you won't get your overall answer as fast. Also, I didn't suggest move the Pool() ahead, not sure that helps.

http://stackoverflow.com/a/73064277
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49289187
downvote count: 0
has comment: http://stackoverflow.com/comment/133814117
has body: if you are interested in the best precision according to max_depth you can look at this L = [] for i in range(1,n): dtree = DecisionTreeClassifier(max_depth=i) dtree.fit(X_train,y_train) y_pred = dtree.predict(X_test) L.append(round(accuracy_score(y_test,y_pred),4)) print(L.index(max(L))) print(max(L)) 'n' it's up to you to look at the value you don't want to exceed to avoid overfitting I advise you not to increase this value too much*
type: Answer

http://stackoverflow.com/comment/85615072
has text: Seems to be telling you the type of `Fore` itself: `type(Fore)` --> `colorama.ansi.AnsiFore`
comment on: http://stackoverflow.com/a/49306346
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85738374
type: Comment
comment on: http://stackoverflow.com/q/49368705
score: 0
type: QuestionComment
has text: @MosesKoledoye Thanks for the info

http://stackoverflow.com/q/49435907
has comment: http://stackoverflow.com/comment/85873877
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49436069
has title: I am trying to filter directories out of a list using regex
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49436069
has body: I have many directories and subdirectories in a list format and i am trying to pull out only the ones I need. I start with an array of xml files in the directory repo/bob/ebb. I would like to specifically locate the files in the following directories: where a dash means any character: repo/bob/ebb/bb--/nr/dl - - - - - - - - - - -/ [every xml inside this directory recursively] repo/bob/ebb/bb----/nr/dl - - - - - - - - - - -/ [every xml inside this directory recursively] I have come up with the following code in order to do this but I am recieving a syntax error. I have started learing Regex yesterday and am probably not grasping something but this is my attempt. Any help would be greatly appreciated. Thank you in advance. import glob import re import os x = glob.glob('/repo/bob/ebb/*/nr/*/*/*/*/test_suites.xml') print x for y in x: if re.search(r'/repo/bob/ebb/bb\+{2,4}/nr/dl\.+',y) print y ps I realize I am using glob and can use the '+' but I would like to incorporate the regex into this. I am getting "invalid syntax" at the search line so I am doing something wrong just unsure of what it is. thanks again
type: Question
has comment: http://stackoverflow.com/comment/85874065
upvote count: 0
score: -2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85874148

http://stackoverflow.com/comment/85582319
has text: @StephenRauch oh! im not. im writing 1 million row at a time.
score: 0
comment on: http://stackoverflow.com/q/49289451
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86031213
type: QuestionComment
has text: Be clear and elaborate you question
comment on: http://stackoverflow.com/q/49361952
type: Comment
score: 0

http://stackoverflow.com/comment/85732362
type: AnswerComment
comment on: http://stackoverflow.com/a/49365187
score: 0
has text: Actually already did something like this, although I liked your way better so I'm stealing it! I still need to do the merging part though, rather than generating more rows at this point.
type: Comment

http://stackoverflow.com/q/49394609
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85791194
has body: I have a csv document pulled from a database with random carriage returns. My data (very small subset) looks like this: Data in Excel I have 4 columns. The names attribute in column 1 always start with NA. As shown in the picture, the second row start with NAalbert, but then the three next column values for this row is outputted in the next line. The same with the third name NAander, the address is correctly placed, but the next two row values are then placed in the next row. How can I delete the seemingly random carriage returns in my csv, making the data fit the correct columns? Thanks!
has comment: http://stackoverflow.com/comment/85815497
score: 0
has title: Remove and reorder csv with random carriage returns python
tagged with: http://stackoverflow.com/tag/csv
tagged with: carriage-return
tagged with: python
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85879153
answer count: 0

http://stackoverflow.com/comment/85617352
type: AnswerComment
comment on: http://stackoverflow.com/a/49289549
score: 0
type: Comment
has text: thanks a lot for this! I appreciate the time you spent looking into this

http://stackoverflow.com/comment/85611394
type: QuestionComment
has text: The two tests are separate. In the first test I test whether a given function correctly edits the form, I change the data. In the second test, he tries to delete the form. It is removed, but for certainty I want to call the address after deletion, to check if this element is present. I do not have access to the database.
comment on: http://stackoverflow.com/q/49296620
score: 0
type: Comment

google-api
tags question: http://stackoverflow.com/q/49374112
tag name: google-api
tags question: http://stackoverflow.com/q/49351659
tags question: http://stackoverflow.com/q/49355731
tags question: http://stackoverflow.com/q/49331054
tags question: http://stackoverflow.com/q/49359001
tags question: http://stackoverflow.com/q/49344274
tags question: http://stackoverflow.com/q/49383479
type: Tag
tags question: http://stackoverflow.com/q/49313123
tags question: http://stackoverflow.com/q/49409512

http://stackoverflow.com/a/49346280
type: Answer
has comment: http://stackoverflow.com/comment/85692646
answers question: http://stackoverflow.com/q/49346246
score: 1
has body: You need to align dimensions correctly X[:, y[0] == 0] The first : specifies to grab everything in the first dimension. Using the y[0] == 0 in the second slot specifies that we are indexing the second dimension.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49411908
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
tagged with: datetime
tagged with: python
has body: I have the following df: date time 2018-01-01 00:00:00 7:30:33 2017-01-01 00:00:00 7:30:33 I want to create a datetime column that should look like this: 2018-01-01 7:30:33 2017-01-01 7:30:33 To do this I use the following code: df["datetime"] = pd.to_datetime(df['date'].apply(str)+' '+df['time']) It works the majority of the time. However, in some parts of my df (I dont know which parts), I get the following error: ValueError: hour must be in 0..23 What am I doing wrong and how can I fix this?
upvote count: 4
has title: Combine date and time; ValueError: hour must be in 0..23
accepted answer: http://stackoverflow.com/a/49411939
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49411939
score: 4

http://stackoverflow.com/q/49300516
upvote count: 1
accepted answer: http://stackoverflow.com/a/49300697
has title: Remove contents of an array from a column in pandas
favorite count: 0
has answer: http://stackoverflow.com/a/49300697
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49300573
has body: I'm trying to remove the contents of an array positions = ['CF','ST','RW','LW','CB','RB','LB','CM','CAM','CDM','RM','LM','RWB','LWB'] from the column Name in my dataframe with football players.Sample of this dataframe below. Player dataframe Can anyone help me remove these strings, I have tried str.replace and it won't work, Thanks
has comment: http://stackoverflow.com/comment/85605656
tagged with: pandas
has answer: http://stackoverflow.com/a/49300573
score: 1
has comment: http://stackoverflow.com/comment/85603050
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49301234
answer count: 4
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/85605825
has answer: http://stackoverflow.com/a/49300732
has comment: http://stackoverflow.com/comment/85605181
downvote count: 0

http://stackoverflow.com/comment/85634959
has text: That is great. Seems like my solution was pretty bad. I now incorporated your solution into mine. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/49306501
score: 1
type: Comment

http://stackoverflow.com/comment/85759562
type: Comment
has text: Yoiu have improper indentation of a block after 'for line in f:'
comment on: http://stackoverflow.com/q/49379254
score: 1
type: QuestionComment

http://stackoverflow.com/q/49434055
favorite count: 0
type: Question
tagged with: longest-substring
has comment: http://stackoverflow.com/comment/86126047
has body: Finding a common substring has been answered in many questions, i.e. given a list of strings find the (typically longest or largest number of words) substring that is common to all of them. See here: Longest common substring from more than two strings - Python My question is, how does one go about finding the longest modal substring in a list of strings? The important stipulation here is that this substring does not necessarily have to appear in all strings in the list. There is a little bit of art to the science here because the obvious tradeoff is between 1) how many strings do you want the substring to appear in? and 2) how long do you want the substring to be? To fix ideas, lets just assume that we want the desired substring to have three words (in case of a tie here, take the longest string, followed by first instance). So given the list, mylist = ["hey how's it going?", "I'm fine thanks.", "Did you get that thing?", "Of course I got that thing, that's why I asked you: how's it going?"] The desired output is, "how's it going" If the stipulation was instead two words long then the desired output would be, "that thing" Since "that thing" is a longer string than, "how's it" or "it going" The above answers in code are the modal substrings of three and two words long, respectively. EDIT: Since there is a bounty on this I will be a little more specific with what a modal sub-string is. Modal substring: For a given length of words in the substring (this is needed to uniquely identify the modal substring), the modal substring is the substring that is common to the largest number of strings in the list. If there is a tie (i.e. for a given length of three words in the substring there are two candidate substrings that both appear in 80% of the strings) then the substring with the longest character length should be used. If there is a still a tie after that (which should be very unlikely but is good to account for), then just take the first one or choose randomly. A good an…
linked to: http://stackoverflow.com/q/2892931
has title: Finding *modal* substring of a list of strings in python
has comment: http://stackoverflow.com/comment/86125656
tagged with: python
linked to: http://stackoverflow.com/q/1546226
has comment: http://stackoverflow.com/comment/86128120
has comment: http://stackoverflow.com/comment/113435083
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/49560223
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/49560223
answer count: 1
tagged with: string
downvote count: 1

http://stackoverflow.com/a/49411106
type: Answer
score: 0
has body: When an element from a list is deleted, the index's shift down one. An index is just an element located in a list. if you have a list of 1,2,3,4,5 and you delete list[3] then you now have 1,2,3,5 and now list[3] == 5
answers question: http://stackoverflow.com/q/49410978

http://stackoverflow.com/comment/85658446
comment on: http://stackoverflow.com/q/49328229
has text: You may find [my answer](https://stackoverflow.com/a/48692740/5858851) to a similar question useful. Also related: [this](https://datascience.stackexchange.com/questions/12321/difference-between-fit-and-fit-transform-in-scikit-learn-models) and [this](https://stackoverflow.com/questions/23838056/what-is-the-difference-between-transform-and-fit-transform-in-sklearn).
score: 1
type: Comment
type: QuestionComment

where-clause
tags question: http://stackoverflow.com/q/49416666
tags question: http://stackoverflow.com/q/49322418
tag name: where-clause
type: Tag

http://stackoverflow.com/comment/85772277
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49385544
type: Comment
has text: Thank you, now I am getting other error, but I can get through it on my own.

http://stackoverflow.com/q/49287971
score: 0
has comment: http://stackoverflow.com/comment/85579137
answer count: 1
has title: Sending emails to subgroups/supergroups - Nested dictionaries?
has body: I have the file with following records. This represents group'name:emailadd' Group1: it@group.foobar.com, Group1: it@group.foobar.com Group2: man@foobar.com, Group2: man@foobar.com Group3: xyz@foobar.com, test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com Group_test: iu@foobar.com, gvgrp: in@foobar.com, rsgrp: ij@foobar.com, dev: mp@foobar.com, rs: uru@foobar.com Assume very first field:email is supergrpup and other is nested groups that means Supegroups: Group1: it@group.foobar.com Group2: man@foobar.com Group3: xyz@foobar.com Group_test: iu@foobar.com Subgroups: Group1: it@group.foobar.com Group2: man@foobar.com test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com gvgrp: in@foobar.com, rsgrp: ij@foobar.com, dev: mp@foobar.com, rs: uru@foobar.com Now I want to send email to these groups to address ( separated by ':') But the email should be send to supergroups and its respective subgroups Like for line: Group3: xyz@foobar.com, test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com It should send email to supergroup email and all subgroups email address and use their groupnames in body of email. To: xyz@foobar.com, yz@foobar.com, new@foobar.com, new_g@foobar.com, ij@foobar.com, turu@foobar.com Body: Failed because of groupnames : Group3, test-grp, grp-t, test-contract, grp0, grp8 ---------&gt; These are all group associated with email specified in "To": I am not sure how I should do that? I was trying to create dictionaries but again its not working... It would be great help , if someone can have a look and help me out? Many thanks Bob
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49288253
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/85567327
has text: Have you already installed the tensorflow-gpu package? `pip install tensorflow-gpu`
comment on: http://stackoverflow.com/q/49282269
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85691916
score: 0
has text: Do not use wildcard imports
comment on: http://stackoverflow.com/q/49344541
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85640813
comment on: http://stackoverflow.com/q/49319494
type: Comment
has text: @MalloyDelacroix Also, in spec file that option is already activated:- `exe = EXE(pyz, a.scripts, exclude_binaries=True, name='pyqt_link6', debug=False, strip=False, upx=True, console=True )`
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85656673
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49327371
has text: you might have to say hello before sending mail. `smtpObj.ehlo()`
score: 0

http://stackoverflow.com/a/67422610
score: 0
has body: You should be using HTTPDigestAuth like this: session = requests.session() session.auth = requests.auth.HTTPDigestAuth(api_username, api_password) self.url = base_url + "pearson-rest/services/PublicPortalServiceJSON" try: self.client = zeep.Client( wsdl=self.url + "?wsdl", transport=zeep.transports.Transport(session=session), ) except requests.exceptions.ConnectionError: raise APIException(f"Could not connect to {base_url}.") except requests.exceptions.HTTPError: raise APIException( f"Incorrect api credentials ({api_username}, {api_password})." )
answers question: http://stackoverflow.com/q/49364403
type: Answer

http://stackoverflow.com/q/49317486
type: AnsweredQuestion
score: 1
has title: ThingsBoard IoT Gateway - Timestamp mapping timeseries in release 1.4.0
downvote count: 0
answer count: 1
has body: I've just upgraded my ThingsBoard IoT Gateway to the release 1.4.0, and I saw from the repository that it is now possible to map the published telemetry with client side timestamp. From my understanding this feature before was only possible by directly publishing to the ThingsBoard embedded MQTT broker, but not through the Gateway. From the repository I found that the previous mapping class (rep. branch 1.2) was the following: public class KVMapping { private String key; private DataTypeMapping type; private String value; } While the new release (rep. branch 1.4) has the following class: public class KVMapping { private String key; private DataTypeMapping type; private String value; private String ts; private String tsFormat; } From my understanding the timestamp feature (and the formatting style) have been added in the message mapping. My problem is that I'm unable to map the timestamp in the message I publish towards ThingsBoard. The platform still receives the correct key and value, but maps the data with the server side timestamp. This is a code snippet of the python code I use to publish the packet to the external MQTT broker, that shows how my json packet is structured: timeStamp = "1488273476000" data = { "about": "Devices", "properties": [ { "about": "Device1", "iotStateObservation": [ { "phenomenonTime": timeStamp, "value": "1" } ] }, { "about": "Device2", "iotStateObservation": [ { "phenomenonTime": timeStamp, "value": "174468" } ] }, { "about": "Device3", "iotStateObservation": [ { "phenomenonTime": timeStamp, "value": "12" } ] } ] } This is a snippet from my ThingsBoard IoT gateway mapping file (mqtt-config.json), here configured all the wanted mapping: { "topicFilter": "sensors", "converter": { "type": "json", "filterExpression": "$.properties[*]", "deviceNameJsonExpression": "${$.about}", "timeseries": [ { "type": "double", "ts": "${$.iotStateObservation[0].phenomenonTime}", "key": "${$.about}", "value": "${$.iotStateObservation[0].value}" } ] } } Is t…
has answer: http://stackoverflow.com/a/49727804
upvote count: 1
favorite count: 0
type: Question
tagged with: thingsboard
accepted answer: http://stackoverflow.com/a/49727804
tagged with: mqtt
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: iot

http://stackoverflow.com/comment/85688471
has text: Oh OK, so from reading the Python docs [here](https://docs.python.org/2/tutorial/classes.html), I saw that it would be referring to the instance, not the class (so `self.pi`).
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49344058

http://stackoverflow.com/q/49325855
score: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/85653512
has title: Python Selenium Testing. How can I extract the Auto Suggestions from search box on Google Home Page?
downvote count: 1
accepted answer: http://stackoverflow.com/a/49327804
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49327804
has body: I am doing some auto testing Python + Selenium.Is there any way to check suggestion box in google for example using selenium. Something like I would like to now that suggestion table is revealed when auto test put google in search bar.
tagged with: autocomplete
possible better answer: http://stackoverflow.com/a/49333769
tagged with: python
has answer: http://stackoverflow.com/a/49333769
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: selenium-chromedriver
answer count: 2
linked to: http://stackoverflow.com/q/53612605

http://stackoverflow.com/comment/85691374
has text: Ok. Wait a bit.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49345616
score: 0

http://stackoverflow.com/q/49350380
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49350638
accepted answer: http://stackoverflow.com/a/49350638
tagged with: python
tagged with: design-patterns
has title: Can someone explain me the Borg design pattern in python?
has body: I know this pattern is used in order to create multiple instances with the same state, but i really don't understand how it works. class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class Singleton(Borg): def __init__(self, **kwargs): Borg.__init__(self) self._shared_state.update(kwargs) def __str__(self): return str(self._shared_state) More specifically, what happens when in the Singleton init method I call Borg.init ?

http://stackoverflow.com/q/49371767
tagged with: django-admin
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85801314
has body: I want to pass songname list and songcount list to user update page at admin side. I've already extended admin templates. Just want to know how can I pass custom parameters to user update page. My codes below change_form.html: {% extends "admin/change_form.html" %} {% block after_related_objects %} {% endblock %} To generate list, I need request object.
tagged with: parameters
score: 3
upvote count: 3
downvote count: 0
answer count: 0
has title: pass parameter to change_form.html in user form of django admin site
linked to: http://stackoverflow.com/q/49386533
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85797492

pelican
tags question: http://stackoverflow.com/q/49419199
type: Tag
tag name: pelican

http://stackoverflow.com/comment/85773195
comment on: http://stackoverflow.com/a/49385217
score: 0
type: Comment
type: AnswerComment
has text: I checked with np.where() Everything seems to be 0

facebook
tags question: http://stackoverflow.com/q/49321748
tag name: facebook
type: Tag
tags question: http://stackoverflow.com/q/49436643
tags question: http://stackoverflow.com/q/49424199
tags question: http://stackoverflow.com/q/49346595
tags question: http://stackoverflow.com/q/49412667
tags question: http://stackoverflow.com/q/49281520

http://stackoverflow.com/q/49354949
has answer: http://stackoverflow.com/a/49354984
favorite count: 0
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/65030971
answer count: 5
has answer: http://stackoverflow.com/a/49354994
has answer: http://stackoverflow.com/a/49355176
possible better answer: http://stackoverflow.com/a/49354994
has title: Why does split() return more elements than split(" ") on same string?
tagged with: python
accepted answer: http://stackoverflow.com/a/49354984
has answer: http://stackoverflow.com/a/49355272
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/85710465
linked to: http://stackoverflow.com/q/18169006
has comment: http://stackoverflow.com/comment/85710248
has body: I am using split() and split(" ") on the same string. But why is split(" ") returning less number of elements than split()? I want to know in what specific input case this would happen.
tagged with: string
downvote count: 1

http://stackoverflow.com/comment/85591842
has text: Possible duplicate of [UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>](https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character)
comment on: http://stackoverflow.com/q/49294655
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51750380
answers question: http://stackoverflow.com/q/49315432
upvote count: 2
has comment: http://stackoverflow.com/comment/90494350
score: 2
has body: I believe there are multiple issues to be tackled here. Running eval() should be accompanied by a session. As suggested in In TensorFlow, what is the difference between Session.run() and Tensor.eval()?, .eval() expects a default session to be running which was not likely in your case earlier. So, the best option here was to precede the code with a session. From your comment, we can see that this is done. The variables in the hidden layers (i.e. weights/kernels) need to be initialized once the graph is complete. Hence, you might want to use something similar to this: init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) with tf.variable_scope("hidden_layer2", reuse=True): w = tf.get_variable("kernel") print(w.eval(session=sess))
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85708168
comment on: http://stackoverflow.com/a/49353831
type: Comment
type: AnswerComment
has text: Thank you ! but I don't understand what I need to adjust in my form ?
score: 0

http://stackoverflow.com/comment/85566267
has text: yes, but that still "collapses" all rows along that dimension instead of keeping N of them
comment on: http://stackoverflow.com/a/49281770
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49307218
type: Question
score: 2
has body: I'm working with Boto3 for AWS for my current project. I need to have a few different describe_images arguments for EC2 as optional and I can't use wildcard or empty inputs to get around having them in or not. I'm looking for a way for add arguments being passed as needed rather than having to do a number of if checks with slightly different content. For example, take the snippet below. I'd like for the Owners and ImageIds arguments to be dynamically added if they are provided upstream but not include them if they aren't. I haven't had any luck with Google yet so figured I would ask make a quick post. response = ec2.describe_images( ExecutableUsers=['all'], Filters=search_filters, Owners=['309956199498'], ImageIds=['ami-26ebbc5c'] ) Thanks
upvote count: 2
answer count: 1
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
has title: dynamically set what is included in function call
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49310125
linked to: http://stackoverflow.com/q/36901
tagged with: python
tagged with: boto3
accepted answer: http://stackoverflow.com/a/49310125

http://stackoverflow.com/comment/85839282
has text: The large dataset is similar to sample data given but in hundred K or million of rows. His question is how to re write the codes to run faster.
comment on: http://stackoverflow.com/q/49418656
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85767071
type: QuestionComment
has text: @Grasshopper: Nope does not work. I am using `elem.clear()` at different locations, but it does not change the outcome.
comment on: http://stackoverflow.com/q/49378987
type: Comment
score: 0

http://stackoverflow.com/q/49436433
answer count: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49436826
accepted answer: http://stackoverflow.com/a/49436826
has body: I'm trying to print each element individually, which is fine but also repeat each element based on position eg. "abcd" = A-Bb-Ccc-Dddd etc So my problems are making print statements print x times based off their position in the string. I've tried a few combinations using len and range but i often encounter errors because i'm using strings not ints. Should i be using len and range here? I'd prefer if you guys didn't post finished code, just basically how to go about that specific problem (if possible) so i can still go about figuring it out myself. user_string = input() def accum(s): for letter in s: pos = s[0] print(letter.title()) pos = s[0 + 1] accum(user_string)
has title: Print elements of string multiple times based on position
tagged with: python
has answer: http://stackoverflow.com/a/49436593
possible better answer: http://stackoverflow.com/a/49436593
upvote count: 2
type: AnsweredQuestion
score: 2

django-rest-framework
tags question: http://stackoverflow.com/q/49391072
tags question: http://stackoverflow.com/q/49326588
tags question: http://stackoverflow.com/q/49397352
tags question: http://stackoverflow.com/q/49426407
tags question: http://stackoverflow.com/q/49418578
tags question: http://stackoverflow.com/q/49324980
tags question: http://stackoverflow.com/q/49428770
tags question: http://stackoverflow.com/q/49414976
tags question: http://stackoverflow.com/q/49302994
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/49330581
tags question: http://stackoverflow.com/q/49313301
tags question: http://stackoverflow.com/q/49326259
tags question: http://stackoverflow.com/q/49286928
type: Tag
tags question: http://stackoverflow.com/q/49363049
tags question: http://stackoverflow.com/q/49291427
tags question: http://stackoverflow.com/q/49281234
tags question: http://stackoverflow.com/q/49354636
tags question: http://stackoverflow.com/q/49342882
tags question: http://stackoverflow.com/q/49287205
tags question: http://stackoverflow.com/q/49287209
tags question: http://stackoverflow.com/q/49368119
tags question: http://stackoverflow.com/q/49400426
tags question: http://stackoverflow.com/q/49327509

http://stackoverflow.com/q/49308441
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/57647628
score: 0
has comment: http://stackoverflow.com/comment/85649108
has title: Update Value dynamically using repeated Ajax calls from DJango template
answer count: 1
has comment: http://stackoverflow.com/comment/85619770
type: Question
linked to: http://stackoverflow.com/q/49170851
has body: I wanted to show my sound sensor readings from a django site (original code as posted in the link). Now as per the situation 2 of the accepted answer, I wanted to make a Javascript function which repeatedly calls the ajax_data function from views template. But it seems that no repeated calls are being made. And no update in reading reflects either. My django template till now: Noise measurement site Hello there Present noise level : {{noise_level}} dB (I have mentioned rest of the code in my previously asked question. I have read some of the answers on the platform but I'm not getting much results.) Update Sorry I made a mistake. I made slight changes in the code and posted output without that only. Now I have made the exact changes as in the previous part. But output is not sorted out yet. (Thanks to comment by CumminUp07)
has comment: http://stackoverflow.com/comment/85772185
tagged with: django
tagged with: python
tagged with: jquery
accepted answer: http://stackoverflow.com/a/57647628
tagged with: ajax

http://stackoverflow.com/q/49438207
tagged with: python
score: -1
has body: I am making a small python program for an address book and I'm trying to create an edit feature. def editEntry(): f = open("address_book.txt", "r") editList = [] for line in f: Name, Age, Address, City = line.split(',') editList.append([Name, Age, Address, City]) print (editList , "\n") choice = int(input("Which entry would you like to edit?" + "\n")) test = editList[choice - 1] del editList [choice] print (test) editEntryList = [] Name = input("What is the name?" + "\n") Age = input("What is the age?" + "\n") Address = input("What is the address?" + "\n") City = input("What is the city?" + "\n") editList.append(Name + ", ") editList.append(Age + ", ") editList.append(Address + ", ") editList.append(City + "\n") print(editList) print(editEntryList) I take in the data from a .txt file and you choose which entry you want to edit. I'm then trying to remove that one from the list so it can all be rewritten to the .txt file without having a duplicate entry. From what I can find I need to use del *List*[index] but because I take in a number and store it in a variable I can't use the variable (choice) for the index. How can I fix this? edit So in the .txt file I currently have 3 entries. The third of which needs editing. The code I have already reads the 3 lines into the list so Index 0 contains the first line Index 1 contains the second line Index 2 contains the third line Once the user inputs which entry they want to edit I want that index removing from the list so it only contains 2 and then later on in the program I simply take in the details the user wants to readd and rewrite the 3 entries into the .txt file again.
has comment: http://stackoverflow.com/comment/85878618
possible better answer: http://stackoverflow.com/a/49438420
has answer: http://stackoverflow.com/a/49438563
type: AnsweredQuestion
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85878427
has comment: http://stackoverflow.com/comment/85878569
downvote count: 1
has title: How to use an integer variable for remove from a list in Python
has comment: http://stackoverflow.com/comment/85878461
has answer: http://stackoverflow.com/a/49438420
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85878511
accepted answer: http://stackoverflow.com/a/49438563
has comment: http://stackoverflow.com/comment/85878523

http://stackoverflow.com/comment/85878922
type: QuestionComment
type: Comment
has text: akshay gave me the perfect answer
score: 0
comment on: http://stackoverflow.com/q/49420379

http://stackoverflow.com/comment/85781817
type: Comment
score: 0
has text: Can you post the content of phonebook1.txt?
type: AnswerComment
comment on: http://stackoverflow.com/a/49389815

http://stackoverflow.com/comment/85578290
score: 0
type: Comment
type: QuestionComment
has text: @DeliriousLettuce This would fail: `{"y": "yval", "v": "y1val", "a" : "aval"} although it satisfies the stated criterion.
comment on: http://stackoverflow.com/q/49287203

http://stackoverflow.com/comment/85812261
score: 0
has text: It is quite tricky. In that case the original seems to me more readable. I would use _ instead of dummy.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49405283

http://stackoverflow.com/a/49324184
has comment: http://stackoverflow.com/comment/85649771
answers question: http://stackoverflow.com/q/49323740
has body: This will be horribly inaccurate but it will get the size of a row and divide it against the size of the file. import sys import csv import os with open("example.csv", newline="") as f: reader = csv.reader(f) row1 = next(reader) _Size = sys.getsizeof(len("".join(row1))) print("Size of Line 1 &gt; ",_Size) print("Size of File &gt;",str(os.path.getsize("example.csv"))) print("Approx Lines &gt;",(os.path.getsize("example.csv") / _Size)) (Edit) If you change the last line to math.floor(os.path.getsize("example.csv") / _Size) It's actually quite accurate
score: 0
type: Answer

http://stackoverflow.com/comment/85571521
has text: Yes, the tensorflow model uses `tf.float32`.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49282636

pyqt4
tags question: http://stackoverflow.com/q/49412383
tags question: http://stackoverflow.com/q/49288674
tags question: http://stackoverflow.com/q/49306186
tags question: http://stackoverflow.com/q/49283580
tags question: http://stackoverflow.com/q/49371264
tags question: http://stackoverflow.com/q/49326873
tags question: http://stackoverflow.com/q/49377049
type: Tag
tags question: http://stackoverflow.com/q/49344925
tags question: http://stackoverflow.com/q/49405243
tags question: http://stackoverflow.com/q/49403423
tags question: http://stackoverflow.com/q/49385525
tags question: http://stackoverflow.com/q/49400752
tag name: pyqt4

http://stackoverflow.com/a/49353274
has comment: http://stackoverflow.com/comment/85706819
has comment: http://stackoverflow.com/comment/85707120
has body: As was pointed out in the comments, the fact that only one thread is running at one time is because the q.get() call is inside the loop. This blocks until a result is ready, which effectively serializes the threads. Moving that outside the loop will start all threads before checking the queue. However, this does not solve your problem of exiting other threads when one finishes. The "best" way to do this really depends on the structure of the node.mine() method. For example, if it's a loop of some kind, generally like: while True: relatively_fast_computation() then you can add a threading.Event() or similar to the mix, and have each thread check whether the event is set instead of just infinitely looping. while not event.is_set(): relatively_fast_computation() The main thread waits for a result on the queue, and when one is received, sets the event. The worker threads then notice this the next pass through the while loop and quit. This is probably the preferred way, as it allows the worker threads to properly exit, cleanup, close files, etc. The issue here is that this will not work well if each pass through the while loop is very slow, and it won't work at all if the functions inside there truly block, as in network I/O. In that case, there are workarounds, but none of them sound great or particularly applicable to your situation. Edit: And as was also pointed out in the comments, if the node.mine() method is a pure CPython function, then threading here is probably useless. The GIL will prevent CPU-bound code like hashing from running more than one thread anyway. Use multiprocessing.
has comment: http://stackoverflow.com/comment/85706949
upvote count: 1
has comment: http://stackoverflow.com/comment/85706983
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85707094
accepted answer of: http://stackoverflow.com/q/49352961
score: 1
has comment: http://stackoverflow.com/comment/85706851
type: Answer
answers question: http://stackoverflow.com/q/49352961

http://stackoverflow.com/comment/85708175
score: 0
has text: Im not convinced you even wrote this code. This code is written to take in arguments so everytime you run the script you need to specify the argument or have default arguments if they’re not defined. So if that’s not the behaviour you want re-write the code to work as an application you want it to. But my answe above answered your question on how to run the script !
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49353773

http://stackoverflow.com/comment/85723001
type: Comment
type: QuestionComment
score: 0
has text: OK. I'm afraid this isn't sufficient for me to understand *what exactly what you want* in your dataframe and in what format. Please rewrite your question so it is more clear. Good luck!
comment on: http://stackoverflow.com/q/49361201

http://stackoverflow.com/comment/85919401
type: AnswerComment
score: 0
has text: Thanks for this, I don't think I would've discovered this in at least 4 weeks. One tiny followup: Is it possible to set a current schema with a sessionpool?
comment on: http://stackoverflow.com/a/49452712
type: Comment

http://stackoverflow.com/q/49295824
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85593866
has body: I have a class defined in a file called recording.py that I'm trying to import into a Jupyter notebook. This class makes use of methods from numpy, which I import in both the notebook and the .py file as 'np'. When I try to call one of these methods, I get an error proclaiming that the name 'np' is not defined. I've tried both using 'import recording.py' (and appending the directory it's in to the path) and running '%run recording.py' in a cell, and I get the same error. What am I missing here? I can't think of anything else to try. EDIT for additional clarity: I have a file recording.py that defines a class: import numpy as np class Recording: --- some methods --- where methods from numpy are used in some of the class methods. In the same directory, I have a Jupyter notebook where I want to use this class. In this notebook, I have: import numpy as np import sys sys.path.append('path/to/file') import recording #or from recording import Recording r = recording.Recording(initialization arguments) r.method_that_uses_numpy() I have also tried replacing 'import recording' with '%run recording.py'. When I try to execute this, I get this error asserting that 'np' is not defined: /Documents/neuroscience/scratch/recording.py in remove_neuron(self, n) 41 42 def remove_neuron(self,n): ---&gt; 43 self.centroid = np.delete(self.centroid,n,1) 44 self.time = np.delete(self.time,n,1) 45 self.intRaw = np.delete(self.intRaw,n,1) NameError: name 'np' is not defined I have no idea why this is happening or how to fix it.
has comment: http://stackoverflow.com/comment/85593943
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85702865
tagged with: python
has comment: http://stackoverflow.com/comment/85848292
tagged with: jupyter-notebook
has title: How to import my own class that uses an imported module into jupyter notebook
answer count: 0
score: 1

http://stackoverflow.com/a/49418215
downvote count: 2
answers question: http://stackoverflow.com/q/49418144
type: Answer
has comment: http://stackoverflow.com/comment/85838577
has body: This is happening because python caches and reuses some immutable built-in objects, even if they're "stored" as different variables &gt;&gt;&gt; a = 1 &gt;&gt;&gt; id(a) 56188528L &gt;&gt;&gt; b = int(1) &gt;&gt;&gt; id(b) 56188528L Python didn't have to allocate any memory or instantiate a new object for the second variable. It's just reusing the immutable integer object that had already been created. If you had put your timing tests in different files and ran them separately, or if you had ran the int(1) test first, you would have seen different results.
score: -1
upvote count: 1

http://stackoverflow.com/comment/85692169
comment on: http://stackoverflow.com/q/49345411
score: 0
has text: Thanks a lot for the side notes. I changed my code according to your advice.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49419682
type: UnansweredQuestion
tagged with: time-complexity
has title: ID Allocator implementation in Python
downvote count: 0
has comment: http://stackoverflow.com/comment/85840979
favorite count: 0
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85840888
tagged with: python
has answer: http://stackoverflow.com/a/49420187
type: Question
score: 2
tagged with: python-3.x
answer count: 2
has body: In one of my recent interviews, I was asked to implement an ID allocator. Here is the problem: Implement an id allocator class that can allocate ids from the range 0~size-1. There are 2 methods for this class: alloc() - allocates a id that is not being used, returns it. release(id) - takes in an id that is being used, and make it available to be allocated. The followup requirement was basically to maintain a bit array to save space, however the runtime for both of the methods need to be better than linear. I was stuck on that followup, do you guys have any ideas? from bitarray import bitarray class id_allocator(): def __init__(self, size): self.ids = bitarray(size) # 0 is available, 1 is unavailable def alloc(self): for idx, _id in enumerate(self.ids): if not _id: self.ids[idx] = True return idx raise Exception('no ids available') def release(self, _id): if _id &gt; len(self.ids) or self.ids[_id] == True: raise Exception('invalid id') self.ids[_id] = False
upvote count: 2
has answer: http://stackoverflow.com/a/78857035

http://stackoverflow.com/q/49307581
answer count: 1
has title: Unable to specify partitioner in spark-mongo connector (Class not found Exception)
type: Question
type: UnansweredQuestion
tagged with: pyspark
has answer: http://stackoverflow.com/a/49307969
tagged with: python
has body: I am currently writing Pyspark_2.2.1 standalone applications with MongoDB_2.6 as the database, mongo-spark connector with version 2.2.1. While running spark application with spark-submit, I get below error: : java.lang.ClassNotFoundException: spark.mongodb.input.partitionerOptions.MongoPaginateBySizePartitioner I tried to mention while reading the data from MongoDB database. This is how my read looks like: users = spark.read.format("com.mongodb.spark.sql.DefaultSource") \ .option("uri" , "mongodb://127.0.0.1/xyz.abc") \ .option("partitioner", "spark.mongodb.input.partitionerOptions.MongoPaginateBySizePartitioner ") \ .load() I have followed following link to specify partitioner: https://docs.mongodb.com/spark-connector/master/configuration/. Here even DefaultPartitioner does not work. I get the same error. Any help would be appreciated. Thanks
tagged with: runtime-error
score: 0
tagged with: mongodb
tagged with: apache-spark

http://stackoverflow.com/a/49332758
has body: First, your problem has nothing at all to do with placeholders or named groups; you're doing that part just fine. To verify that, try capturing every piece as an unnamed group and printing out what you get: &gt;&gt;&gt; s = "hello world 1234/book" &gt;&gt;&gt; x = r"(^h.*)([0-9].*)(/.*$)" &gt;&gt;&gt; y = re.search(x, s) &gt;&gt;&gt; print(y.groups()) ('hello world 123', '4', '/book') See? You're getting the exact same '4' for the group you care about. Printing out all the groups is usually a helpful test of what's going on. For an even better test, use one of the many online regex debuggers, which can highlight the matches and explain them to you. For example, regex101 shows (via coloring) that the ^h.* is matching hello world 123 even without changing your regex to make it more debuggable. Anyway, the problem with your existing regex is that the first .* will match as much as possible while allowing the rest of the pattern to work—which means it'll match 'hello world 123', as you can see above, instead of just 'hello world ', as you want. If you want to toggle the greediness of a pattern, put a ? on the end: &gt;&gt;&gt; s = "hello world 1234/book" &gt;&gt;&gt; x = r"(^h.*?)([0-9].*)(/.*$)" &gt;&gt;&gt; y = re.search(x, s) &gt;&gt;&gt; print(y.groups()) ('hello world ', '1234', '/book') And now you can remove the groups you don't want and restore the name to the one you do want.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49332536

http://stackoverflow.com/comment/85707732
type: QuestionComment
comment on: http://stackoverflow.com/q/49352249
type: Comment
has text: The code you posted does not give that error.
score: 1

http://stackoverflow.com/comment/85686047
type: Comment
score: 0
type: AnswerComment
has text: Thanks, forgot about that. Ill change it.
comment on: http://stackoverflow.com/a/49342560

http://stackoverflow.com/comment/85621462
comment on: http://stackoverflow.com/q/49308879
score: 0
type: Comment
has text: honestly, I don't know. :-( let me do some research and see if I can directly populate the db with these values instead of having extra steps. thanks
type: QuestionComment

http://stackoverflow.com/comment/85823068
score: 0
has text: @COLDSPEED this gives "Key Error: 'D' "
type: Comment
comment on: http://stackoverflow.com/q/49410596
type: QuestionComment

http://stackoverflow.com/q/49438074
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85878203
has title: Getting LineEdit.text() from another imported file
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85878401
has comment: http://stackoverflow.com/comment/85893675
type: Question
has comment: http://stackoverflow.com/comment/85878276
accepted answer: http://stackoverflow.com/a/50042301
upvote count: 0
tagged with: pyqt
has answer: http://stackoverflow.com/a/50042301
answer count: 1
has body: I'm using python2.7 with pyqt 4.10 and I have two py files the first one called Warehouse.py that contains class Ui_mainWindow(object): and in it there is a function def setupUi(self, mainWindow): inside of it there is the creation of the widget lineEdit now in the 2nd file, I need to call the text within this widget, I've used this code: import Warehouse user1 = Ui_mainWindow.setupUi().lineEdit.text() So, it returns me this error : Traceback (most recent call last): File "G:\Python\townoftech-warehouse\item_entry.py", line 109, in item_in user1 = Ui_mainWindow.setupUi().lineEdit.text() NameError: global name 'Ui_mainWindow' is not defined
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/49326310
has comment: http://stackoverflow.com/comment/103183145
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/103160506
accepted answer of: http://stackoverflow.com/q/49313650
has comment: http://stackoverflow.com/comment/109147759
has comment: http://stackoverflow.com/comment/103137312
has body: The call Bidirectional(LSTM(128, return_sequences=True, return_state=True))(input) returns 5 tensors: The entire sequence of hidden states, by default it'll be the concatenation of forward and backward states. The last hidden state h for the forward LSTM The last cell state c for the forward LSTM The last hidden state h for the backward LSTM The last cell state c for the backward LSTM The line you've posted would raise an error since you want to unpack the returned value into just three variables (lstm, state_h, state_c). To correct it, simply unpack the returned value into 5 variables. If you want to merge the states, you can concatenate the forward and backward states with Concatenate layers. lstm, forward_h, forward_c, backward_h, backward_c = Bidirectional(LSTM(128, return_sequences=True, return_state=True))(input) state_h = Concatenate()([forward_h, backward_h]) state_c = Concatenate()([forward_c, backward_c])
answers question: http://stackoverflow.com/q/49313650
type: AcceptedAnswer
score: 30
upvote count: 30

http://stackoverflow.com/a/49506903
has comment: http://stackoverflow.com/comment/86212252
has comment: http://stackoverflow.com/comment/86219343
has comment: http://stackoverflow.com/comment/86212236
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49429368
has body: GENERAL ANSWER ABOUT MEMORY WITH MULTIPROCESSING You asked: "What is causing so much memory to be allocated". The answer relies on two parts. First, as you already noticed, each multiprocessing worker gets it's own copy of the data (quoted from here), so you should chunk large arguments. Or for large files, read them in a little bit at a time, if possible. By default the workers of the pool are real Python processes forked using the multiprocessing module of the Python standard library when n_jobs != 1. The arguments passed as input to the Parallel call are serialized and reallocated in the memory of each worker process. This can be problematic for large arguments as they will be reallocated n_jobs times by the workers. Second, if you're trying to reclaim memory, you need to understand that python works differently than other languages, and you are relying on del to release the memory when it doesn't. I don't know if it's best, but in my own code, I've overcome this be reassigning the variable to a None or empty object. FOR YOUR SPECIFIC EXAMPLE - MINIMAL CODE EDITING As long as you can fit your large data in memory twice, I think you can do what you are trying to do by just changing a single line. I've written very similar code and it worked for me when I reassigned the variable (vice call del or any kind of garbage collect). If this doesn't work, you may need to follow the suggestions above and use disk I/O: #### earlier code all the same # clear memory by reassignment (not del or gc) gen_matrix_df = {} '''Now, pipe each dataframe from the list using map.Pool() ''' p = Pool(3) # number of pool to run at once; default at 1 result = p.map(matrix_to_vcf, list(gen_matrix_df_list.values())) #del gen_matrix_df_list # I suspect you don't even need this, memory will free when the pool is closed p.close() p.join() #### later code all the same FOR YOUR SPECIFIC EXAMPLE - OPTIMAL MEMORY USAGE As long as you can fit your large data in memory once, and you have some idea of ho…
has comment: http://stackoverflow.com/comment/86174985
has comment: http://stackoverflow.com/comment/86185669
downvote count: 0

http://stackoverflow.com/comment/85588989
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49293102
has text: "prints wrong output"...You haven't said what is correct and incorrect output.

http://stackoverflow.com/comment/85714126
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49347548
type: Comment
has text: weird I ran your code didn't have any problems. https://gist.github.com/vedantshetty/7f9300a0fce2b5f099a34c5a64cc126a

http://stackoverflow.com/comment/85843578
type: QuestionComment
score: 0
has text: @YukaLangbuana So why wouldn't Matt be grouped with the other QBs instead of or in addition to being grouped with the other WSU students?
comment on: http://stackoverflow.com/q/49399471
type: Comment

http://stackoverflow.com/comment/85622016
has text: This is definitely a dup; it's come up three times in the last week. (It didn't used to come up this often… Wonder what's changed?) Anyone know where the canonical answer is?
comment on: http://stackoverflow.com/q/49309972
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86693086
has text: @StefanCrain sorry, first time. Fixed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49358590
score: 0

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/49366548
tags question: http://stackoverflow.com/q/49359687
tags question: http://stackoverflow.com/q/49362245
tags question: http://stackoverflow.com/q/49431565
tags question: http://stackoverflow.com/q/49431421
tags question: http://stackoverflow.com/q/49405766
tags question: http://stackoverflow.com/q/49415480
tags question: http://stackoverflow.com/q/49292114
tags question: http://stackoverflow.com/q/49282724
tags question: http://stackoverflow.com/q/49427867
tags question: http://stackoverflow.com/q/49413769
tags question: http://stackoverflow.com/q/49310725
tags question: http://stackoverflow.com/q/49403315
tags question: http://stackoverflow.com/q/49385363
tags question: http://stackoverflow.com/q/49391821
tag name: json
tags question: http://stackoverflow.com/q/49374091
tags question: http://stackoverflow.com/q/49285819
tags question: http://stackoverflow.com/q/49373825
tags question: http://stackoverflow.com/q/49288724
tags question: http://stackoverflow.com/q/49390075
tags question: http://stackoverflow.com/q/49410425
tags question: http://stackoverflow.com/q/49391072
tags question: http://stackoverflow.com/q/49331307
tags question: http://stackoverflow.com/q/49299470
tags question: http://stackoverflow.com/q/49309138
tags question: http://stackoverflow.com/q/49342139
tags question: http://stackoverflow.com/q/49435728
tags question: http://stackoverflow.com/q/49429709
tags question: http://stackoverflow.com/q/49324013
tags question: http://stackoverflow.com/q/49302604
tags question: http://stackoverflow.com/q/49350739
tags question: http://stackoverflow.com/q/49396558
tags question: http://stackoverflow.com/q/49351496
tags question: http://stackoverflow.com/q/49428308
tags question: http://stackoverflow.com/q/49310278
tags question: http://stackoverflow.com/q/49388141
tags question: http://stackoverflow.com/q/49317885
tags question: http://stackoverflow.com/q/49311281
tags question: http://stackoverflow.com/q/49344495
tags question: http://stackoverflow.com/q/49317486
tags question: http://stackoverflow.com/q/49355984
tags question: http://stackoverflow.com/q/49379532
tags question: http://stackoverflow.com/q/49437057
tags question: http://stackoverflow.com/q/49418234
tags question: http://stackoverflow.com/q/49411263
tags question: http://stackoverflow.com/q/49284203
tags question: http://stackoverflow.com/q/49344723
tags question: http://stackoverflow.com/q/49418376
tags question: http://stackoverflow.com/q/49361068
tags question: http://stackoverflow.com/q/49324838
tags question: http://stackoverflow.com/q/49425632
tags question: http://stackoverflow.com/q/49410886
type: Tag
tags question: http://stackoverflow.com/q/49281370
tags question: http://stackoverflow.com/q/49293306
tags question: http://stackoverflow.com/q/49302127
tags question: http://stackoverflow.com/q/49307030
tags question: http://stackoverflow.com/q/49331602
tags question: http://stackoverflow.com/q/49310497
tags question: http://stackoverflow.com/q/49409035
tags question: http://stackoverflow.com/q/49423548
tags question: http://stackoverflow.com/q/49299808
tags question: http://stackoverflow.com/q/49354262
tags question: http://stackoverflow.com/q/49391892
tags question: http://stackoverflow.com/q/49417400
tags question: http://stackoverflow.com/q/49356218
tags question: http://stackoverflow.com/q/49308665
tags question: http://stackoverflow.com/q/49288285
tags question: http://stackoverflow.com/q/49410712
tags question: http://stackoverflow.com/q/49372413
tags question: http://stackoverflow.com/q/49438907
tags question: http://stackoverflow.com/q/49371868
tags question: http://stackoverflow.com/q/49357682
tags question: http://stackoverflow.com/q/49313125

http://stackoverflow.com/a/49372478
type: Answer
score: 1
downvote count: 0
has body: Consider storing your data in lists, instead of individual variables. notifs = [1, 2, 3] persons = ['a', 'b', 'c'] Initialise a diagonal 2D array using np.diag, and pass it to pd.DataFrame: pd.DataFrame( np.diag(notifs), index=persons, columns=np.arange(1, len(notifs) + 1) ).add_prefix('notification') notification1 notification2 notification3 a 1 0 0 b 0 2 0 c 0 0 3
upvote count: 1
answers question: http://stackoverflow.com/q/49372435

http://stackoverflow.com/q/49375467
tagged with: python
has comment: http://stackoverflow.com/comment/85752061
has comment: http://stackoverflow.com/comment/85752139
has comment: http://stackoverflow.com/comment/85752231
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 3
score: -3
has body: I'm trying to do a calculation in the following code: def traffic_intensity(count): """Number of cars passing by""" int(count) if count &lt; 5000: level = "Very Low" elif 5000 &lt;= count &lt; 10000: level = "Low" elif 10000 &lt;= count &lt; 18000: level = "Moderate" elif count &gt;= 18000: level = "High" return level def number_of_busy_days(counts): """Busy days based on traffic flow""" daily_counts = 0 for count in counts: if traffic_intensity(level) == "Moderate" or "High": daily_counts = daily_counts + 1 return daily_counts counts = [18000, 10000, 500, 9999, 12000] print(number_of_busy_days(counts)) What I'm trying to achieve is to use the traffic_intensity function to calculate the number of busy days - a busy day is defined as having more than the "Moderate" amount of traffic given in the traffic_intensity function. I've tried a lot of different ways but I'm running out of ideas at this point. The problem I'm encountering is that it doesn't find the level variable form the first function. I get the following error: if traffic_intensity(level) == "Moderate" or "High": NameError: name 'level' is not defined Is anyone able to help me? Thanks! ^_^
has comment: http://stackoverflow.com/comment/85752081
has comment: http://stackoverflow.com/comment/85752163
favorite count: 0
type: Question
has title: Forwarding variables between functions
has answer: http://stackoverflow.com/a/49375535
has comment: http://stackoverflow.com/comment/85752164

http://stackoverflow.com/q/49314988
tagged with: scikit-learn
answer count: 1
has body: I am trying to learn scikit but when I am trying to run this simple example then I am getting the below error. The error also says Reshape your data either using array.reshape(-1, 1) ValueError: Expected 2D array, got 1D array instead: but I am not show where do I implement it. Below is my code from sklearn.linear_model import LinearRegression # Training data X = [[6], [8], [10], [14],[18]] y = [[7], [9], [13], [17.5], [18]] # Create and fit the model model = LinearRegression() model.fit(X, y) print 'A 12" pizza should cost: $%.2f' % model.predict([12])[0] Below is the complete error - ValueErrorTraceback (most recent call last) &lt;ipython-input-4-20775a37bc05&gt; in &lt;module&gt;() 6 model = LinearRegression() 7 model.fit(X, y) ----&gt; 8 print 'A 12" pizza should cost: $%.2f' % model.predict([12])[0] /home/atif/anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.pyc in predict(self, X) 254 Returns predicted values. 255 """ --&gt; 256 return self._decision_function(X) 257 258 _preprocess_data = staticmethod(_preprocess_data) /home/atif/anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.pyc in _decision_function(self, X) 237 check_is_fitted(self, "coef_") 238 --&gt; 239 X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) 240 return safe_sparse_dot(X, self.coef_.T, 241 dense_output=True) + self.intercept_ /home/atif/anaconda2/lib/python2.7/site-packages/sklearn/utils/validation.pyc in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 439 "Reshape your data either using array.reshape(-1, 1) if " 440 "your data has a single feature or array.reshape(1, -1) " --&gt; 441 "if it contains a single sample.".format(array)) 442 array = np.atleast_2d(array) 443 # To ensure that array flags are maintained ValueError: Expected 2D array, got 1D array instead: array=[12]. Reshape your data either using array.reshape(-1, 1) if your data has a s…
type: Question
linked to: http://stackoverflow.com/q/41972375
has comment: http://stackoverflow.com/comment/85631388
tagged with: python
has comment: http://stackoverflow.com/comment/85631538
has title: I am getting ValueError: Expected 2D array, got 1D array instead
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49315441
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49315441

http://stackoverflow.com/comment/85686164
has text: Work perfectly for me -- placed it through vigorous testing (i.e. a `for` loop generating 1000 random strings) and it worked every time.
type: Comment
comment on: http://stackoverflow.com/q/49342926
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85595479
comment on: http://stackoverflow.com/q/49296799
score: 0
type: Comment
has text: Thanks Graipher. I'm not entirely sure what that means. Do you mean something like I need to change the values in the list? Could you show me how to do that?
type: QuestionComment

http://stackoverflow.com/q/49380572
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/125340833
answer count: 8
has comment: http://stackoverflow.com/comment/125336449
has answer: http://stackoverflow.com/a/62698425
has answer: http://stackoverflow.com/a/60281933
has comment: http://stackoverflow.com/comment/114766025
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61399118
has answer: http://stackoverflow.com/a/51213556
tagged with: python
tagged with: pathlib
has body: I was converting some old Python code to use pathlib instead of os.path for most path-related operations, but I ended up with the following problem: I needed to add another extension to a path that already had an extension (not replace it). With os.path, since we are merely manipulating strings, the solution was to add the extension with string operations: newpath = path + '.res' It doesn't work with pathlib.Path because it doesn't allow concatenation of arbitrary characters. The closest I could find was the following: newpath = path.with_suffix(path.suffix + '.res') It looks like a workaround because it still uses string addition in the end. And it has a new pitfall because I forgot at first to handle the case where there are already several extensions and you want to add a new one, leading to the following code to get back the old behaviour: newpath = path.with_suffix(''.join(path.suffixes) + '.res') Now it doesn't feel terse nor clean since it uses more and more string operations to achieve the old behaviour instead of pure path operations. The fact that Path.suffixes exists means that the library's developers considered the case where a file can have multiple extensions, yet I couldn't find a way to simply add a new extension to a path. Is there a more idiomatic way that I have missed to achieve the same behaviour? EDIT: actually path.with_suffix(path.suffix + '.res') is enough to handle the case where there are already several file extensions, even though it wasn't immeditely obvious to me.
downvote count: 1
has answer: http://stackoverflow.com/a/79244153
has answer: http://stackoverflow.com/a/67486254
has comment: http://stackoverflow.com/comment/114765746
has comment: http://stackoverflow.com/comment/93081390
has answer: http://stackoverflow.com/a/53092299
score: 128
has answer: http://stackoverflow.com/a/53116529
has comment: http://stackoverflow.com/comment/100140298
has comment: http://stackoverflow.com/comment/114753081
upvote count: 129
has comment: http://stackoverflow.com/comment/114758526
has title: Adding another suffix to a path that already has a suffix with pathlib
favorite count: 0
type: Question

http://stackoverflow.com/a/49364963
downvote count: 0
has body: I installed Ubuntu 16.04.4 as a fresh VM, and only did an sudo apt-get update/sudo apt-get upgrade And then did the following: sudo apt install python3-pip sudo apt install libfbclient2 mkdir fdb-experiment cd fdb-experiment pip3 install fdb nano connect.py With connect.py: import fdb # 172.26.69.161 is my Windows machine with Firebird con = fdb.connect(dsn='172.26.69.161:d:/data/db/testdatabase.fdb', user='sysdba', password='masterkey') cur = con.cursor() cur.execute("select * from rdb$database") print(cur.fetchall()) Then: python3 connect.py Output: [(None, 225, None, 'ISO8859_1 ')] I did have to restart my VM in between because of some networking problems to the Windows host OS (which is running the Firebird server I used). I can only reproduce your problem if I perform sudo apt remove libfbclient2. In other words, I can't reproduce your problem. The only thing I can think of is that maybe you're using an older version of fdb (I'm using 1.8) which locates the client library in a different way (but as your stacktrace has the same line numbers I see if I remove libfbclient2, that is likely not the case). You might want to try if running sudo ldconfig fixes the problem, this will rebuild the cache of shared libraries. If that doesn't work, then check if cat /etc/ld.so.conf.d/* lists /usr/lib/x86_64-linux-gnu (if it doesn't, then I'm not entirely sure what would be the correct course of action to fix that).
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49360384

http://stackoverflow.com/comment/85691746
type: QuestionComment
comment on: http://stackoverflow.com/q/49345950
score: 0
has text: Have you installed MySQLdb? pip install mysqlclient
type: Comment

http://stackoverflow.com/a/49590670
score: 4
has comment: http://stackoverflow.com/comment/123583132
answers question: http://stackoverflow.com/q/49311795
has comment: http://stackoverflow.com/comment/86254710
downvote count: 0
has comment: http://stackoverflow.com/comment/86252065
has comment: http://stackoverflow.com/comment/101864889
has body: You can find my fork of pyhelm with examples and Python3 support. git clone git@github.com:andriisoldatenko/pyhelm.git cd pyhelm &amp;&amp; python setup.py install How to use Pyhelm First you need repo_url and chart name to download chart from pyhelm.repo import from_repo chart_path = chart_versions = from_repo('https://kubernetes-charts.storage.googleapis.com/', 'mariadb') print(chart_path) "/tmp/pyhelm-kibwtj8d/mongodb" Now you can see that chart folder of mongodb:: In [3]: ls -la /tmp/pyhelm-kibwtj8d/mongodb total 40 drwxr-xr-x 7 andrii wheel 224 Mar 21 17:26 ./ drwx------ 3 andrii wheel 96 Mar 21 17:26 ../ -rwxr-xr-x 1 andrii wheel 5 Jan 1 1970 .helmignore* -rwxr-xr-x 1 andrii wheel 261 Jan 1 1970 Chart.yaml* -rwxr-xr-x 1 andrii wheel 4394 Jan 1 1970 README.md* drwxr-xr-x 8 andrii wheel 256 Mar 21 17:26 templates/ Next step to build ChartBuilder instance to manipulate with Tiller:: from pyhelm.chartbuilder import ChartBuilder chart = ChartBuilder({'name': 'mongodb', 'source': {'type': 'directory', 'location': '/tmp/pyhelm-kibwtj8d/mongodb'}}) # than we can get chart meta data etc In [9]: chart.get_metadata() Out[9]: name: "mongodb" version: "0.4.0" description: "Chart for MongoDB" Install chart:: from pyhelm.chartbuilder import ChartBuilder from pyhelm.tiller import Tiller chart = ChartBuilder({'name': 'mongodb', 'source': {'type': 'directory', 'location': '/tmp/pyhelm-kibwtj8d/mongodb'}}) chart.install_release(chart.get_helm_chart(), dry_run=False, namespace='default') Out[9]: release { name: "fallacious-bronco" info { status { code: 6 } first_deployed { seconds: 1521647335 nanos: 746785000 } last_deployed { seconds: 1521647335 nanos: 746785000 } Description: "Dry run complete" } chart {.... }
has comment: http://stackoverflow.com/comment/86215050
type: Answer
has comment: http://stackoverflow.com/comment/101866405
upvote count: 4

http://stackoverflow.com/comment/85693303
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49319880
has text: @xyres but the problem is that you will not have a limit on the number of threads, and the reason to use ThreadPoolExecutor is to limit the number of threads.

http://stackoverflow.com/a/49378585
has comment: http://stackoverflow.com/comment/85757950
has body: In order to print the reverse order of what your program prints, change your i &lt; j to i &gt; j and j &lt; i to i &lt; j. Do the same for your numList[i] &gt; numList[j]. Your code will now print something like: List before shuffling: [26, 52, -58, 48, -91, -53, -20, -7, 78, -74, 10, -8, 29, -57, 31, 80, -76, -48, 45, -59, -46, -23, 33, -64, -89] List after shuffling: [-91, -89, -76, -74, -64, -59, -58, -57, -53, -46, -48, -23, -20, -8, -7, 10, 26, 29, 31, 33, 45, 48, 52, 78, 80]
has comment: http://stackoverflow.com/comment/85758188
score: 0
has comment: http://stackoverflow.com/comment/85757894
answers question: http://stackoverflow.com/q/49377933
type: Answer

http://stackoverflow.com/comment/85729150
type: QuestionComment
has text: @jezrael alright, i think i should delete my question then, I thought there might be a single line than can execute this without creating copies and copying columns
comment on: http://stackoverflow.com/q/49363931
score: 0
type: Comment

http://stackoverflow.com/q/49280302
accepted answer: http://stackoverflow.com/a/49280594
tagged with: python
tagged with: noaa
favorite count: 0
type: Question
upvote count: 2
has body: API: https://www.ncdc.noaa.gov/cdo-web/webservices/v2 Parameters: CITY:US270013 specifies Minneapolis, MN datatypeid=TOBS specifies that I want the observed temperature Python Code url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&amp;locationid=CITY:US270013&amp;startdate=2016-05-01&amp;enddate=2016-05-31&amp;limit=1000&amp;datatypeid=TOBS' response = requests.get(url, headers = headers) response = response.json() stationData = pd.DataFrame(response['results']) print(stationData.sort_values(by='station').to_string(index=False)) Results: attributes datatype date station value ,,7,2400 TOBS 2016-05-01T00:00:00 GHCND:USC00211448 89 ,,7,2400 TOBS 2016-05-14T00:00:00 GHCND:USC00211448 6 ,,7,2400 TOBS 2016-05-07T00:00:00 GHCND:USC00211448 61 ,,7,2400 TOBS 2016-05-16T00:00:00 GHCND:USC00211448 106 ,,7,2400 TOBS 2016-05-26T00:00:00 GHCND:USC00211448 172 ,,7,2400 TOBS 2016-05-28T00:00:00 GHCND:USC00211448 161 ,,7,2400 TOBS 2016-05-17T00:00:00 GHCND:USC00211448 50 ,,7,2400 TOBS 2016-05-06T00:00:00 GHCND:USC00211448 178 According to that table, May 6th 2015 had an observed temperature of 178 degrees in Minneapolis. This is clearly wrong but there is little documentation on their website. Does their TOBS follow a different scale for temperatures, or is there a different variable I should be using?
downvote count: 0
tagged with: weather-api
has answer: http://stackoverflow.com/a/49280594
score: 2
type: AnsweredQuestion
has title: NOAA API returning impossible historical temperature values
answer count: 1

http://stackoverflow.com/comment/85647208
has text: Truntle you are trying to do with Python classes something that they are not designed for. This is like trying to translate a sentence from English to Spanish swapping every word with a dictionary, you will get a non-readable sentence. When you learn a new language, forget what you know about others, learn it and then stablish relations to remember parts if you want. Its like trying to use `interface{}` in Go to replace generic types when you come from C++. Do not try to adapt a programming language to your programming habits, make your programming habits adapt to your currently used language.
score: 0
comment on: http://stackoverflow.com/q/49320766
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85831372
has text: @martineau i haven't tried it yet but it's possible `getattr()` would work on modules that include a `__getattr__` function- but i wouldn't expect it to work on modules that do not, and it would also probably be blind to objects that the `__getattr__` isn't aware of.
comment on: http://stackoverflow.com/q/49412334
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49387488
score: 2
has comment: http://stackoverflow.com/comment/85776222
downvote count: 4
answers question: http://stackoverflow.com/q/49387445
has comment: http://stackoverflow.com/comment/85776260
has comment: http://stackoverflow.com/comment/85776274
has body: The list comprehension here is the preferred method. However, if you wanted to avoid the list comprehension, you can use map(): map(lambda f: f(0), funcs) #[0, 0.0] But in python3 you would need to wrap the call to map() with list since map() returns an iterator: list(map(lambda f: f(0), funcs)) But as @jonrsharpe mentioned in the comments, this is not recommended as it wastefully creates a list. Timing Results On my computer running python 2.7 #List comprehension %%timeit [f(0) for f in funcs] #1000000 loops, best of 3: 352 ns per loop #map + lambda %%timeit map(lambda f: f(0), funcs) #1000000 loops, best of 3: 687 ns per loop #generator list(f(0) for f in funcs) #1000000 loops, best of 3: 1.1 µs per loop #map + methodcaller %%timeit map(methodcaller('__call__', 0), funcs) #1000000 loops, best of 3: 687 ns per loop The slowest solution (by far) is the generator method suggested by @timgeb in the comments. List comprehension is the fastest Both solutions using map() are second fastest.
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/85776232
has comment: http://stackoverflow.com/comment/85777809

http://stackoverflow.com/q/49322712
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49323039
has title: subclasses with functions having the same name in python
tagged with: oop
linked to: http://stackoverflow.com/q/31232098
tagged with: python
has body: I have two classes in python, and a third which inherits from the first two: class A(): def __init__(var1, var2): self.var1 = var1 self.var2 = var2 def MyFunc(): #do stuff class B(): def __init__(var1): self.var1 = var1 def MyFunc(): #do other stuff class C(A,B): def __init__(self, var1, var2, var3) A.__init__(self,var1, var2) B.__init__(self, var3) As you might notice both classes have different functions bearing the same name. Doing the following: &gt;&gt;&gt; classC = C(1,2,3) &gt;&gt;&gt; classC.MyFunc() Appears to work but I would like to be sure of which MyFunc function I am calling. How do I control which function from my subclasses is being called?
tagged with: class
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85646719
score: 0
has comment: http://stackoverflow.com/comment/85649766
has comment: http://stackoverflow.com/comment/85647318
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49323039

http://stackoverflow.com/q/49316825
favorite count: 0
type: Question
has title: The usage of radix sort
has answer: http://stackoverflow.com/a/49317108
tagged with: radix-sort
type: UnansweredQuestion
tagged with: python
has body: Let's say i have a file containing data on users and their favourite movies. Ace: FANTASTIC FOUR, IRONMAN Jane: EXOTIC WILDLIFE, TRANSFORMERS, NARNIA Jack: IRONMAN, FANTASTIC FOUR and based of that, the program I'm about to write returns me the name of the users that likes the same movies. Since Ace and Jack likes the same movie, they will be partners hence the program would output: Movies: FANTASTIC FOUR, IRONMAN Partners: Ace, Jack Jane would be exempted since she doesn't have anyone who shares the same interest in movies as her. The problem I'm having now is figuring out on how Radix Sort would help me achieve this as I've been thinking whole day long. I don't have much knowledge on radix sort but i know that it compares elements one by one but I'm terribly confused in cases such as FANTASTIC FOUR being arranged first in Ace's data and second in Jack's data. Would anyone kindly explain some algorithms that i could understand to achieve the output?
score: 0
upvote count: 1
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/85633818
type: Comment
type: QuestionComment
has text: @APC cx-Oracle==6.0.2
comment on: http://stackoverflow.com/q/49315383
score: 0

http://stackoverflow.com/comment/85748963
type: QuestionComment
has text: `no attribute called model` it is written in my question :)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49370795

http://stackoverflow.com/comment/85811743
has text: Does the python process need to be running constantly, or is it enough to invoke it at a certain (higher frequency) interval? How fast does it have to restart to fulfil its purpose?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49405343
type: Comment

http://stackoverflow.com/q/49400780
accepted answer: http://stackoverflow.com/a/49400877
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/68097704
has body: My Command output is something like 0x53 0x48 0x41 0x53 0x48 0x49. Now i need to store this in a hex value and then convert it to ASCII as SHASHI. What i tried- I tried to store the values in hex as int("0x31",16) then decode this to ASCII using decode("ascii") but no luck. "0x31".decode("utf16")this throws an error AttributeError: 'str' object has no attribute 'decode' Some other stuffs with random encoding and decoding whatever found through Google. But still no luck. Question :- How can i store a value in Hex like 0x53 0x48 0x41 0x53 0x48 0x49 and convert it's value as SHASHI for verification. Note: Not so friendly with Python, so please excuse if this is a novice question.
tagged with: type-conversion
possible better answer: http://stackoverflow.com/a/49400986
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49400923
has answer: http://stackoverflow.com/a/49400877
has title: How to store Hex and convert Hex to ASCII in Python?
has answer: http://stackoverflow.com/a/49400986
tagged with: data-conversion
has comment: http://stackoverflow.com/comment/85802925
tagged with: python
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/85751146
comment on: http://stackoverflow.com/a/49374584
score: 0
has text: From all of the answers, I think that this is the most simplest so thank you very much!!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85840309
has text: I get a different error.
comment on: http://stackoverflow.com/q/49419351
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49352447
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49352285
has body: Looks good. You're almost there. It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !&lt; n it runs n times. That means that you add n**2 to n**2*n. That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3 Hope this was clear enough.
score: 2
upvote count: 2

http://stackoverflow.com/q/49369163
type: Question
tagged with: python-3.x
tagged with: assertraises
upvote count: 12
tagged with: python
has title: Custom exceptions in unittests
score: 12
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35490843
has body: I have created my custom exceptions as such within errors.py mapper = { 'E101': 'There is no data at all for these constraints', 'E102': 'There is no data for these constraints in this market, try changing market', 'E103': 'There is no data for these constraints during these dates, try changing dates', } class DataException(Exception): def __init__(self, code): super().__init__() self.msg = mapper[code] def __str__(self): return self.msg Another function somewhere else in the code raises different instances of DataException if there is not enough data in a pandas dataframe. I want to use unittest to ensure that it returns the appropriate exception with its corresponding message. Using a simple example, why does this not work: from .. import DataException def foobar(): raise DataException('E101') import unittest with unittest.TestCase.assertRaises(DataException): foobar() As suggested here: Python assertRaises on user-defined exceptions I get this error: TypeError: assertRaises() missing 1 required positional argument: 'expected_exception' Or alternatively: def foobar(): raise DataException('E101') import unittest unittest.TestCase.assertRaises(DataException, foobar) results in: TypeError: assertRaises() arg 1 must be an exception type or tuple of exception types Why is it not recognizing DataException as an Exception? Why does the linked stackoverflow question answer work without supplying a second argument to assertRaises?
linked to: http://stackoverflow.com/q/18084476
has comment: http://stackoverflow.com/comment/85740037
answer count: 1
downvote count: 0
tagged with: python-unittest
accepted answer: http://stackoverflow.com/a/49369203
has answer: http://stackoverflow.com/a/49369203
favorite count: 0
tagged with: unit-testing

http://stackoverflow.com/a/49421402
type: Answer
has comment: http://stackoverflow.com/comment/85844490
has comment: http://stackoverflow.com/comment/85844406
upvote count: 2
answers question: http://stackoverflow.com/q/49421228
has body: The following solution is conceptually similar to one proposed by Julien but has a different implementation. from collections import Counter from itertools import chain a = [[1,2,1], [4,5], [1,2], [6,7]] Calculate the set of duplicates. If two items are repeated only within a sublist, they are not considered dups. First, get a counter of all items. counter = Counter(chain(*map(set, a))) #Counter({2: 2, 1: 1, 4: 1, 5: 1, 3: 1, 6: 1, 7: 1}) dups = {val for val, count in counter.items() if count &gt; 1} #{1,2} Intersect the duplicates with each sublist and filter out the duped sublists: list(filter(lambda sublist: not dups &amp; set(sublist), a)) #[[4, 5], [6, 7]] It works both for lists of lists and lists of tuples.
has comment: http://stackoverflow.com/comment/85844471
score: 2
downvote count: 0

http://stackoverflow.com/comment/85862213
type: QuestionComment
has text: [PD](https://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors)
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49430215

timer
tag name: timer
tags question: http://stackoverflow.com/q/49379419
tags question: http://stackoverflow.com/q/49352878
type: Tag
tags question: http://stackoverflow.com/q/49357063
tags question: http://stackoverflow.com/q/49309927

http://stackoverflow.com/q/49353430
tagged with: python
score: -1
has title: running python code using single key presses
has comment: http://stackoverflow.com/comment/85817286
has answer: http://stackoverflow.com/a/49973364
has answer: http://stackoverflow.com/a/49407640
has body: Currently building Petrol-powered RC car controlled by a raspberry pi and 16ch adafruit servo controller Pi hat. Pretty novice query from a beginner but how can simple Python commands be carried out by a single key press. E.g. Holding the "w" key on a keyboard to run "pwm.setPWM(0, 0, servoMax)". (In order for the servo to push the throttle to move the vehicle forward). What follows is the code currently used: #!/usr/bin/python from Adafruit_PWM_Servo_Driver import PWM import time pwm = PWM(0x40) servoMin = 150 servoMax = 600 def setServoPulse(channel, pulse): pulseLength = 1000000 pulseLength /= 60 print "%d us per period" % pulseLength pulseLength /= 4096 print "%d us per bit" % pulseLength pulse *= 1000 pulse /= pulseLength pwm.setPWM(channel, 0, pulse) pwm.setPWMFreq(60) While (True): pwm.setPWM(0, 0, servoMin) #throttle servo set to off position -should be default pwm.setPWM(0, 0, servoMAX) #throttle servo set on -to be run by "W" key pwm.setPWM(1, 0, servoMin) #steering servo left -by holding "A" key pwm.setPWM(1, 0, servoMax) #steering servo right -by holding "D" key I would assume the answer involves If and ElseIf commands, but I really would just like to run a program then input() keyboard presses to run the code.
downvote count: 1
favorite count: 0
type: Question
answer count: 2
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/85707265
tagged with: servo
linked to: http://stackoverflow.com/q/15855168
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85772925
type: QuestionComment
has text: If I use raw_input() I get this error: severity: 'Error' message: 'E0602:Undefined variable 'raw_input'' at: '36,8' source: 'pylint' code: 'E0602' @jonrsharpe
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49385105

http://stackoverflow.com/comment/85879922
score: 0
has text: What are the key and value types? And do you care about worst-case time. or just usually-fast? If you're mapping 8-bit strings to 8-bit strings, using a local key-value store, maybe even as simple `dbhash` or `gbdm`, may be reasonably efficient almost all the time as long as you leave enough memory free for caching.
type: QuestionComment
comment on: http://stackoverflow.com/q/49438954
type: Comment

http://stackoverflow.com/comment/85945670
type: QuestionComment
has text: Thank you for your time, when I run the code taking out the matplotlib graphs it runs exactly as expected, so I figured maybe someone knew I was missing a certain DLL. If I manually move the matplotlib folder into the build file I receive the traceback error that I attached the photos of it that helps at all.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49331835

http://stackoverflow.com/a/49532117
accepted answer of: http://stackoverflow.com/q/49361952
has comment: http://stackoverflow.com/comment/86073221
has comment: http://stackoverflow.com/comment/86075386
type: Answer
has body: Write like this in your action: Any Name your.model form kanban,tree,form [('state', '!=', 'draft')] or if you want this function to be applied only to a particular group means, write this in security.xml file: Any Name [('state', '!=', 'draft')]
answers question: http://stackoverflow.com/q/49361952
has comment: http://stackoverflow.com/comment/86075001
has comment: http://stackoverflow.com/comment/86074738
has comment: http://stackoverflow.com/comment/110705676
has comment: http://stackoverflow.com/comment/86073546
has comment: http://stackoverflow.com/comment/86075502
has comment: http://stackoverflow.com/comment/86075412
has comment: http://stackoverflow.com/comment/86075452
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86073914
has comment: http://stackoverflow.com/comment/110705667
upvote count: 1
has comment: http://stackoverflow.com/comment/86075184
has comment: http://stackoverflow.com/comment/86074653
has comment: http://stackoverflow.com/comment/86073832

http://stackoverflow.com/a/49296876
type: Answer
has body: A list comprehension is one way. "Pythonic" is subjective and I would not claim this is the most readable or desirable method. data = ['keywords', 'testcases'] data_combination = ['data', 'index'] res = [[i] + data_combination[0:j] for i in data \ for j in range(1, len(data_combination)+1)] # [['keywords', 'data'], # ['keywords', 'data', 'index'], # ['testcases', 'data'], # ['testcases', 'data', 'index']]
accepted answer of: http://stackoverflow.com/q/49296697
downvote count: 0
answers question: http://stackoverflow.com/q/49296697
upvote count: 7
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85595914
has comment: http://stackoverflow.com/comment/85595757

http://stackoverflow.com/q/49344715
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85690535
accepted answer: http://stackoverflow.com/a/49350353
has comment: http://stackoverflow.com/comment/85689697
has body: I was looking for Java's equivalent code or underlying theory for pythons np.random.choice (Numpy as np). I am trying to implement Q-learning in Java. I have a similar implementation that uses Python's np.random.choice method to select the random moves from the probability distribution. Python's code Input list: ['pooh', 'rabbit', 'piglet', 'Christopher'] and probabilies: [0.5, 0.1, 0.1, 0.3] I want to select one of the value from the input list given the associated probability of each input element.
has comment: http://stackoverflow.com/comment/85689603
tagged with: random
has comment: http://stackoverflow.com/comment/85690464
has answer: http://stackoverflow.com/a/49350353
has comment: http://stackoverflow.com/comment/85689578
score: 1
tagged with: java
has comment: http://stackoverflow.com/comment/85690555
has comment: http://stackoverflow.com/comment/85689665
tagged with: python
has comment: http://stackoverflow.com/comment/85689649
has comment: http://stackoverflow.com/comment/85689659
duplicate of: http://stackoverflow.com/q/6409652
has comment: http://stackoverflow.com/comment/85690474
has title: What is the Java equivalent of Python's Numpy np.random.choice?
has comment: http://stackoverflow.com/comment/85689740
has comment: http://stackoverflow.com/comment/85690580
type: Question
tagged with: numpy
upvote count: 2
has comment: http://stackoverflow.com/comment/85689683
tagged with: probability
has comment: http://stackoverflow.com/comment/85690524
answer count: 1
has comment: http://stackoverflow.com/comment/85689877
has comment: http://stackoverflow.com/comment/85689737
has comment: http://stackoverflow.com/comment/85690404
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/4702036
linked to: http://stackoverflow.com/q/6409652

http://stackoverflow.com/a/49358804
has body: This is my solution to the problem. import cv2 import numpy as np # read and scale down image img = cv2.pyrDown(cv2.imread('sample_images/phone_test.jpg', cv2.IMREAD_UNCHANGED)) # threshold image ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 150, 255, cv2.THRESH_BINARY) # find contours and get the external one image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: # get the bounding rect x, y, w, h = cv2.boundingRect(c) crop = img[y:y+h+22,x:x+w+5] #give a bit of space, because the boundingRect is not perfect cv2.imwrite('sample_images/phone_test_crop.jpg', crop) cv2.destroyAllWindows() Before: Before crop After: After crop
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49317229
accepted answer of: http://stackoverflow.com/q/49317229
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85685486
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49342540
type: AnswerComment
has text: I see what you did, and I've done something similar, but when I went to implement this, I found something that I wasn't aware was happening (hopefully it's the cause of my problems). So the file is being split by the lines (I did line = file.split("\n"), but I just realized that this is causing the variable that handles each line to treat each line as a singular item in an array. No wonder it's not working! But then, when I went to test this theory by doing print(line[3]), it said that the list index is out of range even though there are much more than 4 lines in this file.

http://stackoverflow.com/comment/85750546
has text: Just move it to 3.7 folder
score: 0
comment on: http://stackoverflow.com/a/49343576
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49324933
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/85651690
has body: Please help me I am not able to find why is my python code showing errors if (temp == "") error is : if (temp == "") ^ SyntaxError: invalid syntax
accepted answer: http://stackoverflow.com/a/49324975
answer count: 1
favorite count: 0
has title: python if statement shows errors
type: Question
score: -2
has answer: http://stackoverflow.com/a/49324975
tagged with: python
linked to: http://stackoverflow.com/q/37833625

http://stackoverflow.com/comment/85582981
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Usually I'd point out that CPython's garbage collection happens immediately except in the special case where there are cycles… but pickle has done all kinds of crazy things in the past, and for all I know there could be a cycle between its type cache and the last loaded pickle or something…
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49289830

http://stackoverflow.com/q/49352870
has body: A B C 0 2002-01-13 15:00:00 120 1 2002-01-13 15:30:00 110 2 2002-01-13 16:00:00 130 3 2002-01-13 16:30:00 140 4 2002-01-14 15:00:00 180 5 2002-01-14 15:30:00 165 6 2002-01-14 16:00:00 150 7 2002-01-14 16:30:00 170 I want to select one row per each A group, with next conditions: Select the "minimum C column value + 10". If it doesn´t exist "minimum C column value + 10", take the next C column value. Output should be: A B C 0 2002-01-13 15:00:00 120 5 2002-01-14 15:30:00 165
has comment: http://stackoverflow.com/comment/85705953
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49353316
tagged with: pandas
tagged with: python
has title: Select row with conditions column value
has answer: http://stackoverflow.com/a/49352909
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49353316
downvote count: 2
accepted answer: http://stackoverflow.com/a/49352909

http://stackoverflow.com/comment/85578706
type: QuestionComment
comment on: http://stackoverflow.com/q/49286876
score: 0
has text: @EthanFurman I edited my question for better understanding, I hope it helped.
type: Comment

http://stackoverflow.com/a/49411939
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49411908
has body: Convert date to datetime, and time to timedelta, and just sum 'em up. pd.to_datetime(df.date) + pd.to_timedelta(df.time) 0 2018-01-01 07:30:33 1 2017-01-01 07:30:33 dtype: datetime64[ns] If you're worried about invalid values, add the errors='coerce' argument to both functions to handle them appropriately.
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49411908
type: AcceptedAnswer

http://stackoverflow.com/q/49301203
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has title: keras error got an unexpected keyword argument 'epochs'
has body: I'm trying to train a network in Keras to classify an image and after debugging the last issue got this one of unexpected keywork epochs muiruri_samuel@training-2:~/google-landmark-recognition-challenge$ python train.py Using TensorFlow backend. Found 981214 images belonging to 14951 classes. Found 237925 images belonging to 14951 classes. Epoch 1/1 2018-03-15 13:35:19.822304: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instruc tions that this TensorFlow binary was not compiled to use: AVX2 FMA Traceback (most recent call last): File "train.py", line 74, in &lt;module&gt; validation_data=validation_generator) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 91, in w rapper return func(*args, **kwargs) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/models.py", line 1276, in fit_genera tor initial_epoch=initial_epoch) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 91, in w rapper return func(*args, **kwargs) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/engine/training.py", line 2224, in f it_generator class_weight=class_weight) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/engine/training.py", line 1883, in t rain_on_batch outputs = self.train_function(ins) File "/home/muiruri_samuel/.local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 2478, in __call__ **self.session_kwargs) TypeError: run() got an unexpected keyword argument 'epochs' at this point I've removed epochs but still getting the same error from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K from keras.callbacks import EarlyStopping from keras.callbacks import ModelCheckpoint # dimensions of our images. img_width, img_hei…
has comment: http://stackoverflow.com/comment/85604888
score: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49301581
has answer: http://stackoverflow.com/a/49301581
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85789365
comment on: http://stackoverflow.com/q/49393805
score: 2
has text: Does it have to be in pure Python? Numpy would (probably) make this much faster as you could mask parts of the available array based on your range. However, you should really show any way you have made this work before considering what might be the fastest.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49345925
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85698747
has body: I can't reproduce the [2,2,256,512] shape. But with this piece of code: rnn_size = 512 batch_size = 256 time_size = 5 input_size = 2 keep_prob = 0.5 lstm_1 = tf.nn.rnn_cell.LSTMCell(rnn_size) lstm_dropout_1 = tf.nn.rnn_cell.DropoutWrapper(lstm_1, output_keep_prob=keep_prob) lstm_2 = tf.nn.rnn_cell.LSTMCell(rnn_size) stacked_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_dropout_1, lstm_2]) rnn_inputs = tf.placeholder(tf.float32, shape=[None, time_size, input_size]) # Shape of the rnn_inputs is (batch_size, time_size, input_size) init_state = stacked_lstm.zero_state(batch_size, tf.float32) rnn_outputs, final_state = tf.nn.dynamic_rnn(stacked_lstm, rnn_inputs, initial_state=init_state) print(rnn_outputs) print(final_state) I get the right shape for run_outputs: (batch_size, time_size, rnn_size) Tensor("rnn/transpose_1:0", shape=(256, 5, 512), dtype=float32) The final_state is indeed a pair of LSTMStateTuple (for the 2 cells lstm_dropout_1 and lstm_2): (LSTMStateTuple(c=&lt;tf.Tensor 'rnn/while/Exit_3:0' shape=(256, 512) dtype=float32&gt;, h=&lt;tf.Tensor 'rnn/while/Exit_4:0' shape=(256, 512) dtype=float32&gt;), LSTMStateTuple(c=&lt;tf.Tensor 'rnn/while/Exit_5:0' shape=(256, 512) dtype=float32&gt;, h=&lt;tf.Tensor 'rnn/while/Exit_6:0' shape=(256, 512) dtype=float32&gt;)) as described in the string doc of tf.nn.dynamic_run: # 'outputs' is a tensor of shape [batch_size, max_time, 256] # 'state' is a N-tuple where N is the number of LSTMCells containing a # tf.contrib.rnn.LSTMStateTuple for each cell
accepted answer of: http://stackoverflow.com/q/49345172
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49345172

http://stackoverflow.com/comment/85707204
has text: @Vimanyu Now I'm getting the error `Failed to execute child process "bash -c "python3 sniffer.py"" (No such file or directory`. I am using Kali Linux 2018.1
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49351431

http://stackoverflow.com/comment/85809363
type: AnswerComment
comment on: http://stackoverflow.com/a/49403911
type: Comment
has text: @konstantin then your list does have a different format than the one in my demo which you did not tell us about.
score: 0

http://stackoverflow.com/comment/85905732
type: AnswerComment
has text: I am still a bit confused. This algorithm looks very handy, but could you add comments to describe each line, because I don't know how to incorporate this into my game.
comment on: http://stackoverflow.com/a/49433498
type: Comment
score: 0

http://stackoverflow.com/comment/85827210
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49397270
has text: The text above might need rephrasing. But I am not sure what case is not covered here. We either raised our object/class, got a TypeError or got and exception from outside (KeyboardInterrupt, etc.) am I missing something?

http://stackoverflow.com/comment/85664970
comment on: http://stackoverflow.com/q/49331307
score: 0
type: Comment
type: QuestionComment
has text: Say if questData is a long list of strings like this: {"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true}, how would we be able to search All Fired Up in this long list of strings, then print all the information between the { }? Does that clarify what I am asking?

attributeerror
tags question: http://stackoverflow.com/q/49325837
tags question: http://stackoverflow.com/q/49365979
tags question: http://stackoverflow.com/q/49332694
tag name: attributeerror
type: Tag
tags question: http://stackoverflow.com/q/49379088
tags question: http://stackoverflow.com/q/49420059

http://stackoverflow.com/q/49342838
has comment: http://stackoverflow.com/comment/85686760
answer count: 2
has body: I have a script that pulls information from an API and is supposed to write it to a CSV file which I have in the same directory. For some reason, all the code seems to execute fine but the CSV never actually contains any data. Am I missing something crucial? I've checked the documentation for the CSV module but can't find anything. Here is my code: import time, json, requests, csv with open('data.csv', 'w') as csvfile: fieldnames = ['time','last','vwap','high','low','open','vol'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() def btstampTime(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['timestamp'] def btstampLast(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['last'] def btstampVWAP(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['vwap'] def btstampHigh(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['high'] def btstampLow(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['low'] def btstampOpen(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['open'] def btstampVol(): bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/') return bitStampTick.json()['volume'] while True: timestamp = btstampTime() last = float(btstampLast()) vwap = float(btstampVWAP()) high = float(btstampHigh()) low = float(btstampLow()) open = float(btstampOpen()) vol = float(btstampVol()) writer.writerow({'time': timestamp, 'last': last, 'vwap': vwap, 'high': high, 'low': low, 'open': open, 'vol': vol}) print('Time: ', timestamp) print('Last =', last) print('VWAP =', vwap) print('High =', high) print('Low =', low) print('Open =', open) print('Volume =', vol) print('') time.sleep(60)
has title: Python: Can't save to CSV
upvote count: 2
has comment: http://stackoverflow.com/comment/85685983
tagged with: api
downvote count: 0
possible better answer: http://stackoverflow.com/a/49343272
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49343272
has comment: http://stackoverflow.com/comment/85686163
has comment: http://stackoverflow.com/comment/85686040
has comment: http://stackoverflow.com/comment/85686688
accepted answer: http://stackoverflow.com/a/49343188
has comment: http://stackoverflow.com/comment/85686534
has comment: http://stackoverflow.com/comment/85686170
has comment: http://stackoverflow.com/comment/85685998
has answer: http://stackoverflow.com/a/49343188
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85686626
tagged with: python
has comment: http://stackoverflow.com/comment/85686067
type: AnsweredQuestion
score: 2

c++
tags question: http://stackoverflow.com/q/49358457
tags question: http://stackoverflow.com/q/49373068
tags question: http://stackoverflow.com/q/49401213
tags question: http://stackoverflow.com/q/49393611
tags question: http://stackoverflow.com/q/49396094
tags question: http://stackoverflow.com/q/49356318
tags question: http://stackoverflow.com/q/49313291
tags question: http://stackoverflow.com/q/49346490
tags question: http://stackoverflow.com/q/49328368
tags question: http://stackoverflow.com/q/49401223
tags question: http://stackoverflow.com/q/49301317
tags question: http://stackoverflow.com/q/49320251
tags question: http://stackoverflow.com/q/49394526
tags question: http://stackoverflow.com/q/49428298
tags question: http://stackoverflow.com/q/49371712
tags question: http://stackoverflow.com/q/49312257
tags question: http://stackoverflow.com/q/49395878
type: Tag
tags question: http://stackoverflow.com/q/49390354
tags question: http://stackoverflow.com/q/49283031
tag name: c++
tags question: http://stackoverflow.com/q/49353463

http://stackoverflow.com/comment/85735560
comment on: http://stackoverflow.com/q/49366928
has text: @internet_user But I wouldn't know that until I realize I write something in the future, right?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49410529
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: How do I run a Python script in Unix
has comment: http://stackoverflow.com/comment/85822769
has body: I'm not a Python developer but I need to use this language to set up certain application. I'd like to do basic auth. Python documentation reads: Making requests with HTTP Basic Auth is very simple: &gt;&gt;&gt; from requests.auth import HTTPBasicAuth &gt;&gt;&gt; requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) &lt;Response [200]&gt; So I created a file where I put: from requests.auth import HTTPBasicAuth requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) However, it is not as simple as the documentation claims. When I run the code I get the following error: ./auth.py: line 1: from: command not found ./auth.py: line 2: syntax error near unexpected token `'https://api.github.com/user',' ./auth.py: line 2: `requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))' I use Python 2.7.
has comment: http://stackoverflow.com/comment/85822777
tagged with: python
tagged with: zapier
has comment: http://stackoverflow.com/comment/85822691
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/49410625
accepted answer: http://stackoverflow.com/a/49410625

http://stackoverflow.com/q/49413904
has comment: http://stackoverflow.com/comment/85836945
tagged with: maya
has comment: http://stackoverflow.com/comment/85829441
has comment: http://stackoverflow.com/comment/85896696
has title: MassEdits on referenceEdits
type: Question
type: UnansweredQuestion
tagged with: python
has body: I've got issues with the maya function referenceEdit. For my job I've to clean animators scenes for our client in order to be sure there is no animations on meshes, no mesh hided, etc... So I would like to delete referenceEdits on all my meshes when an animator validated his shot. But if I make a for loop on meshes for delete their referenceEdits if they've any, Maya takes much more time than expected even in batchMode I could jump on something like 30-90 min per scene just for this step of cleaning. I tried to make it with threading but Maya seems to not like it, here is my code without threading: import time start = time.time() debug=False meshes = cmds.ls( type='mesh', ap=True, recursive=True ) tr_meshes = [ cmds.listRelatives( x, p=True, path=True)[0] for x in meshes ] to_test = list( set( meshes+tr_meshes ) ) edit_types = ['addAttr', 'connectAttr', 'deleteAttr', 'disconnectAttr', 'parent', 'setAttr', 'lock', 'unlock'] if to_test: for x in to_test: if debug: print '.',x for edit_type in edit_types: edits = cmds.referenceQuery( x, editStrings=True, editCommand=edit_type, successfulEdits=True, failedEdits=True ) if edits: # Then Delete ReferenceEdits on it cmds.referenceEdit( x, removeEdits=True, editCommand=edit_type, successfulEdits=True, failedEdits=True ) if debug: for y in edits: print '\t.',y print time.time() - start Anybody knows how to achieve this faster please? Like something in Maya API? Or something else? My other trail is by editing directly the .ma but it's quite dangerous isn't it? [EDIT] I forgot to say I open my scenes without loading refs, launch my script and then save it and reopen it for other operations of cleaning just for be sure nothing brokes during the step
score: 0
answer count: 0

http://stackoverflow.com/q/49433979
downvote count: 0
has comment: http://stackoverflow.com/comment/85924158
tagged with: python
has comment: http://stackoverflow.com/comment/85878563
has comment: http://stackoverflow.com/comment/85869979
has title: global variables across files and numpy behavior
has answer: http://stackoverflow.com/a/49434141
score: 3
has body: I have three files: bar.py, foo.py, and main.py. # bar.py import numpy as np global y x=0 y=0 z=np.array([0]) # foo.py from bar import * def foo(): x=1 y=1 z[0]=1 # main.py from foo import * from bar import * print(x,y,z) # 0 0 [0] foo() print(x,y,z) # 0 0 [1] Question: Why did x and y not change their values while z did change value of its element? And, how should I write so that I can change values of x and y, which can also be accessible from other files? Normally I'd never write in this fashion, which was forced when translating an archaic FORTRAN77 program into python. The original code heavily uses common blocks and includes, so basically I cannot trace the declarations of all variables. But still I wanted to preserve the original style of the code, so I tried to make a "global variables module", whose variables can be modified from any part of the program. Back to my question, my guess is that numpy.ndarray is just pointer, and we do not change the value of a pointer, so z has changed. But even then the behavior of z seems very dangerous, that I cannot trust z to be shared as a global variable and its value is the same across all files. Who knows that z in main and foo are pointing the same memory sector? Moreover, how can I make some variables truly global? Actually when I tried to translate that FORTRAN program, I tried to make class and instances of them, then pass the instance over the arguments of the function, then I realized that requires modifying the code tremendously. What can I do?
upvote count: 3
has comment: http://stackoverflow.com/comment/85870161
answer count: 1
tagged with: global-variables
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85878643
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/4693120
type: UnansweredQuestion

http://stackoverflow.com/comment/85834603
has text: Can you display the frame right after capture without any processing? I suspect your camera doesn’t support the set size so cap.read() returns an error.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49416356

http://stackoverflow.com/a/49404454
answers question: http://stackoverflow.com/q/49404001
score: 3
has comment: http://stackoverflow.com/comment/85899014
upvote count: 3
has comment: http://stackoverflow.com/comment/85860366
has comment: http://stackoverflow.com/comment/108571714
has body: If I understand correctly, you seem to just be missing a reset_index() call. Try this: df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1).fillna(0) df.columns = df.columns.droplevel(0).rename('') df = df.reset_index()
accepted answer of: http://stackoverflow.com/q/49404001
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/49423670
answers question: http://stackoverflow.com/q/49423574
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85865581
has body: I am not exactly sure where you encoutered the error (you didnt metion it) but I think its here: train_vecs_w2v = np.concatenate([buildWordVector(z, n_dim) for z in tqdm(map(lambda x: x.words, x_train))]) You call buildWordVector there just like that - that seems to be the problem because the function buildWordVector is wihin a class, and should be called like so: classinstance=wordvector() classinstance.buildWordVector(args) You should try that. Hope I helped (if still in doubt, comment) Example (imperfect without full code): c=wordvector() train_vecs_w2v = np.concentrate([c.buildWordVector(z, n_dim) for z in tqdm(map(lambda x: x.words, x_train))]) EDIT: You say you need help with running a function of a class from another function of a class. Say you have a class like so: class testClass(): def spam(self): print('eggs') So say you want to make a function foo() inside the class that calls spam(). You have to ensure that when defining spam(), it (and the function that calls it) has the magic self variable (spam(self)). Then, to call on it from another function all you have to do is self.spam() and it will be called. This is what I am talking about: class testClass(): def spam(self): print('eggs') def foo(self): self.spam() Additionaly, with parameters: class testClass(): def spam(self,text): print(text) def foo(self): self.spam('eggs') So, this is how you do it. However, because of this magic self variabe, you have to call the functions in the class differently - by first making an instance of testClass(). How to do it: Say you already made the class as it is above. First, make an instance of the class. testClassInstance = testClass() then call the functions using the testClassInstance like so: testClassInstance.foo() result: eggs So this is how you do it, hope you understand. If still in doubt, comment.
has comment: http://stackoverflow.com/comment/85923054
type: Answer
has comment: http://stackoverflow.com/comment/85950317

http://stackoverflow.com/comment/85814002
score: 0
type: Comment
has text: Yes as you said "my algo visits all the child nodes" so if you look at when stack_depth increments then it looks like we will increment every time we access a node. And in our case we are accessing every single node. Because there is no return condition when stops the algorithm when the correct node is found. If you get what I mean.
type: AnswerComment
comment on: http://stackoverflow.com/a/49405672

http://stackoverflow.com/comment/85610454
comment on: http://stackoverflow.com/q/49302240
type: Comment
has text: indeed, if your batch has 4 samples, your placeholder should have one dimension for the sample size (the first one) which is `None` (to make batch size changeable without having to rewrite the network structure)
score: 1
type: QuestionComment

http://stackoverflow.com/q/49330175
tagged with: function
has answer: http://stackoverflow.com/a/49330200
accepted answer: http://stackoverflow.com/a/49330200
has title: use function or var to create a data frame column/index name
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
has body: I've got a series of loops that calculate sales for different brands, different periods from different dataframes. And here is the part of the code I want to optimize: #shname,dep,lname,y - come from itterables var=shname+dep+'ytd'+lname if dep == 'PY': ytd=data.loc[(Data.Brand==lname) &amp; (Data['PY_YTD?']==True),['Sales']].sum() if dep == 'NY': ytd=data.loc[(Data.Brand==lname) &amp; (Data['NY_YTD?']==True),['Sales']].sum() exec('%s=%d' % (var,ytd)) as you see there is a column name that happens to be different in dataframes depending on report year (PY - present, NY- next): Data['PY_YTD?']==True Data['NY_YTD?']==True so I simply used IF. However I wonder if there is a way to use some kind of function that calculates the column name based on currently iterated value I imagine it should look something like this: def YEAR (y): if y = 'PY': return Data['PY_YTD?']==True if y = 'NY': return Data['NY_YTD?']==True ytd=data.loc[(Data.Brand==lname) &amp; (YEAR(var)),['Sales']].sum()s would appreciate your help
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85665958
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49331896
type: Comment
has text: @AaronB Most of my answer is devoted to explaining the difference between the two. What part of it do you not understand, so I can make it clearer?

http://stackoverflow.com/a/49410882
has body: The simplest change you can make to your code is to get rid of importdata, which is just a wrapper on pd.read_csv. Try: filename = 'C:/Users/asus/Desktop/memoire/sequences-code.csv' data = pd.read_csv(filename, sep=';', header=None) Let me know if that helps.
has comment: http://stackoverflow.com/comment/85823850
has comment: http://stackoverflow.com/comment/85826451
has comment: http://stackoverflow.com/comment/85823737
type: Answer
has comment: http://stackoverflow.com/comment/85824380
answers question: http://stackoverflow.com/q/49410546
has comment: http://stackoverflow.com/comment/85824066
has comment: http://stackoverflow.com/comment/85823616
score: 0

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

http://stackoverflow.com/comment/85863343
type: QuestionComment
has text: you didn't include the stack trace, only the error
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49430565

http://stackoverflow.com/comment/85820753
has text: can the list contains not adjacents 'a's?
comment on: http://stackoverflow.com/q/49409150
score: 0
type: Comment
type: QuestionComment

multithreading
tags question: http://stackoverflow.com/q/49434728
tags question: http://stackoverflow.com/q/49418638
tags question: http://stackoverflow.com/q/49318306
tags question: http://stackoverflow.com/q/49392956
tags question: http://stackoverflow.com/q/49304429
tags question: http://stackoverflow.com/q/49368207
tags question: http://stackoverflow.com/q/49435550
type: Tag
tags question: http://stackoverflow.com/q/49386039
tags question: http://stackoverflow.com/q/49343907
tags question: http://stackoverflow.com/q/49431655
tags question: http://stackoverflow.com/q/49369629
tags question: http://stackoverflow.com/q/49304897
tags question: http://stackoverflow.com/q/49438246
tags question: http://stackoverflow.com/q/49317117
tags question: http://stackoverflow.com/q/49287685
tags question: http://stackoverflow.com/q/49401730
tags question: http://stackoverflow.com/q/49391569
tags question: http://stackoverflow.com/q/49434267
tags question: http://stackoverflow.com/q/49352961
tags question: http://stackoverflow.com/q/49386761
tags question: http://stackoverflow.com/q/49358473
tags question: http://stackoverflow.com/q/49355297
tags question: http://stackoverflow.com/q/49438070
tags question: http://stackoverflow.com/q/49390512
tags question: http://stackoverflow.com/q/49327775
tags question: http://stackoverflow.com/q/49316475
tags question: http://stackoverflow.com/q/49356784
tags question: http://stackoverflow.com/q/49430954
tags question: http://stackoverflow.com/q/49371214
tags question: http://stackoverflow.com/q/49416387
tags question: http://stackoverflow.com/q/49379419
tags question: http://stackoverflow.com/q/49399391
tags question: http://stackoverflow.com/q/49429398
tags question: http://stackoverflow.com/q/49415190
tags question: http://stackoverflow.com/q/49384742
tags question: http://stackoverflow.com/q/49327987
tag name: multithreading
tags question: http://stackoverflow.com/q/49368302
tags question: http://stackoverflow.com/q/49343682
tags question: http://stackoverflow.com/q/49407894
tags question: http://stackoverflow.com/q/49375702
tags question: http://stackoverflow.com/q/49344582
tags question: http://stackoverflow.com/q/49281955

http://stackoverflow.com/comment/85649226
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49320816
type: AnswerComment
has text: we can use `output = '\n'.join('\t'.join(map(str,row)) for row in zip(l,q))` to have them in columns with `print(output)`, but finding the minimum is our challenge then.

http://stackoverflow.com/comment/85757355
comment on: http://stackoverflow.com/a/49368567
score: 0
type: Comment
type: AnswerComment
has text: This tells me ` Type Error: iter_rows() got an unexpected keyword argument 'min_col'`

http://stackoverflow.com/a/49332646
type: Answer
answers question: http://stackoverflow.com/q/49332536
has comment: http://stackoverflow.com/comment/85668040
has comment: http://stackoverflow.com/comment/85667989
has comment: http://stackoverflow.com/comment/85667978
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85667369
has comment: http://stackoverflow.com/comment/85668012
has body: In regex you don't need to worry about what is the starting string unless you want to match it. In your case you don't need to write .* before the placeholder you used. so you can just use the regex like below: s = "hello world 1234/book" re.search(r'(?P&lt;text&gt;[0-9].*)/.*$', s).group(1) # '1234'
score: 1

http://stackoverflow.com/q/49405101
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49405143
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49405143
favorite count: 0
type: Question
has body: I have been searching for hours.I have a DataFrame like so :- col1. col2. col3. col4 row1. a. p u 0 row2. b. q v 1 row3. a. r w 2 row4. d. s x 3 row5. b. t y 4 Now I want to group all this rows by the value of 'col1' so that I get :- col1. col2. col3. col4 row1. a. p r u w 0,2 row2. b. q t v y 1,4 row3. d. s x 3 Now I found a way where df.groupby('col1)['col2'].apply(' '.join()) would group all rows in 'col2' by the same value of 'col1'.But I am unable to extend the above command such that all rows of all columns are grouped together to get the output mentioned earlier. The above DataFrame is just for illustration.The actual DataFrame includes around 100 rows and columns and all cells store feedbacks except for col1 which stores the name of the item for which the feedback is on.I want to group all columns on the basis of the same items(col1) and then I will be performing sentimental analysis on the DataFrame.
downvote count: 0
tagged with: data-analysis
answer count: 1
tagged with: python
has title: Grouping all rows of a pandas DataFrame(with many columns) with the same value in a given column
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/121921693
type: AnswerComment
has text: I tried this with PySide2. Alt and Shift modifiers won't work with PySide2. Any idea why and how to fix it?
comment on: http://stackoverflow.com/a/49316872
type: Comment
score: 0

http://stackoverflow.com/comment/86085723
type: AnswerComment
has text: @paul23 Did this solve your issue, or was it not the buffering that caused the problem?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49459659

http://stackoverflow.com/q/49316327
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49317165
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49317165
upvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/74343939
type: AnsweredQuestion
has title: How to set Collation in MySQL database with Django 2.* mysqlclient?
has body: I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', }, } } 'charset': 'utf8mb4', This parameter seems don't work properly and tables in DB utf8. Although i want to manually set and tables Collation to utf8mb4_general_ci Will be appreciate for any clues.
tagged with: django-models
score: -1
tagged with: mysql
possible better answer: http://stackoverflow.com/a/74343939
linked to: http://stackoverflow.com/q/6115612

http://stackoverflow.com/a/60094385
type: Answer
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/49350821
upvote count: 5
has body: You have to install pytest-asyncio. pip install pytest-asyncio You don't have to import it anywhere. Just decorate the async def tests with @pytest.mark.asyncio. It was mentioned by in the @hoefling comments, I'm posting this answer just to make it more visible: coroutine 'my_coro' was never awaited means that the coroutine object was never put into the event loop, so I suppose you are either missing pytest-asyncio that puts tests into event loop. Without pytest-asyncio, pytest doesn't know that it should await the async test. It just runs it as a non-async function, which is not enough to actually execute the async function body: $ python3 Python 3.7.3 (default, Apr 3 2019, 05:39:12) &gt;&gt;&gt; async def foo(): ... raise Excepion('this is never raised') ... &gt;&gt;&gt; foo() &lt;coroutine object foo at 0x7f7d857d4cc8&gt; &gt;&gt;&gt; exit() sys:1: RuntimeWarning: coroutine 'foo' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback

http://stackoverflow.com/a/49419824
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: There are two ways, either you set allow_redirects=False to prevent the request to be redirect to another page, or, you can check the canonical url: from bs4 import BeautifulSoup import requests import urllib l = 'http://en.wikipedia.org/wiki/Google_Inc_Class_A' req = requests.get(l, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(req._content, "lxml") canonical = soup.find('link', {'rel': 'canonical'}) canonical['href'] You can see more here: When I use python requests to check a site, if the site redirects me to another page, will I know?
accepted answer of: http://stackoverflow.com/q/49419577
score: 2
answers question: http://stackoverflow.com/q/49419577
upvote count: 2

http://stackoverflow.com/comment/85690514
score: 0
has text: No, the behaviour is the same regardless of whether the type is mutable.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49344917

http://stackoverflow.com/a/49436607
has comment: http://stackoverflow.com/comment/85875526
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49436376
has body: This should work: words = "help_me_code_please" size = 4 start = len(words)%size - size for i in reversed(range(start, len(words), size)): print(words[max(0,i):i+size]) output is ease e_pl _cod p_me hel Explanation: start gives us a starting point, that is some divisible block away from the length of our string (words). In our example, it's -1, as that is 20 (5*4) away from 19, the length of words. Now we do a reverse loop, from 19 -&gt; -1 at size four. So we go 15, 11, 7, 3, -1. Within each loop, we print from our position to the position + 4. So the first loop iteration prints out words[15:19] which outputs ease, the second is words[11:15], etc etc. This results in the output we see. Hopefully this explanation makes sense!
has comment: http://stackoverflow.com/comment/85879161
accepted answer of: http://stackoverflow.com/q/49436376
has comment: http://stackoverflow.com/comment/85878856
has comment: http://stackoverflow.com/comment/85875831
has comment: http://stackoverflow.com/comment/85875308
type: Answer
has comment: http://stackoverflow.com/comment/85875605
score: 0

http://stackoverflow.com/comment/85586159
type: Comment
type: QuestionComment
score: 0
has text: "everything is setup correctly" - well...
comment on: http://stackoverflow.com/q/49291275

http://stackoverflow.com/comment/85762991
type: Comment
type: QuestionComment
has text: Try `(?<=[a-z])at(?=[a-z])` or `\Bat\B` which almost does the same.
score: 3
comment on: http://stackoverflow.com/q/49381154

http://stackoverflow.com/q/49304516
accepted answer: http://stackoverflow.com/a/49304517
has title: Plotting a flow duration curve for a range of several timeseries in Python
downvote count: 2
has answer: http://stackoverflow.com/a/49304517
upvote count: 1
has comment: http://stackoverflow.com/comment/85613743
favorite count: 0
type: Question
has body: Flow duration curves are a common way in hydrology (and other fields) to visualize timeseries. They allow an easy assessment of the high and low values in a timeseries and how often certain values are reached. Is there an easy way in Python to plot it? I could not find any matplotlib tools, which would allow it. Also no other package seems to include it, at least not with the possibility to plot a range of flow duration curves easily. An example for a flow duration curve would be: An explantion on how to create it in general can be found here: http://www.renewablesfirst.co.uk/hydropower/hydropower-learning-centre/what-is-a-flow-duration-curve/ So the basic calculation and plotting of the flow duration curve are pretty straightforward. Simply calculate the exceedence and plot it against the sorted timeseries (see the answer of ImportanceOfBeingErnest). It gets more difficult though if you have several timeseries and want to plot the range of the values for all exceedence probabilities. I present one solution in my answer to this thread, but would be glad to hear more elegant solutions. My solution also incorporates an easy use as a subplot, as it is common to have several timeseries for different locations, that have to be plotted seperately. An example for what I mean with range of flow duration curves would be this: Here you can see three distinct curves. The black line is the measured value from a river, while the two shaded areas are the range for all model runs of those two models. So what would be the most easy way to calculate and plot a range of flow duration curves for several timeseries?
tagged with: time-series
has answer: http://stackoverflow.com/a/49306501
tagged with: matplotlib
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85611565
possible better answer: http://stackoverflow.com/a/49306501
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/49348198
accepted answer of: http://stackoverflow.com/q/49348091
has body: I was faced to the same question some weeks ago. This snippet worked for me: import lzma with lzma.open('filename.xz', mode='rt') as file: for line in file: print(line) This assumes that the text data in the compressed file was encoded in utf-8 (which was the case for my data). There is an encoding argument in function lzma.open() which allows you to set another encoding if needed EDIT (after you own edit): try to force encoding='utf-8' in lmza.open()
downvote count: 0
has comment: http://stackoverflow.com/comment/85696084
type: Answer
score: 8
upvote count: 8
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49348091

http://stackoverflow.com/a/49325212
has comment: http://stackoverflow.com/comment/85658190
answers question: http://stackoverflow.com/q/49323171
type: Answer
has comment: http://stackoverflow.com/comment/85655193
has body: For those closest point calculations, usually the efficient method is with one of those kd-tree based quick nearest-neighbor lookup. Employing Cython-powered implementation, we would have one approach like so - from scipy.spatial import cKDTree def closest_pts(setA_lat, setA_lng, setB_lat, setB_lng): a_x = setA_lat.values a_y = setA_lng.values b_x = setB_lat.values b_y = setB_lng.values a = np.c_[a_x, a_y] b = np.c_[b_x, b_y] indx = cKDTree(b).query(a,k=1)[1] return pd.Series(b_x[indx]), pd.Series(b_y[indx]) Sample run - 1) Inputs : In [106]: setA_lat Out[106]: 0 40.748043 1 42.361016 dtype: float64 In [107]: setA_lng Out[107]: 0 -73.992953 1 -71.020005 dtype: float64 In [108]: setB_lat Out[108]: 0 42.460000 1 0.645894 2 0.437587 3 40.460000 4 0.963663 dtype: float64 In [109]: setB_lng Out[109]: 0 -71.000000 1 0.925597 2 0.071036 3 -72.000000 4 0.020218 dtype: float64 2) Outputs : In [110]: c_x,c_y = closest_pts(setA_lat, setA_lng, setB_lat, setB_lng) In [111]: c_x Out[111]: 0 40.46 1 42.46 dtype: float64 In [112]: c_y Out[112]: 0 -72.0 1 -71.0 dtype: float64
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85666634
has text: Isn't there some way for it to like "stop when matched" and continue on with the code using the match?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49332044
type: QuestionComment

http://stackoverflow.com/comment/85735261
has text: Your RPi has to run a web server (or at least listen for connections on a socket), you can do it in Node.js or in python (using Flask for example). The easiest way would be to trigger your function when a web page is called. In Node.js you can use a system call to start your python script. I really suggest you to take a look at Flask. It is very easy and it uses python so you stay in the same 'environment'. Good luck !
type: Comment
comment on: http://stackoverflow.com/q/49367052
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85766628
type: Comment
comment on: http://stackoverflow.com/a/49382377
type: AnswerComment
has text: My prob is that as i have mentioned is that the element type is not always text it's only text when the task is completed or else is select.....but the other prob was while first loading the page the type is select and then the type gets change to text if the task is completed or else it remains select
score: 0

http://stackoverflow.com/q/49303835
tagged with: pyspark
tagged with: python
linked to: http://stackoverflow.com/q/48274851
linked to: http://stackoverflow.com/q/49162854
type: AnsweredQuestion
tagged with: apache-spark
tagged with: functional-programming
upvote count: 2
accepted answer: http://stackoverflow.com/a/49313182
has title: How to understand reduceByKey in Spark?
has comment: http://stackoverflow.com/comment/85610023
answer count: 1
has answer: http://stackoverflow.com/a/49313182
score: 1
downvote count: 1
tagged with: documentation
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85610501
has body: I am trying to learn Spark and it has been going well so far, except for problems where I need to use functions like reduceByKey or combineByKey on a pair RDD whose values are lists. I have been trying to find detailed documentation for these functions, that could explain what the arguments actually are, so that I could solve it myself without going to Stack Overflow, but I just cannot find any good documentation for Spark. I have read chapters 3 and 4 from Learning Spark, but to be honest, the explanations for the most complicated functions are very bad. The problem I am dealing with right now is the following: I have a pair RDD where the key is a string and the value is a list of two elements which are both integers. Something like this: (country, [hour, count]). For each key, I wish to keep only the value with the highest count, regardless of the hour. As soon as I have the RDD in the format above, I try to find the maximums by calling the following function in Spark: reduceByKey(lambda x, y: max(x[1], y[1])) But this throws the following error: TypeError: 'int' object is not subscriptable Which does not make any sense to me. I interpreted the arguments x and y as being the values of two keys, e.g. x=[13, 445] and y=[14, 109], but then the error does not make any sense. What am I doing wrong?

http://stackoverflow.com/a/49331788
answers question: http://stackoverflow.com/q/49331686
type: Answer
has body: Where does you function get comp and choice ? Something like this would work : from tkinter import messagebox rock=1 paper=2 scissors=3 def Winning(comp, choice): if (((comp == 2) and (choice == 1)) or ((comp == 3) and (choice == 2)) or((comp == 1) and (choice == 3))): messagebox.showinfo("Info", "YOU LOSE!!!") if (((choice == 2) and (comp == 1)) or ((choice == 3) and (comp == 2)) or((choice == 1) and (comp == 3))): messagebox.showinfo("Info", "YOU WIN!!!") else: messagebox.showinfo("Info", "DRAW!!!") Winning(rock, paper) Is this what you want ?
has comment: http://stackoverflow.com/comment/85666354
score: 0
accepted answer of: http://stackoverflow.com/q/49331686
type: AcceptedAnswer

http://stackoverflow.com/q/49316791
has title: Python, Pandas to add columns from calculation
has answer: http://stackoverflow.com/a/49316818
accepted answer: http://stackoverflow.com/a/49316818
score: 1
tagged with: dataframe
has body: A data frame like this and I am adding some columns from mapping and calculation. code month of entry name reports 0 JJ 20171002 Jason 14 1 MM 20171206 Molly 24 2 TT 20171208 Tina 31 3 JJ 20171018 Jake 22 4 AA 20090506 Amy 34 5 DD 20171128 Daisy 16 6 RR 20101216 River 47 7 KK 20171230 Kate 32 8 DD 20171115 David 14 9 JJ 20171030 Jack 10 10 NN 20171216 Nancy 28 What it is doing here is select some rows and look up the values from the dictionary and insert a further column from simple calculation. It works fine: import pandas as pd data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy', 'Daisy', 'River', 'Kate', 'David', 'Jack', 'Nancy'], 'code' : ['JJ', 'MM', 'TT', 'JJ', 'AA', 'DD', 'RR', 'KK', 'DD', 'JJ', 'NN'], 'month of entry': ["20171002", "20171206", "20171208", "20171018", "20090506", "20171128", "20101216", "20171230", "20171115", "20171030", "20171216"], 'reports': [14, 24, 31, 22, 34, 16, 47, 32, 14, 10, 28]} df = pd.DataFrame(data) dict_hour = {'JasonJJ' : 3, 'MollyMM' : 6, 'TinaTT' : 2, 'JakeJJ' : 3, 'AmyAA' : 8, 'DaisyDD' : 6, 'RiverRR' : 4, 'KateKK' : 8, 'DavidDD' : 5, 'JackJJ' : 5, 'NancyNN' : 2} wanted = ['JasonJJ', 'TinaTT', 'AmyAA', 'DaisyDD', 'KateKK'] df['name_code'] = df['name'].astype(str) + df['code'].astype(str) df1 = df[df['name_code'].isin(wanted)] df1['hour'] = df1['name_code'].map(dict_hour).astype(float) df1['coefficient'] = df1['reports'] / df1['hour'] - 1 But the last 2 lines received a same warning: 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 How can the code can be improved accordingly? Thank you.
tagged with: python
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/85733806
type: Comment
type: QuestionComment
score: 0
has text: Thanks. But, I'm looking for multiple replacements.
comment on: http://stackoverflow.com/q/49366378

http://stackoverflow.com/comment/85683396
type: QuestionComment
comment on: http://stackoverflow.com/q/49341357
has text: Good question, but I think the `HTTPServer` will handle requests synchronously until a mixin is added. I haven't tested this myself, but looking at a few questions (like the one posted before and [this one](https://stackoverflow.com/questions/14088294/multithreaded-web-server-in-python) suggest that to be true.
score: 0
type: Comment

http://stackoverflow.com/q/49338210
upvote count: 1
has answer: http://stackoverflow.com/a/49338834
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85680627
has title: Efficient replacement of rows or columns of 2d arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/49338834
type: AnsweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85690353
has body: I need a lot of operations to replace parts of the array repeatedly, I hope there is an efficient way to avoid loops, because I found that 2d array slicing does not support write operations.So I constructed a simple function to achieve this goal. a = np.random.rand(4,4) b = np.random.rand(4) c = [1,1,1,1] def ravel_index(a,b,row_index,col_index,order='c'): rindex = row_index * a.shape[1] + col_index lindex = rindex + b.ravel().shape[0] return rindex,lindex f,l = ravel_index(a,b,1,0) a.ravel()[f:l]=c print (a) &gt;&gt;&gt;[[ 0.013631517 0.81654666 0.96975073 0.832641632] [ 1. 1. 1. 1. ] [ 0.092047737 0.149801674 0.322049501 0.162026284] [ 0.490197753 0.54935894 0.527087062 0.126544099]] It looks ideal now, But when trying to write in column direction.. f,l = ravel_index(a,b,1,0) a.ravel('F')[f:l]=c print (a) &gt;&gt;&gt;[[ 0.306372691 0.586445896 0.052487946 0.864993735] [ 0.873470159 0.762572666 0.986864265 0.803903923] [ 0.000208709 0.579103322 0.811386673 0.196167481] [ 0.928682626 0.707539068 0.752064295 0.564061717]] Obviously the array is copied, I don't know how to solve this problem, hope to get help Thank you
downvote count: 0

http://stackoverflow.com/a/49366925
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49366169
has body: You can filter all undesirable delimeters: import csv with open('filename.csv') as f: data = [int(i[-2]) for i in csv.reader(f) if len(i) &gt; 1 or i[0] != '\\N'] print(data) Output: [1375, 1376, 1162, 1594, 1595, 799]

http://stackoverflow.com/q/49392801
tagged with: pip
linked to: http://stackoverflow.com/q/22735496
has comment: http://stackoverflow.com/comment/85814140
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85787292
tagged with: python
has title: ModuleNotFoundError: No module named 'pyperclip' in spite of an installation
score: 0
has comment: http://stackoverflow.com/comment/85797446
tagged with: pyperclip
has answer: http://stackoverflow.com/a/73465195
has body: Windows 10, python 3.6.4 I get ModuleNotFoundError: No module named 'pyperclip' when i run a program. When I type pip list and pip freeze in command prompt pyperclip (1.6.0) is shown as installed. When I type pip install pyperclip in command prompt I get Requirement already satisfied: pyperclip in c:\python\lib\site-packages. Do you know how to fix this?
answer count: 1

http://stackoverflow.com/q/49286230
type: UnansweredQuestion
type: Question
tagged with: python
has body: def pascalstriangle(n): list = [1] for i in range(n): print(list) newlist = [] newlist.append(list[0]) for i in range(len(list) - 1): newlist.append(list[i] + list[i + 1]) newlist.append(list[-1]) list = newlist print(pascalstriangle(3)) I want to see this print format [1,1,1,1,2,1] instead of [1] [1, 1] [1, 2, 1]
score: 0
has title: How should I append all my results to one list after each iteration in the python?
answer count: 3
has answer: http://stackoverflow.com/a/49286309
has answer: http://stackoverflow.com/a/49286296
has answer: http://stackoverflow.com/a/49286422

http://stackoverflow.com/q/49380885
possible better answer: http://stackoverflow.com/a/49381456
has body: When using python-selenium and loading a web page I can get the source as follows: webdriver.page_source Is there a way to set the page source? I want to 'read' the html from a file and perform a location action on it, i.e. something like this: driver = webdriver.Firefox() driver.set_source(open('my_file.html')) driver.find_element((By.XPATH, "//div[@id='create']//input")) Is there a way to do this?
has comment: http://stackoverflow.com/comment/85762867
has answer: http://stackoverflow.com/a/49381456
answer count: 2
upvote count: 2
score: 1
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49381445
has answer: http://stackoverflow.com/a/49381445
has title: How to set the page source in python selenium?
tagged with: python

http://stackoverflow.com/a/49366463
has comment: http://stackoverflow.com/comment/85734249
answers question: http://stackoverflow.com/q/49366161
downvote count: 0
has comment: http://stackoverflow.com/comment/85733855
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49366161
has body: You can use a nested list comprehension, checking whether the current part contains a - and using either a range or creating a one-elemented list accordingly: &gt;&gt;&gt; s = "1-10, 20, 30, 40, 400-410" &gt;&gt;&gt; [n for part in s.split(", ") for n in (range(*map(int, part.split("-"))) if "-" in part else [int(part)])] [1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 40, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409] Maybe split this up, for readability: &gt;&gt;&gt; to_list = lambda part: range(*map(int, part.split("-"))) if "-" in part else [int(part)] &gt;&gt;&gt; [n for part in s.split(", ") for n in to_list(part)] Note: As in your first example, this will translate "1-10" to [1, 2, ..., 9], without 10. As noted in comments, this will not work for negative numbers, though, trying to split -3 or -4--2 into pairs of numbers. For this, you could use regular expressions... &gt;&gt;&gt; def to_list(part): ... m =re.findall(r"(-?\d+)-(-?\d+)", part) ... return range(*map(int, m[0])) if m else [int(part)] ... &gt;&gt;&gt; s = "-10--5, -4, -2-3" &gt;&gt;&gt; [n for part in s.split(", ") for n in to_list(part)] [-10, -9, -8, -7, -6, -4, -2, -1, 0, 1, 2] ... or just use a different delimiter for ranges, e.g. -10:-5.
has comment: http://stackoverflow.com/comment/85734331
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85580939
comment on: http://stackoverflow.com/a/49288150
type: Comment
has text: What changes were made? Why?
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85703585
has text: @abarnert I'm the one sending it in to the API so I know that it's a JPEG file.
type: QuestionComment
comment on: http://stackoverflow.com/q/49345303
type: Comment
score: 0

http://stackoverflow.com/comment/85743415
type: QuestionComment
has text: @Aran-Fey yes, I edited my question. Without writing something into the file, I'll get an output.
comment on: http://stackoverflow.com/q/49371170
score: 0
type: Comment

http://stackoverflow.com/comment/85818764
type: AnswerComment
has text: ahh..yes had been looking into celery. I did just add a post_save signal to my user model, to add a user to the mailchimp list..and it appears to be working for all of my signups (normal + facebook) see any issues doing it that way? `@receiver(post_save, sender=User) def send_sub(sender, **kwargs): if kwargs.get('created', True): email = kwargs.get('instance').email SendSubscribeMail(email)`
type: Comment
comment on: http://stackoverflow.com/a/49397674
score: 0

cookiecutter
tags question: http://stackoverflow.com/q/49389440
tag name: cookiecutter
type: Tag

http://stackoverflow.com/q/49309446
has answer: http://stackoverflow.com/a/74079828
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49309553
tagged with: error-handling
possible better answer: http://stackoverflow.com/a/49309533
has answer: http://stackoverflow.com/a/49309522
answer count: 4
has body: So I have a function like: def my_code(arg1, *args): .... And I want this function to only be able to take either 2 or 3 arguments (that means *args can only be 1 or 2 arguments). How do I throw an error message if the number of arguments is wrong? If I use a try/exception, is there a specific exception type for this?
has answer: http://stackoverflow.com/a/49309533
favorite count: 0
type: Question
tagged with: try-catch
has comment: http://stackoverflow.com/comment/85621011
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85621086
tagged with: exception
tagged with: python
accepted answer: http://stackoverflow.com/a/49309522
has comment: http://stackoverflow.com/comment/85621054
linked to: http://stackoverflow.com/q/251464
type: AnsweredQuestion
downvote count: 0
has title: Python - Wrong number of arguments exception?

http://stackoverflow.com/comment/85690644
type: QuestionComment
comment on: http://stackoverflow.com/q/49345303
type: Comment
has text: is the request body true binary? then you should be able to pass the binary data straight through. If its base64 encoded or otherwise passed in as some kind of string you will have to do some extra decoding
score: 0

testing
tags question: http://stackoverflow.com/q/49361114
type: Tag
tags question: http://stackoverflow.com/q/49387217
tag name: testing
tags question: http://stackoverflow.com/q/49290243
tags question: http://stackoverflow.com/q/49341357
tags question: http://stackoverflow.com/q/49396918
tags question: http://stackoverflow.com/q/49352674
tags question: http://stackoverflow.com/q/49300192
tags question: http://stackoverflow.com/q/49372642
tags question: http://stackoverflow.com/q/49332935
tags question: http://stackoverflow.com/q/49325478
tags question: http://stackoverflow.com/q/49378459
tags question: http://stackoverflow.com/q/49306177

http://stackoverflow.com/comment/86119703
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49397019
score: 0
has text: @UbdusSamad no. I don't know why the error is happening though.

http://stackoverflow.com/a/49406809
answers question: http://stackoverflow.com/q/49404485
has body: Switch between self.hide() and self.showMinimized() def start(self): window = MainWindow(self) window.show() self.showMinimized()
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/85734427
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49366786
has text: I have modified as content = [x.split(',') for x in content] , but in result is [['Mary', 'F', '9889\n'], ['Anna', 'F', '4283\n'],... extra to be avoided \n ?

http://stackoverflow.com/q/49434120
tagged with: regex
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49436091
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85870347
tagged with: string
has title: Python: Extract function with Pandas column ignoring regex that i've verified on regexr.com
favorite count: 0
type: Question
tagged with: geocode
type: UnansweredQuestion
has body: I have a column in a pandas data table that contains a string with the city and coordinates. I want to extract the coordinates It should be a relatively simple exercise: Here is the code that i'm using to do the extract: p = r'(?P&lt;latitude&gt;-?\d+\.\d+).*?(?P&lt;longitude&gt;-?\d+\.\d+)' data'latitude', 'longitude' = data['geocode_result'].str.extract(p, expand=True) data But as you can see from my column, in the screenshot, it's listing NaN Here is the regex being verified that it's capturing: Am I missing something obvious? I just want to grab the coordinates from geocode_result Thanks
tagged with: python

http://stackoverflow.com/a/77193765
has body: As mentionned in the answer by DeepSpace, the --system-site-packages flag will grant the created virtual environment access to the system-wide site-packages directory. If the virtual environment has been created, go to $HOME/.venv/[name_of_your_environment]/pyvenv.cfg and change the line include-system-site-packages = false to include-system-site-packages = true, to enable access to packages installed in the base environment.
answers question: http://stackoverflow.com/q/49364776
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/85749721
type: QuestionComment
has text: Code in a comment is unreadable. Edit your question, or answer it if you solved it.
comment on: http://stackoverflow.com/q/49366352
score: 0
type: Comment

http://stackoverflow.com/a/49284330
type: Answer
has body: I think you can try this code: directory = r'path to the directory' from os import walk f = [] #to list the files d = [] # to list the directories for (dirpath, dirnames, filenames) in walk(directory): f.extend(filenames) d.extend(dirnames) break if len(f) and len(d) != 0: print('Not empty') else: print('empty')
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/49284015
score: 1

http://stackoverflow.com/comment/134830641
type: QuestionComment
has text: I wrote [this library](https://github.com/aplbrain/grand-cypher) to aid in writing tests that use Cypher syntax to query an in-memory graph. Hopefully helpful to some!
comment on: http://stackoverflow.com/q/49348839
type: Comment
score: 0

http://stackoverflow.com/q/49378655
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85758460
favorite count: 0
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85758704
has comment: http://stackoverflow.com/comment/85758568
has title: Fastest way to open and deal with a URL in a web browser in Python
has comment: http://stackoverflow.com/comment/85758518
tagged with: python
upvote count: 4
score: 4
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85758371
has answer: http://stackoverflow.com/a/49379304
accepted answer: http://stackoverflow.com/a/49379304
answer count: 1
has body: Using Selenium package I am trying to open a URL in a browser. The browser can be Firefox or Google. Given URL is redirected to some other URL and the browser has to wait for this until its URL gets changed. Here's the code I'm using: import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait starttime = time.time() browser = webdriver.Firefox(executable_path='\\somepath\\chromedriver.exe') browser.get("http://patft.uspto.gov/netacgi/nph-Parser?patentnumber=3,930,293") wait = WebDriverWait(browser, 5) wait.until(lambda driver: browser.current_url !=patent ) url = browser.current_url r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') for tag in soup.find_all(text=re.compile('Current U.S. Class:')): table = tag.findParent('table') result = table.find('tr').text browser.close() print(result) # Current U.S. Class: 29/428 print(time.time() - starttime) But this takes too much time (like 18 to 20 seconds) and I have a huge dataset of these URLs to work on. Is there any faster way to do this task?
downvote count: 0

http://stackoverflow.com/comment/85875162
comment on: http://stackoverflow.com/q/49436330
score: 0
has text: There is a lot of code here not related to your problem. Please provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/128049157
type: AnswerComment
comment on: http://stackoverflow.com/a/51168005
has text: It's not very clear, can you add some tree structure please ?
type: Comment
score: 0

http://stackoverflow.com/q/49298808
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49316005
accepted answer: http://stackoverflow.com/a/49316005
favorite count: 0
possible better answer: http://stackoverflow.com/a/49299018
type: Question
has comment: http://stackoverflow.com/comment/85603126
tagged with: dry
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49304839
has body: For example I have 2 main models in my django app: class Employee(Model): name = CharField(max_length=50) class Client(Model): title = CharField(max_length=50) Abstract base class for phones: class Phone(Model): number = CharField(max_length=10) class Meta: abstract = True Inherited separate classes for Employee and for Client: class EmployeePhone(Phone): employee = ForeignKey(Employee, on_delete=CASCADE, related_name='employee_phones') class ClientPhone(Phone): client = ForeignKey(Client, on_delete=CASCADE, related_name='client_phones') It works but I don't like it, I would prefer to keep just one Phone model instead of 3. I know I could use Generic-Models but unfortunately that's not longer an option, because my app is actually REST-API and it seems to be impossible to create Generic-Object while creating Parent-Object. So is there any solution to keep things clean and DRY ?
has comment: http://stackoverflow.com/comment/85599457
has title: How to keep DRY while creating common models in Django?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49299018

http://stackoverflow.com/comment/86508028
type: QuestionComment
has text: How about creating several scripts and let them run in parallel? So I start multiple scripts from python and wait till they are finished. Through that each python script would have its own session?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49402203

http://stackoverflow.com/q/49352528
has answer: http://stackoverflow.com/a/49353054
tagged with: python
upvote count: 4
answer count: 2
has body: To speed up some operations I transfered image to GPU memory. After some processing I have to crop some area: image = cv2.UMat(image) ... crop = image[y1:y2,x1:x2] The problem is that it is not possible to slice image inside GPU memory. Above code will raise error: "UMat object is not subscriptable". The solution I found is to transfer image back to numpy object, than slice it, and transfer back to GPU: image = cv2.UMat(image) ... image = image.get() crop = image[y1:y2,x1:x2] crop = cv2.UMat(crop) ... But above solution looks costly, as transferring data to/from GPU memory takes time. I have a feeling that there is a way to crop an image within GPU memory. Any hints?
has answer: http://stackoverflow.com/a/58390497
accepted answer: http://stackoverflow.com/a/49353054
downvote count: 0
possible better answer: http://stackoverflow.com/a/58390497
score: 4
favorite count: 0
type: Question
tagged with: opencv
type: AnsweredQuestion
tagged with: opencl
tagged with: gpu
has title: opencv: crop image on the GPU side

http://stackoverflow.com/comment/85618041
comment on: http://stackoverflow.com/a/49307676
type: Comment
has text: @user9453545 It is not necessary to use the layouts, I only did it to have an order in my example, in a few moments I will publish using your template.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85789959
type: Comment
score: 0
has text: @SFTP The number of boolean symbols is about 60, the length of the string is 9903 characters. I can try to come up with a unit test to reproduce the problem if you think it will help.
type: QuestionComment
comment on: http://stackoverflow.com/q/49393692

http://stackoverflow.com/comment/85579132
type: QuestionComment
has text: You don't have an issue with within this code. Try `print (scraped_data[0]) `you'll see the issue there. Your data is not being properly parsed. Take care!
score: 0
comment on: http://stackoverflow.com/q/49287747
type: Comment

http://stackoverflow.com/a/49330744
accepted answer of: http://stackoverflow.com/q/49330708
upvote count: 8
has body: You could also leverage the "truthiness" of non-zero values in an array. np.sum(~array.any(1)) i.e., sum the rows where none of the values in said row are truthy (and hence are all zero)
type: Answer
score: 8
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49330708

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/49402881
tags question: http://stackoverflow.com/q/49379399
tag name: python-packaging
tags question: http://stackoverflow.com/q/49372219

http://stackoverflow.com/q/49366352
has body: I'm very much a beginner. This generates the "right" data off the URL, but when I try to generate a CSV file, the resultant Excel file is empty. This is the code ... import csv import urllib.request from bs4 import BeautifulSoup f = open('dataoutput.csv', 'w', newline = "") writer = csv.writer(f) soup = BeautifulSoup(urllib.request.urlopen("https://www.rjobrien.co.uk/tools/quoteresult/symbol/FGBLM8").read(), 'lxml') tbody = soup('table', {"class": "table table-bordered table-condensed"})[0].find_all('tr') for row in tbody: cols = row.findChildren(recursive=False) cols = [ele.text.strip() for ele in cols] writer.writerow(cols)
tagged with: python
has comment: http://stackoverflow.com/comment/85739496
score: 0
has answer: http://stackoverflow.com/a/49366636
answer count: 2
has answer: http://stackoverflow.com/a/49366800
has title: Generate data using Python and export to excel file
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/85742311
has comment: http://stackoverflow.com/comment/85749721
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/85742282
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/49305991
tagged with: datetime
has answer: http://stackoverflow.com/a/49306062
tagged with: python
accepted answer: http://stackoverflow.com/a/49306062
has body: I have a dataframe with multiple datetime index like I would like to split data_value_index into three columns with the same index. So far I have only separated the dataframe and merge it like df1= df[df['data_value_index']==5] df2= df[df['data_value_index']==9] df3 = df[df['data_value_index']==14] df=pd.merge(df1,df2,left_index=True,right_index=True) Is there any simpler way to do it?
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: Repeated datetime index pandas
type: Question

http://stackoverflow.com/q/49287627
has body: I have a Python 3.6.4 program on windows which uses a configuration file, config.py, to define global variables, as well as the main.py script which does other stuff. My config.py contains a string named "variable" with "value" as its value: # config.py global variable variable = "value" If I import all variables in main.py and try to print(variable), it works fine. But if I try: variable AFTERWARDS, then it fails on the first print(variable). Sorry for the long code, I tried to reproduce the issue with smaller pieces of code and it worked fine, which really confuses me: # main.py import argparse, logging, sys from config import * def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', help="Rapporter davantage d'information.") parser.add_argument('-l', '--journal', action='store', default=None, help="Spécifier le nom du journal.") parser.add_argument('--csv', action="store_true", help="Exporter les résultats vers un fichier de sortie CSV.") args = parser.parse_args() # Configuration du journal log_frmt = "%(asctime)s[%(levelname)s] %(message)s" date_frmt = "%Y-%m-%d %H:%M:%S " if args.verbose: log_lvl = logging.DEBUG else: log_lvl = logging.INFO logging.basicConfig(filename=args.journal, format=log_frmt, datefmt=date_frmt, level=log_lvl) logging.info(f"Journal initié : {args.journal}") if args.csv: print(variable) sys.exit() #try: #print(variable) #variable #logging.debug(f"variable = {variable}") #sys.exit() #except NameError: #variable = None #logging.warning("variable non-défini, initialisé à None") #sys.exit() if __name__ == '__main__': main() The output is: $ python main.py --csv 2018-03-14 16:44:20 [INFO] Journal initié : None value ...which is what you'd expect. But if I uncomment the last part, AFTER sys.exit(): ... logging.info(f"Journal initié : {args.journal}") if args.csv: print(variable) sys.exit() try: print(variable) variable logging.debug(f"variable = {variable}") sys.exit() except NameError: variab…
has comment: http://stackoverflow.com/comment/85581635
has title: Why future code cause NameError in Python
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85578337
tagged with: python
duplicate of: http://stackoverflow.com/q/370357
tagged with: nameerror
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/41369408

http://stackoverflow.com/a/49406652
has comment: http://stackoverflow.com/comment/85863406
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49351121
has comment: http://stackoverflow.com/comment/85815464
answers question: http://stackoverflow.com/q/49351121
has comment: http://stackoverflow.com/comment/85863326
has body: I would recommend against your design as it's quite error prone. Better solutions would de-couple the workers from the server using some sort of queuing system (RabbitMQ, Celery, Redis, ...). Nevertheless, here's a couple of "hacks" you could try out. Turn your child processes into UNIX daemons. The python daemon module could be a starting point. Instruct your child processes to ignore the SIGINT signal. The service orchestrator might work around that by issuing a SIGTERM or SIGKILL signal if child processes refuse to die. You might need to disable such feature. To do so, just add the following line at the beginning of the function_wrapper function: signal.signal(signal.SIGINT, signal.SIG_IGN)
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/85815012
upvote count: 4

http://stackoverflow.com/a/49344529
downvote count: 0
has body: Had trouble getting boto to work but I upgraded to boto3 and it works fine now. Here's the code: img = request.FILES.get('image') session = boto3.Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, ) s3 = session.resource('s3') s3.Bucket('my-bucket').put_object(Key='media/%s' % img.name, Body=img) return HttpResponse() This successfully uploads the image to my bucket during the AJAX call.
accepted answer of: http://stackoverflow.com/q/49332470
upvote count: 8
type: Answer
score: 8
answers question: http://stackoverflow.com/q/49332470
type: AcceptedAnswer

http://stackoverflow.com/comment/85688517
type: AnswerComment
has text: I found out that the `Maximum allowed requests per second` is 20. Link : http://www.questrade.com/api/documentation/rate-limiting. How could I increase the performance of the last `for` loop without losing data?
type: Comment
comment on: http://stackoverflow.com/a/49343402
score: 0

http://stackoverflow.com/comment/85693194
type: AnswerComment
has text: the output should also contain user_id '3' since this user has 3 logins between '2013-01-04' and '2013-01-11' which is a 7 day period, however, it should not contain user_id '4' since it is more than 7 days
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49346070

mongoengine
tags question: http://stackoverflow.com/q/49390825
tags question: http://stackoverflow.com/q/49414253
tags question: http://stackoverflow.com/q/49394201
tag name: mongoengine
tags question: http://stackoverflow.com/q/49405648
type: Tag
tags question: http://stackoverflow.com/q/49305293

http://stackoverflow.com/comment/85842632
has text: It says that if you have a string, but according to the example value in your question, you don't have a string, you have bytes. Iterating over bytes yields integers. Are you sure you're opening the file in binary mode? And you are using Python 3+, right?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49419002

http://stackoverflow.com/q/49282955
has title: Center matplotlib colormap on a specific value
has answer: http://stackoverflow.com/a/49283519
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
score: 2
upvote count: 2
downvote count: 0
answer count: 1
has body: I'm making plots using matplotlib colormap "seismic" and would like to have the white color centered on 0. When I run my script with no changes, white falls from 0 to -10. I tried then setting vmin=-50, vmax=50 but I completely lose the white in that case. Any suggestions on how to accomplish that? from netCDF4 import Dataset as NetCDFFile import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.basemap import Basemap nc = NetCDFFile('myfile.nc') lat = nc.variables['lat'][:] lon = nc.variables['lon'][:] time = nc.variables['time'][:] hgt = nc.variables['hgt'][:] map = Basemap(llcrnrlon=180.,llcrnrlat=0.,urcrnrlon=320.,urcrnrlat=80.) lons,lats = np.meshgrid(lon,lat) x,y = map(lons,lats) cs = map.contourf(x,y,hgt[0],cmap='seismic') cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5, cmap='seismic') cbar.set_label('500mb Geopotential Height Anomalies(m)') map.drawcoastlines() map.drawparallels(np.arange(20,80,20),labels=[1,1,0,0], linewidth=0.5) map.drawmeridians(np.arange(200,320,20),labels=[0,0,0,1], linewidth=0.5) plt.show() Plot with defaults: Plot with vmin, vmax set:
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: colormap

http://stackoverflow.com/a/49320838
type: Answer
has body: Loops in Python usually don't use i very much. Try this: table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']] watcher = {} for x in table: for movie in x[1:]: watcher_for_movie = watcher.get(movie, []) watcher_for_movie.append(x[0]) watcher[movie] = watcher_for_movie print(watcher) Output: {'EXOTIC SPACE': [1, 20], 'CRIMSON PEAK': [4], 'MINIONS': [4], 'SUPERMAN': [4], 'FANTASTIC FOUR': [1, 20]}
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49320727
score: 1

http://stackoverflow.com/a/49372985
score: 0
type: Answer
has body: you can add a validation like this:` def exist(file_name, link): with open(file_name) as tmp: for line in tmp: if link in line: return True return False with open("ClientList.txt", "r") as infile: with open("output.txt", "a") as outfile: for line in infile: if not exist('output.txt',line): outfile.write("".join(["clients name: ",line.strip(), ", clients URL: ", line.strip(), ", service: VIP\n"])) ` even closing and opening the file every time may not be a good idea, you could modify the function so that you maintain the reference to the file and you only have to move the pointer at the beginning and start the search one more time, you could also have all the content in memory and perform a search there directly, but that work will be your decision
answers question: http://stackoverflow.com/q/49372772

http://stackoverflow.com/a/49298077
type: Answer
answers question: http://stackoverflow.com/q/49297836
has comment: http://stackoverflow.com/comment/85654817
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: There are many ways you can get the text you want. Using .contents property You can use .contents to get the required content from a tag. If you check the contents of the div tag (print(soup.div.contents)), you'll get this output: ['\n', எனது நாடகவாழ்க்கை.pdf, '\n 819 × 1,236, 569 pages; 39.7 MB', , '\n'] From here, you can see that the required content is available in the 3rd position (2nd index). To get that, you can use this: html = ''' எனது நாடகவாழ்க்கை.pdf 819 × 1,236, 569 pages; 39.7 MB ''' soup = BeautifulSoup(html, 'lxml') print(soup.find('div').contents[2].strip()) # 819 × 1,236, 569 pages; 39.7 MB Using NavigableString info = ''.join([x.strip() for x in soup.find('div').contents if isinstance(x, NavigableString)]) print(info) # 819 × 1,236, 569 pages; 39.7 MB Don't forget to import this as from bs4 import BeautifulSoup, NavigableString Using .next_sibling property And another way, is to use the . a_tag = soup.find('div').a print(a_tag) # எனது நாடகவாழ்க்கை.pdf info = a_tag.next_sibling print(info.strip()) # 819 × 1,236, 569 pages; 39.7 MB EDIT: Using any one of the above techniques, you can get the content you want. All the PDFs are located inside a tag. Complete code: r = requests.get(u'https://commons.wikimedia.org/wiki/Category:அவ்வை தி. க. சண்முகம்') soup = BeautifulSoup(r.content, 'lxml') for item in soup.find_all('div', class_='gallerytext'): a_tag = item.a print(a_tag['title']) # or print(a_tag['href']) if you want the link info = a_tag.next_sibling.strip() print(info) Output: File:எனது நாடகவாழ்க்கை.pdf 819 × 1,236, 569 pages; 39.7 MB File:தமிழ் நாடகத் தலைமை ஆசிரியர்-1.pdf 637 × 957, 40 pages; 3.61 MB File:தமிழ் நாடகத் தலைமை ஆசிரியர்-2.pdf 612 × 963, 67 pages; 9.32 MB File:நாடகக்கலை-1.pdf 639 × 996, 161 pages; 6.35 MB File:நாடகக்கலை-2.pdf 673 × 954, 155 pages; 7.22 MB File:நாடகச்சிந்தனைகள்.pdf 715 × 1,047, 133 pages; 5.17 MB
has comment: http://stackoverflow.com/comment/85654251
accepted answer of: http://stackoverflow.com/q/49297836
score: 1

http://stackoverflow.com/q/49423770
downvote count: 0
has title: matplotlib.widgets.TextBox: change color
accepted answer: http://stackoverflow.com/a/49425848
has answer: http://stackoverflow.com/a/49425848
type: AnsweredQuestion
tagged with: colors
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85849276
has body: Is there a way to change TextBox text color at any moment? I tried Google already; my question looks too trivial, but I am still at a loss. TextBox methods: : dir(matplotlib.widgets.TextBox) Out[63]: [ ... 'active', 'begin_typing', 'connect_event', 'disconnect', 'disconnect_events', 'drawon', 'eventson', 'get_active', 'ignore', 'on_submit', 'on_text_change', 'position_cursor', 'set_active', 'set_val', 'stop_typing'] AxesWidget superclass methods: : dir(matplotlib.widgets.AxesWidget) Out[64]: [ ... 'active', 'connect_event', 'disconnect_events', 'drawon', 'eventson', 'get_active', 'ignore', 'set_active'] Nothing suggestive. At least, to my eye.
favorite count: 0
type: Question
upvote count: 2
tagged with: widget
score: 2
answer count: 1

http://stackoverflow.com/a/49389444
has body: Check out this post, it's explains the PYTHONPATH variable. How to use PYTHONPATH and the documentation the answer points to https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH When you run from the data directory by default python can't find your tools directory. Also regarding your comment about needing to run from the data directory, you could just use open('../data/file.txt') if you decided to run from the main directory instead. Ideally, you should be able to run your script from anywhere though. I find this snippet very useful os.path.dirname(sys.argv[0]). It returns the directory in which the script exists.
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49389107

http://stackoverflow.com/q/49339423
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/49339494
answer count: 3
has comment: http://stackoverflow.com/comment/85679070
has answer: http://stackoverflow.com/a/49339494
has comment: http://stackoverflow.com/comment/85678967
downvote count: 1
favorite count: 0
has title: Taking a list, comparing values, creating dictionary with several keys
type: Question
possible better answer: http://stackoverflow.com/a/49339492
has comment: http://stackoverflow.com/comment/85679069
has answer: http://stackoverflow.com/a/49339492
tagged with: python
tagged with: dictionary
score: -1
tagged with: list
has body: I am trying to take a list that has IP address and port numbers and print the data out to be in this format 127.0.0.1:21,80,443. Here is a sample of dummy data. 127.0.0.1 80 127.0.0.1 443 192.168.1.1 21 192.168.1.2 22 192.168.1.2 3389 192.168.1.2 5900 I would like this data to output as stated above. Right now, I have the data in a list and am looking to associate the ports with the IP addresses so it is not repeating the IP address to each port. This data should output to: 127.0.0.1:80,443 192.168.1.1:21 192.168.1.2:22,3389,5900
has answer: http://stackoverflow.com/a/49339824

http://stackoverflow.com/q/49362931
has answer: http://stackoverflow.com/a/62959499
type: UnansweredQuestion
has title: Spell correction using Keras RNN in python
has body: I am doing spell correction using RNN, Below is the code I am using from __future__ import print_function, division, unicode_literals import os import errno from collections import Counter from hashlib import sha256 import re import json import itertools import logging import requests import numpy as np import pandas as pd from numpy.random import choice as random_choice, randint as random_randint, shuffle as random_shuffle, seed as random_seed, rand from numpy import zeros as np_zeros # pylint:disable=no-name-in-module from keras.models import Sequential, load_model from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Dropout, recurrent from keras.callbacks import Callback # Set a logger for the module LOGGER = logging.getLogger(__name__) # Every log will use the module name LOGGER.addHandler(logging.StreamHandler()) LOGGER.setLevel(logging.DEBUG) random_seed(123) # Reproducibility class Configuration(object): """Dump stuff here""" CONFIG = Configuration() #pylint:disable=attribute-defined-outside-init # Parameters for the model: CONFIG.input_layers = 2 CONFIG.output_layers = 2 CONFIG.amount_of_dropout = 0.2 CONFIG.hidden_size = 500 CONFIG.initialization = "he_normal" # : Gaussian initialization scaled by fan-in (He et al., 2014) CONFIG.number_of_chars = 100 CONFIG.max_input_len = 20 CONFIG.inverted = True # parameters for the training: CONFIG.batch_size = 100 # As the model changes in size, play with the batch size to best fit the process in memory CONFIG.epochs = 500 # due to mini-epochs. CONFIG.steps_per_epoch = 1000 # This is a mini-epoch. Using News 2013 an epoch would need to be ~60K. CONFIG.validation_steps = 10 CONFIG.number_of_iterations = 10 dataset=pd.read_csv("input_spell.csv") input_data=dataset['input'].tolist() input_data1=str(input_data) output_data=dataset['output'].tolist() output_data1=str(output_data) chars=list("abcdefghijklmnopqrstuvwxyz") MIN_INPUT_LEN = 1 AMOUNT_OF_NOISE = 0.2 / CONFIG.max_input_len CHARS = list("abcdef…
tagged with: python
has answer: http://stackoverflow.com/a/52236855
has comment: http://stackoverflow.com/comment/111234724
tagged with: lstm
answer count: 2
tagged with: spell-checking
has comment: http://stackoverflow.com/comment/85742633
score: 1
downvote count: 0
upvote count: 1
tagged with: recurrent-neural-network
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85761445

http://stackoverflow.com/q/49303305
type: UnansweredQuestion
answer count: 1
tagged with: trepan
score: 0
has answer: http://stackoverflow.com/a/49329067
tagged with: python
has body: I was initially very impressed by some of the advanced features of the trepan2 debugger. But it does not appear to have any command to list breakpoints. That seems like a bizarre oversight. Does anyone know is there a command to list the breakpoints for the trepan2 debugger. I have trepan2 v0.8.4
has title: Is it possible to list breakpoints with trepan2 python debugger?
type: Question
tagged with: debugging

http://stackoverflow.com/q/49296737
type: UnansweredQuestion
tagged with: function
has comment: http://stackoverflow.com/comment/85595995
has comment: http://stackoverflow.com/comment/85595348
has answer: http://stackoverflow.com/a/49298703
downvote count: 5
tagged with: python
score: -5
tagged with: syntax
upvote count: 0
has title: invalid syntax in Python function
linked to: http://stackoverflow.com/q/15291500
answer count: 1
has body: [joepareti54@xxx build]$ ./manta ../scenes/_trainingData.py --dim 3 --addModelGeometry True --addSphereGeometry True Version: mantaflow 64bit fp1 commit dd3bb0c0a65cc531d3c33487bde5edcb4aa6784f from Mar 14 2018, 14:53:44 Loading script '../scenes/_trainingData.py' Traceback (most recent call last): File "../scenes/_trainingData.py", line 12, in &lt;module&gt; from Emitter import * File "/home/joepareti54/FluidNet/manta/scenes/Emitter.py", line 15, in &lt;module&gt; import matlabnoise File "/home/joepareti54/FluidNet/manta/build/../../../matlabnoise/matlabnoise.py", line 81 def Perlin2D(*args) -&gt; "double" : ^ SyntaxError: invalid syntax I believe the invalid syntax occurs in: def Perlin2D(*args) -&gt; "double" :`enter code here` return _matlabnoise.Perlin2D(*args) Perlin2D = _matlabnoise.Perlin2D
favorite count: 0
type: Question

http://stackoverflow.com/a/49368108
score: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/85737631
has comment: http://stackoverflow.com/comment/85738156
has body: Simply a list comprehension with split will do: s = "Wheresoever you go, go with all your heart" print(' '.join([word for word in s.split() if word[0].lower() &gt; 'g'])) # Wheresoever you with your heart Modifying to match with the desired output (Making all uppercase and on new lines): s = "Wheresoever you go, go with all your heart" print('\n'.join([word.upper() for word in s.split() if word[0].lower() &gt; 'g'])) ''' WHERESOEVER YOU WITH YOUR HEART ''' Without list comprehension: s = "Wheresoever you go, go with all your heart" for word in s.split(): # Split the sentence into words and iterate through each. if word[0].lower() &gt; 'g': # Check if the first character (lowercased) &gt; g. print(word.upper()) # If so, print the word all capitalised.
type: Answer
has comment: http://stackoverflow.com/comment/85751666
upvote count: 4
has comment: http://stackoverflow.com/comment/85738000
answers question: http://stackoverflow.com/q/49367942

http://stackoverflow.com/q/49332306
linked to: http://stackoverflow.com/q/48045412
tagged with: python
answer count: 0
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
has body: I tried selenium in Python to open a Google page, however, instead of loading the page, the Firefox browser keeps telling me the Accessibility issue. I followed the instruction to change the settings but can not find it! Besides, I found a solution to a similar problem - Webdriver.get(url) open Firefox but not the URL, but after I linked geckodriver, the Accessibility problem is till there. Could someone please help? Tens of Thanks in advance!!!!! from selenium import webdriver driver = webdriver.Firefox(executable_path=r'path\geckodriver.exe') driver.get('http://www.google/com') Screenshot - Accessibility issue Screenshot - Firefox instruction Screenshot - Can not find the setting
favorite count: 0
type: Question
has title: Python Selenium Firefox Accessibility issue
type: UnansweredQuestion

http://stackoverflow.com/q/49372619
has comment: http://stackoverflow.com/comment/85752136
accepted answer: http://stackoverflow.com/a/49375587
has comment: http://stackoverflow.com/comment/85752175
answer count: 4
score: 8
type: Question
has answer: http://stackoverflow.com/a/49375587
has comment: http://stackoverflow.com/comment/85752165
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49377135
has body: I set numpy random seed at the beginning of my program. During the program execution I run a function multiple times using multiprocessing.Process. The function uses numpy random functions to draw random numbers. The problem is that Process gets a copy of the current environment. Therefore, each process is running independently and they all start with the same random seed as the parent environment. So my question is how can I share the random state of numpy in the parent environment with the child process environment? Just note that I want to use Process for my work and need to use a separate class and do import numpy in that class separately. I tried using multiprocessing.Manager to share the random state but it seems that things do not work as expected and I always get the same results. Also, it does not matter if I move the for loop inside drawNumpySamples or leave it in main.py; I still cannot get different numbers and the random state is always the same. Here's a simplified version of my code: # randomClass.py import numpy as np class myClass(self): def __init__(self, randomSt): print ('setup the object') np.random.set_state(randomSt) def drawNumpySamples(self, idx) np.random.uniform() And in the main file: # main.py import numpy as np from multiprocessing import Process, Manager from randomClass import myClass np.random.seed(1) # set random seed mng = Manager() randomState = mng.list(np.random.get_state()) myC = myClass(randomSt = randomState) for i in range(10): myC.drawNumpySamples() # this will always return the same results Note: I use Python 3.5. I also posted an issue on Numpy's GitHub page. Just sending the issue link here for future reference.
downvote count: 0
has answer: http://stackoverflow.com/a/67162498
has comment: http://stackoverflow.com/comment/85752253
tagged with: scipy
favorite count: 0
possible better answer: http://stackoverflow.com/a/49372952
tagged with: multiprocessing
type: AnsweredQuestion
upvote count: 8
has answer: http://stackoverflow.com/a/49372952
has comment: http://stackoverflow.com/comment/85758395
has comment: http://stackoverflow.com/comment/85752296
has title: How to share numpy random state of a parent process with child processes?
tagged with: python

http://stackoverflow.com/a/49423144
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You can read all, store all in a list, reverse all and take first 10 lines that contain ,Kes your approach - takes lots of storage and time use Kasramvd's approach wich is francly far more elegant then this one - leveraging iterable and islice read each line yourself and check if ,Kes in it, if so queue it: from collections import deque # create demodata with open ("filename","w") as f: for n in range (20): for p in range(20): f.write("some line {}-{}\n".format(n,p)) f.write("some line with {} ,Kes \n".format(n)) # read demodata q = deque(maxlen=10) with open("filename") as f: for line in f: # read one line at time, not huge file at once if ',Kes' in line: # only store line if Kes in it q.append(line) # append line, size limit will make sure we store 10 at most # print "remebered" data print(list(q)) Output: ['some line with 10 ,Kes \n', 'some line with 11 ,Kes \n', 'some line with 12 ,Kes \n', 'some line with 13 ,Kes \n', 'some line with 14 ,Kes \n', 'some line with 15 ,Kes \n', 'some line with 16 ,Kes \n', 'some line with 17 ,Kes \n', 'some line with 18 ,Kes \n', 'some line with 19 ,Kes \n'] You will not have the whole file in RAM at once as well, at most 11 lines (curr line + deque holding 10 lines and it only remembers lines with ,Kes in it.
accepted answer of: http://stackoverflow.com/q/49422745
answers question: http://stackoverflow.com/q/49422745
downvote count: 0

http://stackoverflow.com/a/49339998
downvote count: 0
type: AcceptedAnswer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49331545
type: Answer
has body: Use the deriv method on the object you get back from np.poly1d: import numpy as np p = np.poly1d([1, 3, 1, 0, 4]) print(p) print(p.deriv(1)) See the docs for a full list of available methods.
answers question: http://stackoverflow.com/q/49331545
score: 2

http://stackoverflow.com/a/49311725
answers question: http://stackoverflow.com/q/49311592
has body: Since you are in AWS already, it may be easier to just store your data files in s3, and open them directly from there.
type: Answer
score: 0

http://stackoverflow.com/comment/85708886
has text: I ran it just now (copied-pasted from my post), where do you see an error? `return_nums` just returns 1, 2, 3, 4.. so we know what `keys` are for the next function.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49354090
type: AnswerComment

http://stackoverflow.com/comment/86097930
score: 0
type: AnswerComment
has text: Ah, ok. I've added some additional debugging code to cx_Oracle. Would you be able to build cx_Oracle using the latest source code on GitHub and then retry the code that failed?
comment on: http://stackoverflow.com/a/49516977
type: Comment

http://stackoverflow.com/comment/86013058
type: Comment
type: QuestionComment
has text: @RickJames I'm building a CSV with 500k rows. The construction of the CSV and writing the CSV to disk takes less than 0.5 seconds (tested). I do not know the value of `innodb_buffer_pool_size` because I do not have admin rights on the database. If I can read this value without admin rights, let me know how and I can answer that question. There are currently 17 partitions. I plan on only ever having 17 (I delete a partition whenever I make a new one). `time` is added to the DataFrame on the 9th line of the Python code, and the CSV is built from the DataFrame. Other questions?
comment on: http://stackoverflow.com/q/49327363
score: 0

http://stackoverflow.com/q/49296824
has answer: http://stackoverflow.com/a/49296842
type: AnsweredQuestion
has body: I have a dataframe id|number 1|1 1|0 1|1 I want the total sum of number in a new column like: id|number|sum 1|1|2 1|0|2 1|1|2 I am using : df['sum'] = df['number'].sum() but got the output as : id|number|sum 1|1|101 1|0|101 1|1|101
tagged with: pandas
score: 1
answer count: 1
has title: Pandas total sum over rows
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49296842

http://stackoverflow.com/comment/85786317
type: QuestionComment
score: 0
has text: Yes your code may not contain errors but your final exectables will. Try running it through terminal (Terminal on Linux and Mac, cmd on Windows) and not the IDLE and you should see some form of message.
comment on: http://stackoverflow.com/q/49371614
type: Comment

http://stackoverflow.com/comment/85634059
has text: @Leistungsabfall comment should be good enough. I think stick to that answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49315444
type: Comment

http://stackoverflow.com/q/49332606
tagged with: networkx
accepted answer: http://stackoverflow.com/a/49336096
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49336096
tagged with: time-complexity
downvote count: 0
answer count: 1
tagged with: scalability
favorite count: 0
type: Question
has title: How to Estimate Roughly The Computation Time While Using Module NetworkX
upvote count: 2
tagged with: python
has body: Hi I am dealing with a bit big (sorry for ambiguous term) graph, which has 29,981 number of nodes with 150,000 directed-edges in it. I am dealing with it with module networkx which is fairly widely used nowadays among graph theorists. I had executed following script early this morning in Jupyter but can't estimate when to finish: import netowkx as nx import pickle # to read the graph with open ('/home/zachary/H{}'.format("29981"), 'rb') as fp: H = pickle.load(fp) print(list(nx.simple_cycles(H))) How can I roughly guess the time of finish of this script? I a bit knows of what big O and small O's.. but normally this kind of theoretically knowledge still not yet matured in my mind to industrially use those knowledge to calculate and estimate the computation time.

http://stackoverflow.com/q/49335507
score: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49335697
upvote count: 2
has answer: http://stackoverflow.com/a/49335697
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85672655
has comment: http://stackoverflow.com/comment/85672870
has comment: http://stackoverflow.com/comment/85672896
has comment: http://stackoverflow.com/comment/85672814
has comment: http://stackoverflow.com/comment/85672556
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85672581
has comment: http://stackoverflow.com/comment/85672610
type: AnsweredQuestion
has title: Compare numpy array to scalar with 'out=...'
tagged with: performance
has body: I have an array of strings: s = np.array(['a', 'b', 'c']) and I want to have a function array_equal_to_scalar to compare s with string 'a' with writing output to preallocated array (I need fast performance): mask = np.empty(s.shape) np.array_equal_to_scalar(s, 'a', out=mask) So, I expect mask will be &gt; [True False False] Is there any way to make something like array_equal_to_scalar?
tagged with: python
has comment: http://stackoverflow.com/comment/85672576

http://stackoverflow.com/comment/85581254
comment on: http://stackoverflow.com/a/49287796
score: 0
type: AnswerComment
has text: yes that `f-strings` was saying `python 3.5 doesn't support 'f' prefix` .
type: Comment

http://stackoverflow.com/q/49362449
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85724909
has answer: http://stackoverflow.com/a/49362528
has title: Compact way using generators/"with ... as" in Python
has answer: http://stackoverflow.com/a/49362645
has body: I have the following data structure: var = [['x_A_B', 1], ['x_A_C', 1], ['x_B_A', 1], ['x_B_D', 1], ['x_C_A', 1], ['x_C_D', 1], ['x_D_B', 1], ['x_D_C', 1]] I would like to extract these values as var2 = [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'D'), ('C', 'A'), ('C', 'D'), ('D', 'B'), ('D', 'C')] Currently I use the following line var2 = [(item[0].split("_")[1], item[0].split("_")[2]) for item in var] but it's tedious to write, and also calculates the same split two times. Is there a way of writing this in a compact way, maybe with keywords with ... as, something like this? # not working var2 = [(u, v) with item[0].split("_") as _, u, v for item in var] EDIT: I was looking for a more general solution, where I can use arbitrary indices of the split string with arbitrary length of substrings, I just used an improper example. See the solution I accepted.
tagged with: python
has answer: http://stackoverflow.com/a/49362594
favorite count: 0
tagged with: generator
type: Question
accepted answer: http://stackoverflow.com/a/49362805
has answer: http://stackoverflow.com/a/49362805
upvote count: 2
answer count: 5
possible better answer: http://stackoverflow.com/a/49362594
downvote count: 0
has answer: http://stackoverflow.com/a/49362773
tagged with: with-statement

http://stackoverflow.com/a/50530681
answers question: http://stackoverflow.com/q/49384608
type: Answer
score: -1
has body: The error message could not be plainer: The spider must have a name. There is no name in the code you have posted. This is basic to creating a spider in Scrapy. Also, your Python spacing is terrible, you need an editor with Pylint or something that will tell you about PEP8.
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/85599873
comment on: http://stackoverflow.com/q/49298506
type: Comment
type: QuestionComment
score: 0
has text: I am confused about your dataset now. So, you are trying to classify your images into 14951 different classes ? Yes, sigmoid will assume 2 classes but since you will have a neuron for each of your class, it will work fine with as many classes as you have. Also, if you have multiple classes you will need to use one hot encoding to convert it to a vector. Check for `to_categorical` method in keras.

http://stackoverflow.com/comment/85781229
comment on: http://stackoverflow.com/q/49389789
score: 1
has text: Looks like you're using an old version of chromedriver. Try updating chromedriver (and selenium while you're at it).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49438407
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: And for multiple index , you can using query df.query("c=='v1'") Out[255]: a b c g1 v1 1 v1 3 g2 v1 5 v1 7 Or IndexSlice idx = pd.IndexSlice df.loc[idx[:, 'v1'],:] Out[257]: a b c g1 v1 1 v1 3 g2 v1 5 v1 7
accepted answer of: http://stackoverflow.com/q/49438163
type: Answer
answers question: http://stackoverflow.com/q/49438163
score: 1

http://stackoverflow.com/q/49283580
has comment: http://stackoverflow.com/comment/85570759
tagged with: pyqt
has comment: http://stackoverflow.com/comment/85571154
answer count: 1
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85570856
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85570452
has body: user can draw rectangles by this application by giving clicking twice on grey picture. But this application dont saves last rectangles, instead of saving its drawing(updateing) a new rectangle by 2 next points. how i can solve this problem? how can i save previouse rectangles too? class myQLabel(QLabel): def __init__(self,parent): super(myQLabel, self).__init__(parent) self.x = 0 self.y = 0 self.trafficlines = [] def mousePressEvent(self, QMouseEvent): #print mode self.x = QMouseEvent.x() self.y = QMouseEvent.y() if self.x != 0 and self.y != 0: self.trafficlines.append(copy.deepcopy([self.x,self.y])) print "______" print self.x print self.y print "("+str(mode)+")" print "______" def paintEvent(self, QPaintEvent): super(myQLabel, self).paintEvent(QPaintEvent) painter = QPainter(self) if mode == 0: painter.setPen(QPen(Qt.red,3)) elif mode == 1: painter.setPen(QPen(Qt.blue,3)) elif mode == 2: painter.setPen(QPen(Qt.green,3)) elif mode == 3: painter.setPen(QPen(Qt.magenta,3)) if len(self.trafficlines)%2==1 and len(self.trafficlines)>0: painter.drawPoint(self.trafficlines[-1][0],self.trafficlines[-1][1]) if len(self.trafficlines)%2==0 and len(self.trafficlines)>0 and mode!=0: painter.drawLine( self.trafficlines[-2][0],self.trafficlines[-2][1],self.trafficlines[-1][0],self.trafficlines[-1][1] ) if len(self.trafficlines)%2==0 and len(self.trafficlines)>0 and mode==0: x1=self.trafficlines[-2][0] y1=self.trafficlines[-2][1] x2=self.trafficlines[-1][0] y2=self.trafficlines[-1][1] painter.drawLine( x1,y1,x1,y2) painter.drawLine( x1,y2,x2,y2) painter.drawLine( x2,y2,x2,y1) painter.drawLine( x2,y1,x1,y1) self.update() This is all the code: from PyQt4.QtGui import * from PyQt4.QtCore import * import sys, os import copy mode = 5 class Example(QWidget): def __init__(self,parent): super(Example, self).__init__() self.main_image_name="C:\Python27\project\main_image.png" self.initUI() def initUI(self): File_name = QLabel('Setup file name') File_name_edit = QLineEdit() QToolTip.setFont…
tagged with: pyqt4
downvote count: 0
accepted answer: http://stackoverflow.com/a/49284739
tagged with: python
has comment: http://stackoverflow.com/comment/85570581
has answer: http://stackoverflow.com/a/49284739
has comment: http://stackoverflow.com/comment/85570408
has title: how to save previous rectangles after update()?
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/85800133
comment on: http://stackoverflow.com/a/49390045
type: Comment
type: AnswerComment
has text: This JavaScript actually does open a new TAB but only when I don't set a profile. I've been looking for the setting that you suggested but haven't found it under the FireFoxProfile class. Where can I find it ?
score: 0

http://stackoverflow.com/a/49349367
has body: As there is a significant amount of networking I/O involved, threading should improve the overall performance significantly. You can try using a ThreadPool and should test and tweak the number of threads to a one that is best suitable for the situation and shows the overall highest performance . from multiprocessing.pool import ThreadPool # Remove 'for param in paramList' iteration def get_url_data(param): # Rest of code here if __name__ == '__main__': pool = ThreadPool(15) pool.map(get_url_data, paramList) # Will split the load between the threads nicely pool.close()
answers question: http://stackoverflow.com/q/49349186
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/49352549
tagged with: python
has comment: http://stackoverflow.com/comment/85707580
type: Question
tagged with: python-3.x
has title: LPTHW Ex16.. Script is running but Text file not updated
has comment: http://stackoverflow.com/comment/85706995
answer count: 0
has comment: http://stackoverflow.com/comment/85705427
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85705954
score: 0
has body: I'm running the Ex16 script from LPTHW and the script runs fine till the end (including my inputs for writing 3 lines), but the text file is not getting updated. What could be the possible reasons? I'm running this script on Python3. from sys import argv script, filename = argv print ("We're going to erase %r " % (filename)) print ("If you don't want that, hit CTRL-C (^C).") print ("If you do want that, hit RETURN.") input("?") print ("Opening the file...") target = open(filename,'w') print ("Truncating the file. Goodbye!") target.truncate() print ("Now I'm going to ask you for three lines.") line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") print ("I'm going to write these to the file.") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print ("And finally, we close it.") target.close()
has comment: http://stackoverflow.com/comment/85705619

http://stackoverflow.com/comment/85638729
type: QuestionComment
comment on: http://stackoverflow.com/q/49318826
has text: What do you expect `sys.getsizeof(float)` to `return`? Why are you checking the size of the actual class?
score: 0
type: Comment

http://stackoverflow.com/comment/85672655
comment on: http://stackoverflow.com/q/49335507
type: Comment
type: QuestionComment
score: 0
has text: @AndrasDeak absolutely sure, I have to do `np.array_equal_to_scalar(s, value)` 100 000 times with len(s) is about 1 000 000 items.. And numpy will create a new boolean mask in memory every time when I try `value == np.array(['a', 'b', ...])`

http://stackoverflow.com/q/49350346
has comment: http://stackoverflow.com/comment/85706795
type: Question
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/85730180
has title: How to wrap custom future to use with asyncio in Python?
tagged with: python
has comment: http://stackoverflow.com/comment/85715372
tagged with: concurrent.futures
score: 4
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85705650
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
has body: There is a lot of libraries that use their custom version of Future. kafka and s3transfer are just two examples: all their custom future-like classes have object as the superclass. Not surprisingly, you cannot directly call asyncio.wrap_future() on such objects and can't use await with them. What is the proper way of wrapping such futures for use with asyncio?
accepted answer: http://stackoverflow.com/a/49351069
has answer: http://stackoverflow.com/a/49351069

http://stackoverflow.com/a/49308098
has body: You should use the following line in your code: img = Image.open('/.../.../{0}.png'.format(s))
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49308030
score: 1
upvote count: 1

http://stackoverflow.com/a/49422250
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49287776
has comment: http://stackoverflow.com/comment/85850181
answers question: http://stackoverflow.com/q/49287776
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85863791
has body: You can do two things here. The first one you've found yourself: you use __attr_post_init__. The second one is to have a default: &gt;&gt;&gt; import attr &gt;&gt;&gt; @attr.s ... class C: ... x = attr.ib() ... _x_backup = attr.ib() ... @_x_backup.default ... def _copy_x(self): ... return self.x.copy() &gt;&gt;&gt; l = [1, 2, 3] &gt;&gt;&gt; i = C(l) &gt;&gt;&gt; i C(x=[1, 2, 3], _x_backup=[1, 2, 3]) &gt;&gt;&gt; i.x.append(4) &gt;&gt;&gt; i C(x=[1, 2, 3, 4], _x_backup=[1, 2, 3]) JFTR, you example of def __init__(self, data): self.data = data self.data_copy = data is wrong because you’d assign the same object twice which means that modifying self.data also modifies self.data_copy and vice versa.

http://stackoverflow.com/q/49365401
favorite count: 0
tagged with: automation
tagged with: appium
type: Question
tagged with: ios
has body: I am new to ios automation using appium. I am trying to obtain an element based on text in appium automation in python. I am currently obtaining text using following command: uiel = self.driver.find_element_by_xpath('//XCUIElementTypeStaticText[@label="abc"]') Lets say I want to write an api find_element_by_text(string) for IOS, I would have to pass the type of element and string and based on element type I should call, find_element by x_path as shown: if ios_button: uiel = self.driver.find_element_by_xpath('//XCUIElementTypeButton[@label="'+ aString +'"]') elif is_other: uiel = self.driver.find_element_by_xpath('//XCUIElementTypeOther[@label="' + aString + '"]') elif is_cell: uiel = self.driver.find_element_by_xpath('//XCUIElementTypeCell[@label="' + aString + '"]') else: uiel = self.driver.find_element_by_xpath('//XCUIElementTypeStaticText[@label="' + aString + '"]' ) Is there a way to obtain an element in IOS with just one line instead of having all the checks above?
tagged with: python
type: UnansweredQuestion
has title: How can I find elements using text in a generic way for ios automation using appium?
has answer: http://stackoverflow.com/a/49367129
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/49286818
tagged with: multiprocess
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49286901
has body: I have a script that creates a class and try's to launch an object of that class in a separate process; class Task(): def __init__(self, messageQueue): self.messageQueue = messageQueue def run(self): startTime = time.time() while time.time() -startTime &lt; 60: try: message = self.messageQueue.get_nowait() print message self.messageQueue.task_done() except Queue.Empty: print "No messages" time.sleep(1) def test(messageQueue): task = Task(messageQueue) task.run() if __name__ == '__main__': messageQueue = Queue.Queue() p = Process(target=test, args=(messageQueue,)) p.start() time.sleep(5) messageQueue.put("hello") Instead of seeing the message "hello" printed out after 5 seconds, I just get a continuous stream of "No messages". What am I doing wrong?
has answer: http://stackoverflow.com/a/49286901
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Multiprocess message queue not receiving messages

http://stackoverflow.com/comment/85849375
has text: why this code isnt working with this file https://drive.google.com/open?id=1Esuv9KpikqhwccL-dGm-IFfI5S6V7plV
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49423708
score: 0

http://stackoverflow.com/q/49371214
has answer: http://stackoverflow.com/a/49371400
has comment: http://stackoverflow.com/comment/85744767
tagged with: python
has body: Every result i've found online has either been really old, specific to either Python 2.7 or 3.x, or is complicated enough that I can't understand it. My use case is very simple, but i'm having a hard time finding a simple solution. My existing code looks like this: return_val = func_that_makes_a_request(val1, val2) lots = "of" other() code() foo = some_other_func_that_makes_a_request(val3, val4) something_else(foo, return_val) The top line ends making an HTTP request. The next few lines compute some values that are then used to make another HTTP request in the 2nd to last line. These two sections (top line, everything after that except for the last line) are completely independent of each other. The final line though requires the result of both. All I really want is to make these two HTTP requests in parallel, since neither needs to wait for the other. What's the simplest way to do this, that works in Python 2.7+? Edit for future readers Went with this solution: with multiprocessing.dummy.Pool(1) as thread_pool: return_async = thread_pool.apply_async(func_that_makes_a_request, (val1, val2)) lots = "of" other() code() foo = some_other_func_that_makes_a_request(val3, val4) return_val = return_async.get() something_else(foo, return_val)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49371357
has comment: http://stackoverflow.com/comment/85743493
has title: Correct way to run something in a thread that works in 2/3?
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49371357
has comment: http://stackoverflow.com/comment/85743508
has comment: http://stackoverflow.com/comment/85744632
has comment: http://stackoverflow.com/comment/85744010
tagged with: multithreading
has comment: http://stackoverflow.com/comment/85744055
type: Question
has comment: http://stackoverflow.com/comment/85744702
has comment: http://stackoverflow.com/comment/85744613
has comment: http://stackoverflow.com/comment/85743465
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49371400

http://stackoverflow.com/a/49418987
answers question: http://stackoverflow.com/q/49418746
downvote count: 0
has body: In a blog post, Guido van Rossum, the creator of Python, suggests writing the if __name__ == "__main__" block like this: if __name__ == "__main__": sys.exit(main()) This way, main() can return a value, like a normal function, and it will be used as an exit code for the process. I suggest reading the rest of that blog post. It contains helpful suggestions for setting up Python main() function boilerplate to be more flexible.
has comment: http://stackoverflow.com/comment/85839509
has comment: http://stackoverflow.com/comment/85839497
upvote count: 9
type: Answer
score: 9

http://stackoverflow.com/a/49311351
has comment: http://stackoverflow.com/comment/85789401
has body: If you are using moving window 2 , you can consider shift (df.add(df.shift())/2).dropna() Out[25]: A B 1 3.0 4.5 2 5.0 7.5
type: Answer
answers question: http://stackoverflow.com/q/49310303
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85624922
upvote count: 2

http://stackoverflow.com/q/49408744
downvote count: 0
accepted answer: http://stackoverflow.com/a/49409420
tagged with: python
has body: Source used before asked: Pandas: Iterate through a list of DataFrames and export each to excel sheets Splitting dataframe into multiple dataframes I have managed to do all of this: # sort the dataframe df.sort(columns=['name'], inplace=True) # set the index to be this and don't drop df.set_index(keys=['name'], drop=False,inplace=True) # get a list of names names=df['name'].unique().tolist() # now we can perform a lookup on a 'view' of the dataframe joe = df.loc[df.name=='joe'] # now you can query all 'joes' I have managed to make this work - joe = df.loc[df.name=='joe'] and it gave the exact result what I was looking for. As solution to make it work for big amount of data I found this potential solution. writer = pandas.ExcelWriter("MyData.xlsx", engine='xlsxwriter') List = [Data , ByBrand] for i in List: i.to_excel(writer, sheet_name= i) writer.save() Currently I have: teacher_names = ['Teacher A', 'Teacher B', 'Teacher C'] df = ID Teacher_name Student_name Teacher_name Teacher A 1.0 Teacher A Student 1 Teacher A NaN Teacher A Student 2 Teacher B 0.0 Teacher B Student 3 Teacher C 2.0 Teacher C Student 4 If I use - test = df.loc[df.Teacher_name=='Teacher A'] - Will receive exact result. Question: How to optimise that it will automatically save the "test" result to (for each teacher separate) excel file ( .to_excel(writer, sheet_name=Teacher_name ) with teacher name, and will do it for all the existing in the database teacher?
tagged with: excel
score: 2
possible better answer: http://stackoverflow.com/a/59858962
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49409420
favorite count: 0
linked to: http://stackoverflow.com/q/19790790
has answer: http://stackoverflow.com/a/59858962
type: Question
upvote count: 2
tagged with: python-3.x
linked to: http://stackoverflow.com/q/54996477
answer count: 2
has title: Split dataframe according to column value and export to different Excel worksheets
linked to: http://stackoverflow.com/q/36973867

http://stackoverflow.com/q/49327154
has answer: http://stackoverflow.com/a/49339373
type: AnsweredQuestion
tagged with: pyqt5
type: Question
tagged with: infinite-loop
score: 0
has comment: http://stackoverflow.com/comment/85656076
tagged with: path
tagged with: python
answer count: 1
has body: i have a python class that create a window that includes EditLine open button cancel button where the EditLine will get the userInput that is a path for folder. the problem is that once i run the script it enter in infinite loop. code: ''' 1- import the libraries from the converted file 2- import the converted file ''' from PyQt5 import QtCore, QtGui, QtWidgets import pathmsgbox import os import pathlib class path_window(pathmsgbox.Ui_PathMSGbox): def __init__(self,windowObject ): self.windowObject = windowObject self.setupUi(windowObject) self.checkPath(self.pathEditLine.text()) self.windowObject.show() def checkPath(self, pathOfFile): folder = self.pathEditLine.text() while os.path.exists(folder) != True: print("the specified path not exist") folder = self.pathEditLine.text() return folder ''' get the userInput from the EditLine ''' ''' def getText(self): inputUser = self.pathEditLine.text() print(inputUser) ''' ''' function that exit from the system after clicking "cancel" ''' def exit(): sys.exit() ''' define the methods to run only if this is the main module deing run the name take __main__ string only if its the main running script and not imported nor being a child process ''' if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) PathMSGbox = QtWidgets.QWidget() pathUi = path_window(PathMSGbox) pathUi.pathCancelBtn.clicked.connect(exit) sys.exit(app.exec_())
accepted answer: http://stackoverflow.com/a/49339373
has title: what is the error in my python script that cause an infinite loop
has comment: http://stackoverflow.com/comment/85656081

http://stackoverflow.com/comment/85738205
has text: Could you please add what output are you expecting and what output you are getting?
type: Comment
comment on: http://stackoverflow.com/q/49368505
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85578421
type: AnswerComment
comment on: http://stackoverflow.com/a/49287346
type: Comment
has text: Awesome. Thanks!
score: 0

http://stackoverflow.com/q/49343907
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/49345445
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49345445
tagged with: fork
has title: Does multiprocess in python re-initialize globals?
tagged with: python
has answer: http://stackoverflow.com/a/49343943
tagged with: global-variables
type: Question
upvote count: 4
score: 4
answer count: 2
possible better answer: http://stackoverflow.com/a/49343943
has comment: http://stackoverflow.com/comment/85690490
tagged with: multithreading
has comment: http://stackoverflow.com/comment/85690643
downvote count: 0
has body: I have a multiprocessing program where I'm unable to work with global variables. I have a program which starts like this:- from multiprocessing import Process ,Pool print ("Initializing") someList = [] ... ... ... Which means I have someList variables which get initialized before my main is called. Later on in the code someList is set to some value and then I create 4 processes to process it pool = Pool(4) combinedResult = pool.map(processFn, someList) pool.close() pool.join() Before spawning the processes, someList is set to a valid value. However, when the processes are spawned, I see this print 4 times !! Initializing Initializing Initializing Initializing As it is clear in each process the initialization section at the top of the program is getting called. Also, someList gets set to empty. If my understanding is correct, each process should be a replica of the current process's state which essentially means, I should have got 4 copies of the same list. Why are the globals being re-initialized again? And in fact, why is that section even being run? Can someone please explain this to me? I referred to python docs but wasn't able to determine the root cause. They do recommend against using globals and I'm aware of it, but it still doesn't explain the call to the initialization function. Also, I'd like to use multiprocessing and not multithreading. I'm trying to understand how multiprocessing works here. Thanks for your time.
favorite count: 0

http://stackoverflow.com/a/49390840
upvote count: 2
has body: Many thanks @BoarGules your answer did help I switched from py2exe-0.6.9.win64-py2.7.amd64.exe to py2exe-0.6.9.win32-py2.7.exe and it worked like a charm.
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49387647
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49387647

http://stackoverflow.com/a/49479548
answers question: http://stackoverflow.com/q/49338652
has comment: http://stackoverflow.com/comment/105741433
downvote count: 1
has body: I have the same error. Not sure why it happened. But I managed to upgrade by running: pip install setuptools --upgrade --ignore-installed
upvote count: 51
score: 50
type: Answer
has comment: http://stackoverflow.com/comment/100223538

http://stackoverflow.com/comment/85673678
has text: Thanks for reply I tried sth look like code but when I run it I get TypeError: 'Cell' object is not iterable error
comment on: http://stackoverflow.com/a/49336148
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85754173
has text: start filling on 1st click then on 9th click it filled completely (as one click fill one step of circle) and on next click means 10th one it again become empty.
score: 0
comment on: http://stackoverflow.com/q/49357315
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49420660
has answer: http://stackoverflow.com/a/62363379
has comment: http://stackoverflow.com/comment/85883260
has answer: http://stackoverflow.com/a/49422227
tagged with: pyspark
score: 10
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I have script in pyspark like below. I want to unit test a function in this script. def rename_chars(column_name): chars = ((' ', '_&amp;'), ('.', '_$')) new_cols = reduce(lambda a, kv: a.replace(*kv), chars, column_name) return new_cols def column_names(df): changed_col_names = df.schema.names for cols in changed_col_names: df = df.withColumnRenamed(cols, rename_chars(cols)) return df I wrote a unittest like below to test the function. But I don't know how to submit the unittest. I have done spark-submit which doesn't do anything. import unittest from my_script import column_names from pyspark import SparkContext, SparkConf from pyspark.sql import HiveContext conf = SparkConf() sc = SparkContext(conf=conf) sqlContext = HiveContext(sc) cols = ['ID', 'NAME', 'last.name', 'abc test'] val = [(1, 'Sam', 'SMITH', 'eng'), (2, 'RAM', 'Reddy', 'turbine')] df = sqlContext.createDataFrame(val, cols) class RenameColumnNames(unittest.TestCase): def test_column_names(self): df1 = column_names(df) result = df1.schema.names expected = ['ID', 'NAME', 'last_$name', 'abc_&amp;test'] self.assertEqual(result, expected) How can I integrate this script to work as a unittest what can I run this on a node where I have pyspark installed?
has answer: http://stackoverflow.com/a/54831669
downvote count: 0
upvote count: 10
tagged with: unit-testing
favorite count: 0
possible better answer: http://stackoverflow.com/a/62363379
type: Question
has title: Unit test pyspark code using python
accepted answer: http://stackoverflow.com/a/49422227
linked to: http://stackoverflow.com/q/40340100
has answer: http://stackoverflow.com/a/49430328

http://stackoverflow.com/q/49306580
score: 0
has answer: http://stackoverflow.com/a/49306616
has body: I'm using a module called credstash, which contains this function: def getSecret(name, version="", region=None, table="credential-store", context=None, dynamodb=None, kms=None, **kwargs): I want to pass a string to the function to be evaluated as positional and keyword arguments. So I have the variable called arg_action with this contents: TEST_CREDSTASH, table=perf-accounts-credentials-store I want to do something like this: credstash.getSecret(arg_action) The problem is that it's grabbing the whole contents of arg_action instead of interpreting them as the positional argument name and keyword argument table credstash.ItemNotFound: Item {'name': 'TEST_CREDSTASH, table=perf-accounts-credentials-store'} couldn't be found. Is there a way to achieve what I want? I don't want to hardcode the arguments on the function because I have several credstash functions and each one takes different arguments I ended up solving my problem like this: def credstash_action(key_id, table_name, action, args): action_list = { "get": "getSecret", "getall": "getAllSecrets", "list": "listSecrets", "put": "putSecret", "putall": "putAllSecretsAction" } function_list = { "getSecret": get_credstash_secret, "getAllSecrets": get_all_credstash_secrets, } cred_action = action_list.get(action) cred_function = getattr(credstash, cred_action) args_string = " ".join(args) function_list.get(cred_action)(function=cred_function, key_id=key_id, table_name=table_name, args=args_string) def get_credstash_secret(**kwargs): print(kwargs['function'](kwargs['args'], table=kwargs['table_name'])) def get_all_credstash_secrets(**kwargs): print(kwargs['function'](table=kwargs['table_name']))
type: Question
has title: How can I pass a string to be evaluated as positional and keyword arguments?
answer count: 2
has answer: http://stackoverflow.com/a/49306988
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49438287
tagged with: pandas
score: 1
tagged with: matplotlib
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85880637
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49439855
has body: I am trying to create a legend for my scatterplot that matches the colors set in the plot. When I run my code I get two plots, and the colors dont match. Can someone help me fix this? #import files and format them (you can skip this- its just simulating my dataset) import matplotlib.pyplot as plt import pandas as pd d = {'vote': [100, 50,1,23,55,67,89,44], 'ballot': ['a','Yes','a','No','b','a','a','b'], 'whichballot':[1,2,1,1,2,1,1,2]} dfwl=pd.DataFrame(d) dfwl['whichballot'] = dfwl['whichballot'].astype('category').cat.codes dfwl['ballot'] = dfwl['ballot'].astype('category') dfwl['vote'] = dfwl['vote'].astype('int') dfwl=pd.DataFrame(dfwl.reset_index()) dfwl=dfwl[pd.notnull(dfwl['ballot'])] ###END DATA FORMATTING plt.scatter(dfwl.ballot, dfwl.vote, c=dfwl.whichballot) plt.margins(x=0.8) plt.show() plt.table(cellText=[[x] for x in set(dfwl.whichballot)], loc='lower right', colWidths=[0.2], rowColours=['green','yellow','purple'], rowLabels=['label%d'%x for x in set(dfwl.whichballot)])
tagged with: python
has comment: http://stackoverflow.com/comment/85880557
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49439855
has title: Python scatterplot with legend

http://stackoverflow.com/comment/85809398
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49400985
score: 1
has text: oh its a dataframe. in that case you do not need to do `line[0]` just `line`

http://stackoverflow.com/comment/85837904
type: QuestionComment
comment on: http://stackoverflow.com/q/49417414
has text: Do you have a different `settings.py` for your tests? According to that stack trace, whitenoise middleware is definitely being loaded. Also, it might not hurt to post your original traceback (before you removed whitenoise). Perhaps we can help you with your original issue as opposed to the one that manifested while you were trying to fix it.
score: 0
type: Comment

http://stackoverflow.com/q/49363840
type: Question
answer count: 1
tagged with: python
has body: I am plotting data with matplotlib that has different amplitudes for a large number of periods. In some periods there is hardly any amplitude (e.g. 0.1 for a resolution of the data of 0.1). Thus, matplotlib creates ticks in a resolution that is finer that the data's actual resolution. Is there a way to define a MINIMUM distance between the ticks? As the data amplitude can be quite high, I cannot use the same fixed distance for all plots. I would like to keep the ticks chosen automatically except for periods, where they are finer than 0.1. Here is a MWE for a period with low amplitude illustrating the problem: from matplotlib import pyplot as plt import matplotlib.ticker as mtick x = range(10) y = [0.1,0.1,0.1,0.1,0.1,0.1,0.2,0.1,0.1,0.1] fig,ax = plt.subplots() ax.plot(x,y) resulting in this: In this case I would like to only have the ticks at 0.1 and 0.2.
accepted answer: http://stackoverflow.com/a/49364342
type: AnsweredQuestion
tagged with: format
has comment: http://stackoverflow.com/comment/85728598
has answer: http://stackoverflow.com/a/49364342
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85728340
has title: Matplotlib minimum tick distance

http://stackoverflow.com/comment/85710634
score: 0
comment on: http://stackoverflow.com/a/49351598
type: Comment
type: AnswerComment
has text: @ashlock I've updated my answer which handles your case.

http://stackoverflow.com/a/49447965
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: I think your solution would produce indeterminate results, because the rows within a group are in unspecified order, and so the comparison between the array aggregate and given array may produce true or false based on that: [local]:5432 u@sopython*=&gt; select group_id [local] u@sopython- &gt; from multi_groups [local] u@sopython- &gt; group by group_id [local] u@sopython- &gt; having array_agg((atom_id, sequence)) = ARRAY[(1,3),(2,2),(3,1)]; group_id ---------- 2 (1 row) [local]:5432 u@sopython*=&gt; update multi_groups set atom_id = atom_id where atom_id = 2; UPDATE 2 [local]:5432 u@sopython*=&gt; select group_id from multi_groups group by group_id having array_agg((atom_id, sequence)) = ARRAY[(1,3),(2,2),(3,1)]; group_id ---------- (0 rows) You could apply an ordering to both, or try something entirely different: instead of array comparison you could use relational division. In order to divide you have to form a temporary relation from your list of Entity records. Again, there are many ways to approach that. Here's one using unnested arrays: In [112]: vtm = select([ ...: func.unnest(postgresql.array([ ...: getattr(e, f) for e in values_to_match ...: ])).label(f) ...: for f in Entity._fields ...: ]).alias() And another using a union: In [114]: vtm = union_all(*[ ...: select([literal(e.atom_id).label('atom_id'), ...: literal(e.sequence).label('sequence')]) ...: for e in values_to_match ...: ]).alias() A temporary table would do as well. With the new relation at hand you want to find the answer to "find those multi_groups for which no entity exists that is not in the group". It's a horrible sentence, but makes sense: In [117]: mg = aliased(MultiColumnGroups) In [119]: session.query(MultiColumnGroups.group_id).\ ...: filter(~exists(). ...: select_from(vtm). ...: where(~exists(). ...: where(MultiColumnGroups.group_id == mg.group_id). ...: where(tuple_(vtm.c.atom_id, vtm.c.sequence) == ...: tuple_(mg.atom_id, mg.sequence)). ...: correlate_except(mg))).\ ...: distinct()…
accepted answer of: http://stackoverflow.com/q/49438529
has comment: http://stackoverflow.com/comment/85941314
answers question: http://stackoverflow.com/q/49438529

http://stackoverflow.com/comment/85772091
has text: I understand that. I'm still baffled why this doesn't work with adding users to groups with my account while another script works fine(where I create users). For now I have asked google for help on this. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/49383479
type: QuestionComment
score: 0

http://stackoverflow.com/q/49353986
type: Question
accepted answer: http://stackoverflow.com/a/49354082
upvote count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/34835951
has body: I have this data: list_of_dicts_of_lists = [ {'a': [1,2], 'b': [3,4], 'c': [3,2], 'd': [2,5]} {'a': [2,2], 'b': [2,2], 'c': [1,6], 'd': [4,7]} {'a': [2,2], 'b': [5,2], 'c': [3,2], 'd': [2,2]} {'a': [1,2], 'b': [3,4], 'c': [1,6], 'd': [5,5]} ] I need this result: median_dict_of_lists = ( {'a': [1.5,2], 'b': [3,3], 'c': [2,4], 'd': [3,5]} ) ...where each value is the median of the respective column above. I need the mode dictionary where available and median dictionary when no mode exists. I was able to do quick and dirty statistics.mode() by stringing each dict, getting mode of list of strings, then ast.literal_eval(most_common_string) back to a dict, but I need a column wise median in cases where there is no mode. I know how to use statistics.median(); however, the nested notation to apply it to this case, column wise, is frazzling me. The data is all floats; I wrote it as int just to make easier to read.
tagged with: python
has answer: http://stackoverflow.com/a/49354912
tagged with: dictionary
favorite count: 0
score: 2
tagged with: median
type: AnsweredQuestion
tagged with: list
answer count: 3
possible better answer: http://stackoverflow.com/a/49354064
has answer: http://stackoverflow.com/a/49354082
has comment: http://stackoverflow.com/comment/85708515
tagged with: nested
has answer: http://stackoverflow.com/a/49354064
has title: I need column wise median of list_of_dicts_of_lists in python

http://stackoverflow.com/comment/85786236
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49385105
has text: Thx, can you have more values assigned to one person?

http://stackoverflow.com/comment/85656588
type: Comment
comment on: http://stackoverflow.com/a/49327410
has text: @Kevin It would, except that a `cmp` function is still supposed to return -1.0,1, not True/False
type: AnswerComment
score: 1

http://stackoverflow.com/a/49341666
has comment: http://stackoverflow.com/comment/85684029
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49340955
accepted answer of: http://stackoverflow.com/q/49340955
has comment: http://stackoverflow.com/comment/85684052
has comment: http://stackoverflow.com/comment/85684283
has comment: http://stackoverflow.com/comment/85684479
has comment: http://stackoverflow.com/comment/85775941
type: Answer
has comment: http://stackoverflow.com/comment/85683881
has body: Calling terminate just sends the signal to kill the process; you may still have to wait on it before you can get the returncode; otherwise, it will still be None. However, the returncode is unlikely to be all that meaningful. You just killed the process with a SIGTERM, so the returncode is going to be -SIGTERM. If the problem is just that terminate takes too long, or isn't deterministic—well, SIGTERM is meant to be something the child process can use for clean shutdown, which can take time—and can even fail to do anything, if the child has a serious bug. If you really want it to go away immediately, you need to send a SIGKILL instead. (This is the difference between kill 12345 and kill -9 12345 from the terminal.) The way to do that from subprocess is to call the kill method instead of terminate. The ideal solution is usually to have a double-timeout—e.g., terminate after X seconds, then kill if another Y seconds have passed without termination. This gives the process a chance to do graceful shutdown whenever possible, but still guarantees deterministic killing after X+Y seconds. But it depends—for some uses of some programs, giving the child an extra Y seconds to hopefully finish is more important than giving it Y seconds to clean up. Or it doesn't make much difference either way, and the single-step kill is just simpler to code. (This is all a different if you're on Windows, but since you're on OS X, that's irrelevant.)
score: 2

http://stackoverflow.com/a/49302126
score: 0
answers question: http://stackoverflow.com/q/49302020
has body: You have to specify a data type or use a value with correct data type when calling np.array. Try: ROPav = np.array([0.0]*len(ROP))
type: Answer

http://stackoverflow.com/comment/85729835
comment on: http://stackoverflow.com/q/49364502
type: Comment
type: QuestionComment
score: 0
has text: because some pages may have it and some pages may not have it . so i need to use [1] in my response anyway and if it not have it i want it to be return as 'not-found'

http://stackoverflow.com/comment/85652253
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49324752
type: Comment
has text: @IMCoins. I'm not sure I understand you. In my code `v` is already a `set`, so `v` and `set(v)` are equivalent, right? I upvote your answer, though, as it is performant.

http://stackoverflow.com/comment/85606821
comment on: http://stackoverflow.com/a/49302414
score: 0
type: Comment
has text: So in case I want ALL the "mercancia" from all clients, there is no way to do that?
type: AnswerComment

http://stackoverflow.com/comment/85691138
comment on: http://stackoverflow.com/q/49337960
type: QuestionComment
has text: Already using same initial values, tried also with SGD and a range of hyper-parameters. Isn't NMF also a form of low-rank matrix factorization since the number of latent dimensions are very small compared to the original dimensions?
score: 1
type: Comment

http://stackoverflow.com/comment/85839369
type: Comment
has text: Good suggestion @jasonharper, just included it, thanks.
comment on: http://stackoverflow.com/a/49418764
type: AnswerComment
score: 0

http://stackoverflow.com/q/49351729
has answer: http://stackoverflow.com/a/49351752
type: UnansweredQuestion
tagged with: python
score: 0
has title: Date validation in python
has body: I am trying to solve a homework task involving date validation: "What’s the day? Design a program to take 3 inputs, one for day, one for month and one for year. Get your program to validate if this is an actual day, and, if it is, output the day of the week it is!" I have done the first validation bit with the following code but can't do the second bit: import datetime print("This program will check if a date is correct and output what day of the week it was.") day = input("Please input the day&gt;") month = input("Please input the month in number format&gt;") year = input("Please input the year, it must be after 1900&gt;") date_range = False leap_year_check = 0 if (date in range(1,31)) and (month in range (1, 12)) and (year in range(1900, 2018)): date_range = True else: date_range = False if date_range == True: leap_year_check = year % 4 if leap_year_check == 0: if month == 2 and day in range(1, 29): print("The date entered is a correct date") elif month == "1" or "3" or "5" or "7" or "8" or "11" or "12" and day in range (1, 31): print("The date entered is a correct date") elif month == "4" or "6" or "10" or "9" and day in range (1, 30): print("The date entered is a correct date") elif leap_year_check != 0: if month == 2 and day in range(1, 28): print("The date entered is a correct date") elif month == "1" or "3" or "5" or "7" or "8" or "11" or "12" and day in range (1, 31): print("The date entered is a correct date") elif month == "4" or "6" or "10" or "9" and day in range (1, 30): print("The date entered is a correct date") if date_range == False: print("The date entered is incorrect")
tagged with: validation
tagged with: datetime
type: Question
has answer: http://stackoverflow.com/a/49351912
answer count: 2

http://stackoverflow.com/comment/85686205
has text: Have you tried `newdb.Close` immediately after you call `CreateDatabase`?
comment on: http://stackoverflow.com/q/49324024
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/135248233
type: AnswerComment
comment on: http://stackoverflow.com/a/49358837
score: 0
has text: How can this be done using keyword arguments? Trying `executor.map(partial(fun, param1=arg1, param3=arg3), param2=arg2)` throws an error, and removing `param2=` leads to an error as the iterable argument is passed to the first parameter.
type: Comment

http://stackoverflow.com/comment/85780520
type: AnswerComment
comment on: http://stackoverflow.com/a/49389281
type: Comment
has text: Thankyou! I realise now my initial question was a bit off as the example script is an amalgamation of a couple of attempts; one of which where the column headers themselves was the data i wanted to match against. but even though my question was a bit unclear you have actually helped me in fixing it! Many thanks
score: 0

http://stackoverflow.com/q/49388492
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49389468
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85779448
has body: This is part of an ongoing series of issues I'm having trying to condense a csv file with multiple rows for each client based on the number of medical services they received. For each service, they have a row. I've included the dataframe at the bottom. I'm trying to calculate how many times a client (identified with an ID_profile number) got each type of service and add that to a column named for the type of service. So, if a client got 3 Early Intervention Services, I would add the number "3" to the "eisserv" column. Once that is done, I want to combine all the client rows into one. Where I'm getting stuck is populating 3 different columns with data based off one column. I am trying to iterate through the rows using some strings for the function to compare to. The function works, but for reasons I can't understand, all the strings change to "25" as the function works. import pandas as pd df = pd.read_csv('fakeRWclient.csv') df['PrimaryServiceCategory'] = df['PrimaryServiceCategory'].map({'Referral for Health Care/Supportive Services': '33', 'Health Education/Risk reduction': '25', 'Early Intervention Services (Parts A and B)': '11'}) df['ServiceDate'] = pd.to_datetime(df['ServiceDate'], format="%m/%d/%Y") df['id_profile'] = df['id_profile'].apply(str) df['served'] = df['id_profile'] + " " + df['PrimaryServiceCategory'] df['count'] = df['served'].map(df['served'].value_counts()) eis = "11" ref = "33" her = "25" print("Here are the string values") print(eis) print(ref) print(her) df['herrserv']="" df['refserv']="" df['eisserv']="" for index in df.itertuples(): for eis in df['PrimaryServiceCategory']: df['eisserv'] = df['count'] for her in df['PrimaryServiceCategory']: df['herrserv'] = df['count'] for ref in df['PrimaryServiceCategory']: df['refserv'] = df['count'] print("Here are the string values") print(eis) print(ref) print(her) Here is the output: Here are the string values 11 33 25 Here are the string values 25 25 25 id_profile ServiceDate PrimaryServiceCategory…
favorite count: 0
type: Question
tagged with: python
has title: Adding columns to a pandas dataframe based on values of another column
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49389188
has answer: http://stackoverflow.com/a/49388925
possible better answer: http://stackoverflow.com/a/49388925
answer count: 3
has answer: http://stackoverflow.com/a/49389468
downvote count: 0

http://stackoverflow.com/q/49320027
answer count: 1
has body: I'm currently programming with the dialogflow library for python, but when I get the list of parameters I get from an attempt, it returns me a Struct object that I don't know how to read. fields { key: "apellido1" value { string_value: "Baena" } } fields { key: "apellido2" value { string_value: "P\303\251rez" } } fields { key: "nombre" value { string_value: "Rub\303\251n" } } the documentation of the dialogflow library is very limited and there are no examples. The best I can guess is that Struct is from the following route google.protobuf.struct_pb2 Thank you very much for your help
has answer: http://stackoverflow.com/a/53421806
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: dialogflow-es
tagged with: python
has title: How can I read this Struct object in python?
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49349782
upvote count: 1
has answer: http://stackoverflow.com/a/49350017
has body: I have a nested list that contains both None elements and integers. It looks pretty much like this: aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] None elements don't follow any particular pattern and therefore can be found at any position inside the list. I'd like to obtain two things: The minimum value (minimum) among all integers. The indexes that define completely the position of this minimum value. In other words, those two numbers ( i, j ) that satisfy: aList[i][j] = minimum
tagged with: python
favorite count: 0
type: Question
answer count: 2
has title: Finding the minimum value of a nested list and its index
tagged with: min
accepted answer: http://stackoverflow.com/a/49349866
score: -2
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/49350017
downvote count: 3
has answer: http://stackoverflow.com/a/49349866

module
tags question: http://stackoverflow.com/q/49281265
type: Tag
tags question: http://stackoverflow.com/q/49418808
tags question: http://stackoverflow.com/q/49358640
tags question: http://stackoverflow.com/q/49388276
tags question: http://stackoverflow.com/q/49300561
tags question: http://stackoverflow.com/q/49334895
tags question: http://stackoverflow.com/q/49376612
tags question: http://stackoverflow.com/q/49359352
tag name: module
tags question: http://stackoverflow.com/q/49311983
tags question: http://stackoverflow.com/q/49409661
tags question: http://stackoverflow.com/q/49318806
tags question: http://stackoverflow.com/q/49321569
tags question: http://stackoverflow.com/q/49412334
tags question: http://stackoverflow.com/q/49282702

http://stackoverflow.com/comment/85632929
score: 0
comment on: http://stackoverflow.com/q/49312540
type: Comment
type: QuestionComment
has text: @creimers please stop suggesting edits where you **replace** the Python tag with the version specific tag. You can simply **add** the version specific tag keeping the Python tag.

http://stackoverflow.com/comment/86051832
type: QuestionComment
has text: I know, that method was working before I move from a simple form to a formset as I said before. I don't have any post method implemented, because I don't know where or how I should do it. I'm sorry, but I never worked with formset before, so any help with this will be perfect.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49350041

http://stackoverflow.com/comment/85655762
type: Comment
has text: Yes I know. I'm trying to improve the question so I made it not reliant on my own dataset and my original question was lacking in detail on the code.
type: QuestionComment
comment on: http://stackoverflow.com/q/49326860
score: 0

http://stackoverflow.com/q/49402113
type: AnsweredQuestion
score: 0
has title: Gensim Word2Vec most similar different result python
accepted answer: http://stackoverflow.com/a/49403004
has body: I have the first Harry Potter book in txt format. From this, I created two new txt files: in the first, all the occurrencies of Hermione have been replaced with Hermione_1; in the second, all the occurrencies of Hermione have been replaced with Hermione_2. Then I concatenated these 2 text to create one long text and I used this as input for Word2Vec. This is my code: import os from gensim.models import Word2Vec from gensim.models import KeyedVectors with open("HarryPotter1.txt", 'r') as original, \ open("HarryPotter1_1.txt", 'w') as mod1, \ open("HarryPotter1_2.txt", 'w') as mod2: data=original.read() data_1 = data.replace("Hermione", 'Hermione_1') data_2 = data.replace("Hermione", 'Hermione_2') mod1.write(data_1 + r"\n") mod2.write(data_2 + r"\n") with open("longText.txt",'w') as longFile: with open("HarryPotter1_1.txt",'r') as textfile: for line in textfile: longFile.write(line) with open("HarryPotter1_2.txt",'r') as textfile: for line in textfile: longFile.write(line) model = "" word_vectors = "" modelName = "ModelTest" vectorName = "WordVectorsTestst" answer2 = raw_input("Overwrite embeddig? (yes or n)") if(answer2 == 'yes'): with open("longText.txt",'r') as longFile: sentences = [] single= [] for line in longFile: for word in line.split(" "): single.append(word) sentences.append(single) model = Word2Vec(sentences,workers=4, window=5,min_count=5) model.save(modelName) model.wv.save_word2vec_format(vectorName+".bin",binary=True) model.wv.save_word2vec_format(vectorName+".txt", binary=False) model.wv.save(vectorName) word_vectors = model.wv else: model = Word2Vec.load(modelName) word_vectors = KeyedVectors.load_word2vec_format(vectorName + ".bin", binary=True) print(model.wv.similarity("Hermione_1","Hermione_2")) print(model.wv.distance("Hermione_1","Hermione_2")) print(model.wv.most_similar("Hermione_1")) print(model.wv.most_similar("Hermione_2")) How is possible that model.wv.most_similar("Hermione_1") and model.wv.most_similar("Hermione_2") give me different ou…
has answer: http://stackoverflow.com/a/49403004
tagged with: string
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85939160
tagged with: word-embedding
tagged with: word2vec
tagged with: python
tagged with: gensim

http://stackoverflow.com/comment/85593208
score: 0
comment on: http://stackoverflow.com/q/49295322
type: Comment
type: QuestionComment
has text: @Julien I am learning a new language and trying out a multitude of different ways to do the same thing, to get a feel for it.

http://stackoverflow.com/comment/85749266
type: QuestionComment
has text: What do you mean by associated field?
comment on: http://stackoverflow.com/q/49368989
score: 0
type: Comment

http://stackoverflow.com/q/49341966
has comment: http://stackoverflow.com/comment/85684355
has comment: http://stackoverflow.com/comment/85684397
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85684078
has body: Hello I think the two snippet below should essentially do the same thing: for divisor in range(2, 21): if sample % divisor != 0: break The first snippet, I use sample divided by number from 2 to 20, if any one of them gives remainder != 0, then I will break and try sample += 1 (codes omitted) if all(sample % divisor == 0 for divisor in range(2, n2+1)): return sample The second snippet I will return the sample if all() comes back with True, otherwise I will try sample += 1 (codes omitted) The second snippet is found twice slower than the first one. I don't understand, when python evaluate all(), if one False was found in iteration, it should immediately comes back False for all(), instead of finish the whole iteration, right? So why is the second snippet slower than the first one?
downvote count: 4
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85684323
accepted answer: http://stackoverflow.com/a/49342138
has comment: http://stackoverflow.com/comment/85684081
answer count: 1
has comment: http://stackoverflow.com/comment/85684407
tagged with: python
has answer: http://stackoverflow.com/a/49342138
has comment: http://stackoverflow.com/comment/85684100
has comment: http://stackoverflow.com/comment/85684295
has comment: http://stackoverflow.com/comment/85684073
has comment: http://stackoverflow.com/comment/85684336
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85684068
upvote count: 3
has comment: http://stackoverflow.com/comment/85684305
linked to: http://stackoverflow.com/q/27905965
has title: for loop vs. all() execution speed
score: -1
has comment: http://stackoverflow.com/comment/85684070

http://stackoverflow.com/comment/85818253
comment on: http://stackoverflow.com/q/49406381
score: 0
type: Comment
type: QuestionComment
has text: Thank you @sascha for the clear and detailed response.

http://stackoverflow.com/comment/85876978
has text: I now tried the thing below and got the same error: import numpy as np A = np.ones((5,5)) np.nanmean(np.array([A[1,1], A[2, 2:3], A[3, 1:3]])) Traceback (most recent call last): File "C:\Users\jorre\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-13e8c25b811f>", line 1, in <module> np.nanmean(np.array([A[1,1], A[2, 2:3], A[3, 1:3]])) ValueError: setting an array element with a sequence.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49437156

http://stackoverflow.com/comment/85653210
type: Comment
comment on: http://stackoverflow.com/a/49322957
score: 0
type: AnswerComment
has text: @Bonlenfum It's a bug. It looks like that threshold and the number of bins are hardcoded for the initial usecase and have never been generalized, especially not for large random variables or large samples.

http://stackoverflow.com/comment/85609924
type: QuestionComment
has text: @deceze sorry I think everything I've written is relevant in some way? except for the constructor arguments for person! i mean so you guys could understand, but idk.
score: 0
comment on: http://stackoverflow.com/q/49303319
type: Comment

http://stackoverflow.com/comment/85771681
has text: didnt get what you meant by "virtual environment with all dependencies including". More explanation?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49385013

http://stackoverflow.com/comment/117619615
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51747369
has text: I know this is old, but this could be a security vulnerability if you're fetching https externally right?
type: Comment

http://stackoverflow.com/a/49368554
type: Answer
upvote count: 4
score: 4
downvote count: 0
has body: This is one way: lst = [[450, 455, 458], [452, 454, 457], [451, 453]] res = {i: {w: None if w == v[0] else v[0] for w in v} for i, v in enumerate(lst)} Result {0: {450: None, 455: 450, 458: 450}, 1: {452: None, 454: 452, 457: 452}, 2: {451: None, 453: 451}} Explanation Use ternary statement to determine whether you choose None or v[0]. Use enumerate to extract index of nested list.
answers question: http://stackoverflow.com/q/49367943

http://stackoverflow.com/q/49417827
favorite count: 0
possible better answer: http://stackoverflow.com/a/49450015
type: Question
tagged with: python-3.x
has body: I added a button to my layout. When I try to write a callback for it, I get the following error: dash.exceptions.NonExistantEventException: Attempting to assign a callback with the event "click" but the component "get_custom_vndr" doesn't have "click" as an event. Here is a list of the available events in "get_custom_vndr": [] Here's how I'm adding it to my layout: app_vndr.layout = html.Div([ html.Button( '+', id='get_custom_vndr', type='submit' ) ]) and here's the callback function that's giving the above error: @app_vndr.callback( dash.dependencies.Output('overlay', 'className'), events=[dash.dependencies.Event('get_custom_vndr', 'click'), dash.dependencies.Event('add_vndr_id_submit', 'click')]) def show_input(b1_n, b2_n): if b1_n&gt;0: return '' elif b1_n&gt;0: return 'hidden' Did I miss something when I added the button to my layout? or when I tried to write the callback? I got it working for dash.dependencies.Input('get_custom_vndr', 'n_clicks') but I'd like to use two buttons for the same output and with the n_clicks event, I'd need to try to figure out which button was clicked by comparing the current n_clicks to the previous n_clicks for each button, which seems like a pretty hacky way to do it.
answer count: 2
tagged with: plotly-dash
downvote count: 0
has title: Button in Dash doesn't have "click" as an event
tagged with: python
accepted answer: http://stackoverflow.com/a/59210690
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49450015
has answer: http://stackoverflow.com/a/59210690
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/93504155

http://stackoverflow.com/q/49353034
has answer: http://stackoverflow.com/a/49353205
has body: I am creating a simple search engine for my university site using Selenium and Tkinter. My code creates the GUI and produces URL links to queries entered into the search box. Is it possible to have these produced URLs as clickable hyperlinks within the GUI? If so, how would I go about doing this? import selenium.webdriver as webdriver from selenium.webdriver.chrome.options import Options from tkinter import * def get_results(search_term, num_results = 10): url = "https://www.startpage.com" options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') chromedriver = "chromedriver.exe" args = ["hide_console", ] browser = webdriver.Chrome(chromedriver, service_args = args, options = options) browser.get(url) browser.set_window_position(0, 0) browser.set_window_size(0, 0) search_box = browser.find_element_by_id("query") search_box.send_keys(search_term) search_box.submit() try: links = browser.find_elements_by_xpath("//ol[@class='web_regular_results']//h3//a") except: links = browser.find_elements_by_xpath("//h3//a") results = [] for link in links[:num_results]: href = link.get_attribute("href") print(href) results.append(href) results.append(href) mlabel2 = Label(mGui, text = href).pack() browser.close() return results def search_query(): mtext = ment.get() user_search = get_results(mtext + " site:essex.ac.uk") return response = get_results mGui = Tk() ment = StringVar() mGui.geometry('640x640+0+0') mGui.title('Essex University Search') mlabel = Label(mGui, text = 'Essex University Search', font = ("arial", 40, "bold"), fg = "steelblue").pack() mbutton = Button(mGui, text = 'Search', command = search_query, font = ("arial", 10), fg = 'white', bg = 'steelblue').pack() mEntry = Entry(mGui, textvariable = ment).pack()
has title: python Tkinter have displayed text as hyperlink
linked to: http://stackoverflow.com/q/3655449
favorite count: 0
has comment: http://stackoverflow.com/comment/85706411
tagged with: tkinter
linked to: http://stackoverflow.com/q/23482748
upvote count: 2
accepted answer: http://stackoverflow.com/a/49353205
has comment: http://stackoverflow.com/comment/85706472
answer count: 1
has comment: http://stackoverflow.com/comment/85706292
tagged with: selenium
has comment: http://stackoverflow.com/comment/85706396
downvote count: 1
has comment: http://stackoverflow.com/comment/85706507
duplicate of: http://stackoverflow.com/q/23482748
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85706529
score: 1
has comment: http://stackoverflow.com/comment/85706336
tagged with: hyperlink
tagged with: python

http://stackoverflow.com/comment/85684295
comment on: http://stackoverflow.com/q/49341966
type: QuestionComment
has text: I fixed the codes, that was a typo, but even now it is still much much slower
type: Comment
score: 0

http://stackoverflow.com/comment/85650359
type: QuestionComment
comment on: http://stackoverflow.com/q/49322696
has text: Could you add complete stack trace? I think the error is in `alert = self.driver.switch_to.alert`. try adding 1-2 seconds sleep before this and try.
score: 1
type: Comment

http://stackoverflow.com/comment/85699601
type: Comment
comment on: http://stackoverflow.com/a/49338594
score: 0
type: AnswerComment
has text: i just forgot to write it here in stakoverflow, i included "- and space" to my regex, it turned out that i forgot about them. url(r'^main/(?P<message>[ a-zA-Z0-9_|-]+)/$', views.TheView.as_view({'get': 'view'}), name = 'main')

http://stackoverflow.com/a/49350792
has body: I think need read_csv working with txt nice too with header=None for new header with to_csv for write to file: df = pd.read_csv('file.txt', delim_whitespace=True, header=None) df.to_csv('file1.txt', index=False, header=None) Or: df = pd.read_csv('file.txt', sep='\s+', header=None) df.to_csv('file1.txt', index=False, header=None)
type: Answer
accepted answer of: http://stackoverflow.com/q/49350659
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49350659
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49406000
has body: Tkinter is fairly efficient. And for the number of widgets that you have, it won't impact performance much to create them all initially. Here is a sample that works about like what you were trying to do. from calendar import * import datetime try: from tkinter import * # Python 3.x except: from Tkinter import * # Python 2.x class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid(row=0, column=0, sticky='news') DateNow = datetime.datetime.now() month = int(DateNow.month) year = int(DateNow.year) self.createDaysOfWeekLabels() month_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] # Create frames and button controls for previous, current and next month. self.frameList = [] # List that contains the frame objects. self.buttonList = [] # List that contains the button objects. amonth = month - 1 for i in range(3): if amonth &lt; 0: amonth = 11 year -= 1 elif amonth == 12: amonth = 0 year += 1 mFrame = Frame(self) self.createMonth(mFrame, amonth, year) self.frameList.append(mFrame) mButton = Button(self, text=month_name[amonth-1]) mButton['command'] = lambda f=mFrame, b=mButton: self.showMonth(f, b) mButton.grid(row=0, column=i) # Grid each frame mFrame.grid(row=2, column=0, columnspan=7, sticky='news') if (i == 1): mButton['relief'] = 'flat' else: # Remove all but the ith frame. More efficient to remove than forget and configuration is remembered. mFrame.grid_remove() self.buttonList.append(mButton) amonth += 1 # Create year widget at top left of top frame label = Label(self, text=year)#displaying year label.grid(row=0, column=6) def createDaysOfWeekLabels(self): days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for i in range(7): label = Label(self, text=days[i]) label.grid(row = 1, column = i) def showMonth(self, mFrame, mButton): # Display all buttons normally for button in self.buttonList: button['relief'] = 'raised' # Set this month's button relief to flat mButton['relief'] = '…
has comment: http://stackoverflow.com/comment/85818743
answers question: http://stackoverflow.com/q/49396207
has comment: http://stackoverflow.com/comment/85817725
has comment: http://stackoverflow.com/comment/85819007
type: Answer
score: 0

http://stackoverflow.com/q/49367841
score: -1
has body: I'm a total beginner to Python and I'm trying to use Selenium I installed Selenium using this video tutorial https://www.youtube.com/watch?v=0vsswJooDe0. I was able to follow the tutorial up to 11 min 10 seconds. I tried saving the script in multiple locations, including in the paths that were added when installing Selenium. This is the script I am trying to run from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("www.google.com") This is the error that is showing up RESTART: C:/Users/cindy/AppData/Local/Programs/Python/Python36-32/sample.py Traceback (most recent call last): File "C:\Users\cindy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start stdin=PIPE) File "C:\Users\cindy\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Users\cindy\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/cindy/AppData/Local/Programs/Python/Python36-32/sample.py", line 5, in &lt;module&gt; driver = webdriver.Firefox() File "C:\Users\cindy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__ self.service.start() File "C:\Users\cindy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Can someone tell me what I've done wrong and how to fix this? Thanks!
upvote count: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85736664
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/40208051
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49368031
has title: Python Selenium winerror 2
tagged with: python

http://stackoverflow.com/comment/85733084
comment on: http://stackoverflow.com/q/49366161
has text: You can always include things like your 2nd set of intervals using range with the step argument like `list(range(20,50,10))`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85826952
score: 0
has text: @Kingz ... your comment is a very important item to have included in your question. Also, one should not continually change table constraints as it can invalidate other rows. Constraints, keys, triggers, etc. should be set up once during database schema design stage before data population.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49409863

http://stackoverflow.com/q/49299576
tagged with: proxy
tagged with: linux
has body: I was trying to make squid custom authentication with python which i used to connect and check directly from MySQL Database When user was removed from the login table , he is still able to use the proxy , the change happen only when i run : squid -k reconfigure Any other helpful solution that make this happen easily and fast then using command line every time?
tagged with: python
tagged with: squid
has title: How to force squid users to logout?
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: mysql
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85707109
comment on: http://stackoverflow.com/q/49353348
has text: There can be many reasons for that, but the first thing I usually do is in the importing file to `print(dbconn.__file__)` and check if the path is correct
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/85852686
type: QuestionComment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167330/discussion-between-shadkhan-and-wiktor-stribizew).
comment on: http://stackoverflow.com/q/49425537
type: Comment

http://stackoverflow.com/q/49393647
tagged with: matrix
tagged with: numerical-methods
has comment: http://stackoverflow.com/comment/85790014
type: Question
has body: import numpy as np A = np.matrix([[1,1,-1],[0,1,3],[0,0,-6]]) b = np.array([9,3,8]) def back_sub(A,b): n = len(A) print('n is:', n) x = [0]*n for i in range(n-1,-1,-1): #this refers to the rows; i goes 2,1,0 for j in range(i+1,n): b[i] = b[i] - A[i,j]*x[j] x[i] = b[i]/A[i,i] return x I am trying to back substitute an upper-triangular matrix A, and come up with an answer: x1=4/3,x2=7,x3=−4/3 . When I run my code, it gives correct answer for x2 and x3 , but x1 comes out as 0, which is confounding. I have tried to debug my code, and it seems to run fine until i=0 . Why isn't this code giving me the correct value of x1 ?
type: UnansweredQuestion
has title: Back-substitution in Python for 3x3 matrix
tagged with: python
has comment: http://stackoverflow.com/comment/85853911
score: 0
answer count: 0

http://stackoverflow.com/comment/85803677
comment on: http://stackoverflow.com/a/49400381
type: AnswerComment
score: 0
has text: I understand that all the lines start with "B0", but it wasn't clear that the first line was at the *very* start of the file, maybe there are header lines at the top which need to be skipped.
type: Comment

http://stackoverflow.com/comment/85792585
type: Comment
has text: No, it still has the same problem - those identifiers are only assigned because *you just assigned them*. `del x` doesn't delete the object `x` previously referenced, it just decrements its reference count. It would be helpful to explain why this is a thing you're trying to do at all.
type: QuestionComment
comment on: http://stackoverflow.com/q/49395278
score: 0

http://stackoverflow.com/q/49314429
favorite count: 0
has body: I want to add the number of observations to Seaborn barplots. I created a barplot with four bars that represent percentages on the y axis. I want to add a label on each bar showing the number of observations. In my code, the first block creates the barplot. I created the second two blocks of code from examples that I found elsewhere. I get an error message pointing to the row beginning with "medians," and the message says: AttributeError: 'float' object has no attribute 'values' sns.set_style("whitegrid") ax = sns.barplot(x=barplot_x, y="trump_margin_pct", data=mean_analysis) sns.palplot(sns.diverging_palette(240, 0)) ax.set(xlabel='Strength of Candidate Support', ylabel='Average Trump Margin of Victory/(Loss) (in %)') ax.set_title('Average Strength of Candidate Support Across Groups of Counties, 2016') # Calculate number of obs per group &amp; median to position labels medians = mean_analysis['trump_margin_pct'].median().values nobs = mean_analysis['trump_margin_pct'].value_counts().values nobs = [str(x) for x in nobs.tolist()] nobs = ["n: " + i for i in nobs] # Add it to the plot pos = range(len(nobs)) for tick,label in zip(pos,ax.get_xticklabels()): ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], horizontalalignment='center', size='x-small', color='w', weight='semibold')
type: Question
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49316310
has title: How can I add the number of observations to a Seaborn barplot?
downvote count: 0
upvote count: 1
tagged with: seaborn
type: UnansweredQuestion
tagged with: bar-chart
answer count: 1

http://stackoverflow.com/comment/85750277
type: AnswerComment
has text: As for inexistent values, they shouldn't matter. If you never assign the value to a variable, it will never be used.
score: 1
comment on: http://stackoverflow.com/a/49374094
type: Comment

http://stackoverflow.com/a/74079828
has body: I'm facing a similar problem. I think the ValueError is better suited for this. https://docs.python.org/3/library/exceptions.html#ValueError exception ValueError: Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. I have a function that can receive two arguments, but should receive only either one of the two, but not both. If both are set, or none of them are set, it's a problem. I use the ValueError exception for this. Example code: def parse_article(self, url: string = None, file: string = None) -> Article: if url == None and file == None: raise ValueError("Function was called without any arguments. Please set either url or file, but not both.") else: if url != None and file != None: raise ValueError( "Both url and file were given. Please give either url or file, but not both.") # Rest of the function. # Parse the article at the url or in the file, then return it.
answers question: http://stackoverflow.com/q/49309446
score: 0
type: Answer

http://stackoverflow.com/comment/85672957
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49335633
score: 2
has text: "I want to know the number of cases how many kinds of 2-letter cases are in the combination in word 3 and word 4 I sorted the cases and try to delete the cases in the list." <- I'm sorry but this is complete word salad.

http://stackoverflow.com/a/52538403
answers question: http://stackoverflow.com/q/49282262
score: 0
type: Answer
has body: 1) Check out the documentation: https://jira.readthedocs.io/en/master/examples.html#projects 2.1.8. Projects Projects are objects, just like issues: projects = jira.projects() Also, just like issue objects, project objects are augmented with their fields: jra = jira.project('JRA') print(jra.name) # 'JIRA' print(jra.lead.displayName) # 'John Doe [ACME Inc.]' 2) Check out the documentation: https://jira.readthedocs.io/en/master/examples.html#fields Example about accessing the worklogs: issue.fields.worklog.worklogs # list of Worklog objects issue.fields.worklog.worklogs[0].author issue.fields.worklog.worklogs[0].comment issue.fields.worklog.worklogs[0].created if in doubt check the documentation

http://stackoverflow.com/q/49416063
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19735250
tagged with: php
has comment: http://stackoverflow.com/comment/85835043
score: 0
has body: I already looked over almost everything online to find something that answers my question but couldn't find a solution. So Basically what I'm trying to do is to create a website that runs python codes on button click and return the result. I've created a very simple and basic php page test.php &lt;html&gt; &lt;head&gt; &lt;title&gt; test &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" name="runscript" value=" Run Python code " onClick="&lt;? php exec('python myscript.py'); ?&gt;"&gt; &lt;/body&gt; &lt;/html&gt; and this is my python code myscript.py: print("Hello, world!") what I want is to take back the result of the code and put it back in the website. But I have no idea how to deal with it or how to do it. And on the actual website that I will be building, will have to bring back graphs and plots from the python codes and I don't know either how to do it.
has title: Run a python code and returning the results when clicking on a button in html/php
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/85834050
type: Question

http://stackoverflow.com/q/49376612
answer count: 1
score: 1
upvote count: 1
tagged with: jupyter-notebook
favorite count: 0
type: Question
has body: I am developing an application and, for the first version, I am using a Jupyter notebook as the end-user interface. The second cell in the notebook imports all object(s) from a module that I wrote . The third cell acts like a configuration file; the end-user is expected to set variable values. In subsequent cells, module functions and/or instance methods are called, but are unable to "find" variables that were bound in the "configuration" cell. How can I access variables like a in module function calls?
has answer: http://stackoverflow.com/a/49378325
type: UnansweredQuestion
downvote count: 0
has title: module object access to "global" values in Jupyter notebook cell
tagged with: python
tagged with: module
tagged with: scope

http://stackoverflow.com/q/49339355
answer count: 0
upvote count: 3
tagged with: models
has comment: http://stackoverflow.com/comment/85679284
downvote count: 0
has comment: http://stackoverflow.com/comment/113674824
has body: I want to use Inception-v3 with pretrained weights on ImageNet to take inputs that are not just 3 channel RGB images but have more channels, such that the dimension is (224, 224, x!=3), and then assigning a self-defined set of weights to the following Conv2D layer. I was trying to change the input layer and the subsequent Conv2D layer such that it suits my needs, but I could not find a structured way of doing so. I tried building a custom Conv2d tensor with Conv2D(...)(input) and assigning that to the corresponding layer of Inception, but this fails because it requires actual layers, while the above instruction yields a tensor. For all it matters, Conv2D(...)(Input) and Inception.layers[1].output yields the correct same output (which it should be since I just want to change the input dimensions and weights), the question is how to wrap the new Conv2D input-output mapping as a layer and replace it in Inception? I could try hacking my way through this, but generally I wondered if there is a swift and elegant way of reassigning certain layers in those pretrained models with custom specifications. Thank you! Edit: What works is inserting these lines at line 394 of the inception_v3.py from Keras, disabling the exception for more than 3 channel inputs and then simply calling the constructor with the desired input. (Note that Original calls the original InceptionV3 constructor) Code: original_model = Original(weights='imagenet', include_top=False, input_shape=(299, 299, 3)) weights = model.get_weights() original_weights = original_model.get_weights() for i in range(1, len(original_weights)): weights[i] = original_weights[i] averaged_weights = np.mean(weights[0], axis=2)[:, :, None, :] replicated_weights = np.repeat(averaged_weights, 20, axis=2) weights[0] = replicated_weights Then I can call InceptionV3(weights='imagenet', include_top=False, input_shape=(299, 299, 20)) This work and gives the desired result, but seems very hacky.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87505659
type: UnansweredQuestion
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/87496932
has comment: http://stackoverflow.com/comment/87499092
score: 3
has title: How to modify layers of pretrained models in Keras like Inception-v3?

http://stackoverflow.com/q/49414862
possible better answer: http://stackoverflow.com/a/49415204
has title: Storing several informations in one variable in Django Models
has comment: http://stackoverflow.com/comment/85831553
has body: class Cities(models.Model): city_main_image = models.FileField() city_name = models.CharField(max_length=200) city_info = models.CharField(max_length=1000) city_images = models.FileField() In my models.py I have Cities class and I want to upload several images for this class variable, to be clearly for city_images variable how can I do this? Are there any way to do this or not?
downvote count: 0
has answer: http://stackoverflow.com/a/49415074
tagged with: django
upvote count: 1
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/49415204
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49415061
answer count: 3
score: 1
tagged with: django-models
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49415074

http://stackoverflow.com/comment/85676283
comment on: http://stackoverflow.com/q/49336063
type: Comment
score: 1
has text: Does your python command run python 2 or 3? There are issues with text encoding, but some useful defaults where added in python 3 so maybe you don't have to change your program.
type: QuestionComment

http://stackoverflow.com/comment/85841241
score: 0
type: AnswerComment
has text: Thank you! This was really helpful.
type: Comment
comment on: http://stackoverflow.com/a/49397277

http://stackoverflow.com/comment/85619004
has text: That is still not a specific programming question and this is not a tutorial site. PLEASE read [ask] and take the [tour].
comment on: http://stackoverflow.com/q/49307165
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/85756206
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49377662
score: 0
has text: If anything, `sentece` is a NameError and `range()` does not take a list object... Did you mean `for sentence in word_list`? Which loops over every item within that list

http://stackoverflow.com/q/49379456
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/85766381
tagged with: python
tagged with: tensorflow
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I am unable to perform padded batching dataset.padded_batch() , in Tensorflow, here is my code : this code throws an error, doesn't work, I think its because for some reason I am using my own code to calculate MFCC, but it works if I don't call padded_batch I am getting the following error : " InvalidArgumentError: All elements in a batch must have the same rank as the padded shape for component0: expected rank 1 but got element with rank 2 [[Node: IteratorGetNext = IteratorGetNextoutput_shapes=[[?,?], [?,?], [?,?]], output_types=[DT_DOUBLE, DT_STRING, DT_INT64], _device="/job:localhost/replica:0/task:0/device:CPU:0"]] " def _read_py_function(audio, label): audio = audio_to_mfcc(audio) original_length=audio.shape[0] #if audio.shape[0] &lt; timesteps: # original_length=audio.shape[0] # print(original_length) #elif audio.shape[0] &gt;= timesteps: # original_length=timesteps #audio=normalized(pad(audio) , axis=1 ) # audio=pad(audio) return audio ,label, original_length dataset = tf.contrib.data.TextLineDataset("hardik_250_docker.csv") dataset=dataset.map(decode_csv) dataset = dataset.map( lambda audio, label: tuple(tf.py_func( _read_py_function, [audio, label], [tf.double, label.dtype, tf.int64]))) shapes=([None] , [None], [None]) dataset=dataset.padded_batch(2, padded_shapes=shapes)
downvote count: 0
has title: How to pad tuple data in Tensorflow for batching?
has comment: http://stackoverflow.com/comment/85759979

http://stackoverflow.com/comment/85652578
comment on: http://stackoverflow.com/q/49325478
type: Comment
type: QuestionComment
score: 0
has text: And you probably need to post the rest of the test. You seem to be hinting that `response` is something you've got from querying an external API - which firstly is not what `assertContains` is expecting but secondly is a really bad idea to do in a test.

http://stackoverflow.com/q/49425007
has comment: http://stackoverflow.com/comment/85851019
type: Question
tagged with: pycharm
has comment: http://stackoverflow.com/comment/85909722
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85851293
has comment: http://stackoverflow.com/comment/85851104
has comment: http://stackoverflow.com/comment/85851530
has body: How can I take all scripts and files in my Python project directory and create a single executable. I have tried using this: How do I create an executable file out of a PyCharm project using PyInstaller? but it does not work. I have developed the project in PyCharm and I am using Python 3.4.
favorite count: 0
has comment: http://stackoverflow.com/comment/85851307
has comment: http://stackoverflow.com/comment/85851289
has title: Creating an executable from a Pycharm Python Project
score: 1
has answer: http://stackoverflow.com/a/49425373
linked to: http://stackoverflow.com/q/36337376
has comment: http://stackoverflow.com/comment/85851144

http://stackoverflow.com/comment/85647219
type: AnswerComment
comment on: http://stackoverflow.com/a/49322727
has text: @sujatharathod Where is your capital letter in your example `sujat@`?
type: Comment
score: 0

http://stackoverflow.com/q/49421627
has comment: http://stackoverflow.com/comment/85844464
has answer: http://stackoverflow.com/a/49421869
has comment: http://stackoverflow.com/comment/85844198
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/18580794
type: Question
has title: AttributeError: 'NoneType' object has no attribute 'text' in python
tagged with: kivy
has body: I am using python-2.7 and kivy.When i run test.py then it gives error AttributeError: 'NoneType' object has no attribute 'text' in python? Someone tell me what is mistake? test.py import kivy kivy.require('1.9.0') # replace with your current kivy version ! from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.properties import ObjectProperty Window.size = (500, 230) class GroupScreen(Screen): groupName = ObjectProperty(None) def __init__(self, **kwargs): super(GroupScreen, self).__init__(**kwargs) self.groupName.text = "Test" class Group(App): def build(self): self.root = Builder.load_file('test.kv') return self.root if __name__ == '__main__': Group().run() test.kv GroupScreen: groupName:groupName GridLayout: cols: 2 padding : 30,30 spacing: 10, 10 row_default_height: '40dp' Label: text: 'Test' SingleLineTextInput: id: groupName GreenButton: text: 'Ok' GreenButton: text: 'Cancel' Label: Label: &lt;SingleLineTextInput@TextInput&gt;: multiline: False &lt;GreenButton@Button&gt;: background_color: 1, 1, 1, 1 size_hint_y: None height: self.parent.height * 0.150
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/85844330
accepted answer: http://stackoverflow.com/a/49421869
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85753055
has text: did you try with capitalized `Username`? cuz that's the variable declared above
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49375620
score: 0

http://stackoverflow.com/comment/85590387
type: Comment
comment on: http://stackoverflow.com/a/49292608
type: AnswerComment
has text: Another possible problem is for set values - check [here](https://stackoverflow.com/a/20627316/2901002)
score: 0

http://stackoverflow.com/comment/85702463
score: 0
has text: If you plan to avoid matching 8-digit chunks inside longer digit chunks, add lookarounds, `(?<!\d)(?:\d{8}|\d{4}\s\d{4})(?!\d)`
comment on: http://stackoverflow.com/q/49351273
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49307502
tagged with: sparql
has title: Recursive SPARQL query for a combination of triples
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38641984
tagged with: owl
linked to: http://stackoverflow.com/q/44301893
answer count: 1
has comment: http://stackoverflow.com/comment/85725180
has comment: http://stackoverflow.com/comment/85725092
has comment: http://stackoverflow.com/comment/85619155
favorite count: 0
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/49352066
has comment: http://stackoverflow.com/comment/85620445
has body: I have the following query that I run recursively in Python using ontospy: SELECT ?c WHERE { ?c rdfs:subClassOf ?restriction . ?restriction owl:onProperty :has_part ; owl:someValuesFrom ?p . VALUES ?p { &lt;some_uri&gt; } } Basically, I take the values returned from that and re-run the query to follow a hierarchy of "has part some" relationships within an ontology. I am hoping to avoid making multiple SPARQL queries by adding the recursion to the query itself. I know how to do this for a single triple using rdfs:subClassOf* but cannot figure out the syntax for combining the two triples: ?c rdfs:subClassOf ?restriction . ?restriction owl:onProperty :has_part ; owl:someValuesFrom ?p . Is this possible?
upvote count: 5
has answer: http://stackoverflow.com/a/49352066
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85874654
has text: please ask a specific question and list what you have tried so far
type: QuestionComment
comment on: http://stackoverflow.com/q/49436063
score: 0
type: Comment

http://stackoverflow.com/comment/85730338
type: AnswerComment
comment on: http://stackoverflow.com/a/49321336
score: 0
type: Comment
has text: @Truntle edited my answer to include an example of how to add this kind of notation to the python standard library pathlib

http://stackoverflow.com/q/49391043
has title: automate ssh commands using python. Obs. double login required
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85784120
type: UnansweredQuestion
tagged with: python
has body: So, my university has a cluster that I want to use. However, to access it, I need to login in a ssh server of the university first, and through it login in the cluster using the ssh again. So, my code looks like this: def login(): import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('cupido.iqm.unicamp.br', port=22, username='gabriel', password='*********') Where, cupido.iqm.unicamp.br is the host that I need to access first in order to login the cluster through ssh. This works, fine. So I tried to login in the cluster with the following function: def kahuna(): login() ssh.connect('kahuna.iqm.unicamp.br', username='gabrielcesar', password='*********') stdin, stdout, stderr = ssh.exec_command('ls') output=stdout.readlines() print '\n'.join(output) Here where it gets all fusy. For me it would make sense to login first using the previous function and then use ssh.connect again the same way I did before. However I get the following error(in the comments) In summary, is there any way to perform a double login in ssh through python?
tagged with: paramiko
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85783564
tagged with: ssh
upvote count: 1

http://stackoverflow.com/comment/97934099
has text: Yes, the tool used by conda to install the start menu item is [menuinst](https://github.com/ContinuumIO/menuinst). It uses a json that specifies the command that runs on click. You can modify this command (and make it open Jupyter on a directory or file) and reinstall the menu item using the python api of menuinst. All this can be done manually or be added to the post-install script of constructor. You can even add your own menu icon.
comment on: http://stackoverflow.com/a/55605151
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85604888
has text: it was in the fit but i've also seen another in the compile
comment on: http://stackoverflow.com/q/49301203
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85797439
has text: inheritance in which base class properties ahe inherit to child class. no idea about Composition
comment on: http://stackoverflow.com/a/49377086
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49284548
score: 4
answers question: http://stackoverflow.com/q/49284459
downvote count: 0
upvote count: 4
has body: Well, a very stupid solution. After 45 minutes of trial-and-error I found out that I just have to invoke buildozer android debug to compile the application. buildozer android run is independent and just runs the compiled application. As a user of the gradle build system I did not think about this case, because I was familar with the target-based build system. The final solution to compile and run on the target device is therefore: buildozer android debug deploy run I hope this answer will help someone who expects the same problem.
type: Answer

http://stackoverflow.com/comment/85711451
type: QuestionComment
has text: You should add a bit more (or just the full) traceback; not just a single error line.
score: 0
comment on: http://stackoverflow.com/q/49351442
type: Comment

http://stackoverflow.com/a/58464242
downvote count: 3
has body: if take these errors u just need to specify the last with numbers of the classes > as an example u have 6 classes u have to make that : model.add(Dense(6, activation='softmax')) u can use this num_classes=... and the last layers will be model.add(Dense(num_classes, activation='softmax'))
upvote count: 5
answers question: http://stackoverflow.com/q/49392972
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/108558976

http://stackoverflow.com/a/49376557
answers question: http://stackoverflow.com/q/49376339
score: 0
type: AcceptedAnswer
has body: One way to do the desired conversion would be: Code: def convert_comma_number(maybe_number): try: return float(maybe_number.replace(',', '.')) except ValueError: return maybe_number import csv with open('csvfile.csv', 'rU') as f: reader = csv.reader(f, delimiter=';') for row in reader: row = [convert_comma_number(col) for col in row] print(row) Results: ['# 2018-03-16: ECarbix Prices/Volumes for Emission Spot Market'] ['# '] ['# Data type(ST)', 'Trading Date', 'Creation Time'] ['# Data type(IL)', 'Index', 'Unit', 'Price', 'Volume'] ['# Data type(AL)', 'Number of Lines'] ['# '] ['ST', '2018-03-16', '2018-03-19T08:39:48+01:00'] ['IL', 'Day', 'EUR/tCO2', 10.97, 4533000.0] ['AL', 9.0]
accepted answer of: http://stackoverflow.com/q/49376339
type: Answer

http://stackoverflow.com/comment/85665562
type: AnswerComment
has text: I just made a dictionary with the orderdereddict, now I need to store the information from questData into specific locations in a dictionary, any ideas?
comment on: http://stackoverflow.com/a/49331535
type: Comment
score: 0

http://stackoverflow.com/q/49294299
upvote count: 1
favorite count: 0
has body: I am looking for a better solution for the following situation: Object A1, A2, A3... An, they have same attributes: a01, a02, a03, ... a0n. They have different attributes too: A1 has a10, a11, a12, ..., a1n, A2 has a20, a21, a22, .... a2n, A3 has a30, a31, a32, .... a3n, An has an0, an1, an2, .... ann, Here is what to be expected: One list view displays values of attributes a01, a02, a03, ... a0n of all the objects(A1, A2, A3,...An). When clicking a record in the list view, a form of that object will be opened and displayed. For example: We have 3 records: record 1 from object A1 record 2 from object A2 record 3 from object A3. So in the list view the value of attributes: a01, a02, a03, ... a0n of all three records are displayed. When clicking record 1, the form of object A1 will be opened, and value of attributes a10, a11, a12, ..., a1n are displayed; When clicking record 2, form of object A2 will be opened, and value of attributes a20, a21, a22, ..., a2n are displayed. In other words, one list view will direct to different form views. My current solution is all the attributes are merged into one module or class and all data is in one table. When clicking different records in the list view, the same form is displayed, most of the attributes are hide, it looks like a different view is displayed. When clicking record A1, a10, a11, a12, ... a1n are displayed, and a20, a21, a22, .... a2n, an1, an2, .... ann, are hide. The problem with this solution is the number of attributes in one module is becoming larger and larger, and more and more attributes needs to be hide. Do you have any idea to do this better?
has title: How to make different records in one list view direct to different form views in odoo 10
tagged with: odoo
score: 1
has answer: http://stackoverflow.com/a/49316288
tagged with: python
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49352239
answers question: http://stackoverflow.com/q/49352076
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You have to close the file, to get all data written: import csv import re import os import shutil SRCFILE = '/Users/poweruser/Applications/pythonwork/bbbscrap2/scrape/output%s.csv' DESTINATION_FOLDER = '/Users/poweruser/Applications/pythonwork/leadparser/newfiles' class myExporter(object): def __init__(self): i = 0 while os.path.exists(SRCFILE % i): i += 1 self.filename = SRCFILE % i with open(self.filename, 'w') as output: output = csv.writer(output) output.writerow(['Email', 'Website', 'Phone Number', 'Location']) def process_item(self, item, spider): with open(self.filename, 'a') as output: output = csv.writer(output) output.writerow([item['email'], item['website'], item['phonenumber'], item['location']]) folder = os.path.join(DESTINATION_FOLDER, os.path.basename(self.filename)) shutil.copy(self.filename, folder) return item
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49352076

http://stackoverflow.com/a/49380204
has comment: http://stackoverflow.com/comment/85763867
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85766735
has body: Cast the 'row' variable to an np.array instead of a list. import numpy as np row=['12347','Van','18/01/2017'] npvalues = np.array([ ['12345','Bus','23/02/2017'],['12346','Truck','01/07/2017'],['12347','Van','18/01/2017'] ]) row Out[60]: ['12347', 'Van', '18/01/2017'] npvalues Out[61]: array([['12345', 'Bus', '23/02/2017'], ['12346', 'Truck', '01/07/2017'], ['12347', 'Van', '18/01/2017']], dtype='&lt;U10') # Cast instead row = np.asarray(row) np.isin(row, npvalues) Out[63]: array([ True, True, True], dtype=bool) Note - I was able to run your code as is, and get the answer required. row=['12347','Van','18/01/2017'] npvalues = np.array([ ['12345','Bus','23/02/2017'],['12346','Truck','01/07/2017'],['12347','Van','18/01/2017'] ]) np.isin(row, npvalues) Out[64]: array([ True, True, True], dtype=bool) Here are my version infos import sys sys.version Out[71]: '3.6.4 |Anaconda, Inc.| (default, Mar 12 2018, 20:20:50) [MSC v.1900 64 bit (AMD64)]' np.version.full_version Out[67]: '1.13.3'
answers question: http://stackoverflow.com/q/49379907
has comment: http://stackoverflow.com/comment/85763749
type: Answer
accepted answer of: http://stackoverflow.com/q/49379907
has comment: http://stackoverflow.com/comment/85764065
has comment: http://stackoverflow.com/comment/85763201
score: 0
has comment: http://stackoverflow.com/comment/85776230

http://stackoverflow.com/a/49352909
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49352870
has comment: http://stackoverflow.com/comment/85706013
has body: As @Anton vBR commented, first remove rows by condition per groups and then get rows by minimal C by idxmax and select by loc: df = df[df.groupby('A')['C'].transform(lambda x: x &gt;= x.min() + 10)] #filtering with transform `min` only #df = df[df.groupby('A')['C'].transform('min') + 10 &lt;= df['C']] print (df) A B C 0 2002-01-13 15:00:00 120 2 2002-01-13 16:00:00 130 3 2002-01-13 16:30:00 140 4 2002-01-14 15:00:00 180 5 2002-01-14 15:30:00 165 7 2002-01-14 16:30:00 170 df = df.loc[df.groupby('A')['C'].idxmin()] What is same as: idx=df.sort_values(['A','C']).groupby('A')['C'].apply(lambda x: (x &gt;= x.min() + 10).idxmax()) df = df.loc[idx] Alternative solution with sort_values with drop_duplicates: df = df.sort_values(['A','C']) df = df[df.groupby('A')['C'].transform(lambda x: x &gt;= x.min() + 10)].drop_duplicates(['A']) print (df) A B C 0 2002-01-13 15:00:00 120 5 2002-01-14 15:30:00 165
answers question: http://stackoverflow.com/q/49352870

http://stackoverflow.com/comment/85818329
comment on: http://stackoverflow.com/q/49408242
type: Comment
has text: What have you tried to fix it? And what does the documentation say the parameters should be? My first guess would be pass in `A.T` rather than A, based on the error message.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85868154
has text: I tried to adapt the code from https://stackoverflow.com/questions/44426379/input-a-csv-file-into-tensorflow-to-construct-neural-network
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49433165
score: 0

http://stackoverflow.com/comment/85647475
has text: I have tried that, reducing the batch_size to all different numbers (even 1), reducing the vocabulary length, and only doing one convolution, but I get the same error.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49311293
type: QuestionComment

http://stackoverflow.com/comment/85664510
comment on: http://stackoverflow.com/q/49331185
score: 0
type: Comment
type: QuestionComment
has text: @FlatBoulders I attempted to format your post into a question. If my edit was incorrect, then I'm afraid you'll have to edited the question yourself.

http://stackoverflow.com/comment/85830953
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49406282
score: 0
has text: One could take the spline of the log of your data. Then the derivative is available directly.

http://stackoverflow.com/comment/85825731
type: AnswerComment
comment on: http://stackoverflow.com/a/49411531
has text: Thanks for the answer. I just checked with the DBAs to see if they can/will configure HTTP access. Will update with results
score: 0
type: Comment

http://stackoverflow.com/q/49424199
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/101120890
answer count: 0
type: UnansweredQuestion
tagged with: facebook
has body: I am using the Facebook Graph API with an access_token for myself (generated using the Graph API Explorer: https://developers.facebook.com/tools/explorer ) I want to retrieve all photos I am tagged in. I'm starting at this endpoint: https://developers.facebook.com/docs/graph-api/reference/user/photos/ I can page through them fine, but there are only 109 photos before there are no more results. On my Facebook profile, under "Photos" -> "Photos of You" there are many more than 109. Why are all the photos not available to me through the Graph API?
tagged with: python
has title: Facebook Graph API to retrieve tagged images of myself
score: 3
tagged with: python-2.7
upvote count: 3
downvote count: 0
tagged with: facebook-graph-api

http://stackoverflow.com/a/49482105
has comment: http://stackoverflow.com/comment/86111399
has comment: http://stackoverflow.com/comment/86101976
answers question: http://stackoverflow.com/q/49400385
has comment: http://stackoverflow.com/comment/86068503
score: 1
has body: To make an API call to another region, specify the region_name: ec2 = boto3.client('ec2', region_name='ap-southeast-2') When MaxResults is exceeded, obtain the next set of results by making the same call, but set NextToken to the value returned by NextToken in the previous result set.
type: Answer
has comment: http://stackoverflow.com/comment/86099526
has comment: http://stackoverflow.com/comment/86114028
has comment: http://stackoverflow.com/comment/86114074
has comment: http://stackoverflow.com/comment/86147179
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86101988

http://stackoverflow.com/q/49341525
score: 1
has body: I'm using the Librosa function librosa.output.write_wav to output a time series as a .wav file and then trying to open it in pydub, but pydub is throwing a FileNotFoundError message (see below). The *.wav files are definitely in the same directory as my Jupyter notebook (convert_spect_to_wav.ipynb). The weird thing is my code works perfectly fine if I feed in *.wav files that were not generated by Librosa. I'm able to listen to the Librosa *.wav files, so I don't know what weird thing Librosa is doing that is making pydub not find the Librosa *.wav files. Directory [lashen.lashen-MOBL] ➤ ls -l total 442 -rwx------ 1 lashen UsersGrp 103566 Feb 17 14:47 bdl_arctic_a0001.wav -rwx------ 1 lashen UsersGrp 12973 Mar 17 12:56 convert_spect_to_wav.ipynb drwx------ 1 lashen UsersGrp 0 Mar 17 12:38 generated -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_0.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_1.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_2.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_3.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_4.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:55 generated_5.wav -rwx------ 1 lashen UsersGrp 43066 Mar 17 12:48 hello.wav -rwx------ 1 lashen UsersGrp 103566 Feb 17 14:58 ksp_arctic_a0001.wav -rwx------ 1 lashen UsersGrp 44530 Mar 17 12:40 ksp_arctic_a0001_0.wav -rwx------ 1 lashen UsersGrp 1408 Mar 6 20:21 parameters.mat -rwx------ 1 lashen UsersGrp 25971 Mar 6 19:54 style_transfer.ipynb -rwx------ 1 lashen UsersGrp 96044 Mar 17 12:40 whole_clip.wav FileNotFoundError message --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) &lt;ipython-input-67-6381f1840332&gt; in &lt;module&gt;() ----&gt; 1 convert_spect_to_wav('../dataset_processed/bdl_spectrogram_array.npy') &lt;ipython-input-66-a201b054f438&gt; in convert_spect_to_wav(file_name) 19 20 # Piece together the wav files ---&gt; 21 …
tagged with: python
tagged with: librosa
tagged with: wav
has comment: http://stackoverflow.com/comment/85887157
has title: pydub cannot find *.wav file written by librosa
answer count: 0
tagged with: pydub
downvote count: 0
has comment: http://stackoverflow.com/comment/85773685
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/85696596
has text: thanks! Two answers to my question with two different methods is really helping me understand how I need to be using input and how to use in expressions. appreciate your help!
type: AnswerComment
comment on: http://stackoverflow.com/a/49337898
score: 0
type: Comment

http://stackoverflow.com/a/57197945
has comment: http://stackoverflow.com/comment/140048489
has body: sentence = 'a quick brown fox jumped a another fox' words = sentence.split(' ') solution 1: result = {i:words.count(i) for i in set(words)} solution 2: result = {} for word in words: result[word] = result.get(word, 0) + 1 solution 3: from collections import Counter result = dict(Counter(words))
type: Answer
score: 6
upvote count: 6
downvote count: 0
answers question: http://stackoverflow.com/q/49316102

http://stackoverflow.com/comment/85689138
comment on: http://stackoverflow.com/q/49344455
score: 0
type: Comment
has text: Does `tags.get` return a string? If so, you should be able to use `str.statswith` to do exactly what you want. I'll post an answer below shortly.
type: QuestionComment

http://stackoverflow.com/comment/85584476
type: QuestionComment
has text: @Gang In `pycharm` it gave me unused import statement error, I removed the import statement
comment on: http://stackoverflow.com/q/49290594
score: 0
type: Comment

http://stackoverflow.com/comment/101411540
type: Comment
comment on: http://stackoverflow.com/a/51957328
type: AnswerComment
has text: The point is to not have them there but have PyCharm suggest them to you.
score: 3

http://stackoverflow.com/q/49397960
tagged with: django
has comment: http://stackoverflow.com/comment/85797902
type: Question
score: 0
has body: I wrote my project in python 3 and django 2.0. The deployment environment has another program that relies on it's built in python 2,and whenever it starts it writes it's python 2 path to the system environment variable,so my Django project can never run normally since it finds the wrong version of python. I'm using Windows server 2008 + Apache + mod_wsgi as the deployment environment. How can I deploy my Django project successfully without using any aggressive strategy(like deleting other python paths and add mine)?
has comment: http://stackoverflow.com/comment/85802930
has comment: http://stackoverflow.com/comment/85797968
tagged with: python
has title: How can i deploy django(using python3) on a Windows computer that already has python2 in it's system PATH?
answer count: 0
tagged with: mod-wsgi
type: UnansweredQuestion
tagged with: wsgi
tagged with: apache

http://stackoverflow.com/comment/135772863
type: Comment
has text: It looks like you copied this without attribution from Wei Zong, writing in the openpyxl newsgroup in 2016: https://groups.google.com/g/openpyxl-users/c/1auXBiDlzHk?pli=1 Although you posted it on the same day, so perhaps you ARE Wei Zong :D
comment on: http://stackoverflow.com/a/72181862
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85661894
comment on: http://stackoverflow.com/q/49329394
score: 0
type: Comment
type: QuestionComment
has text: I've noticed that if I try this, the instance of `Company` thus created does not have a `default_package` attribute. What I would actually like to do is when I create a company with the `CompanyFactory`, also create a `Package` object whose `default_for_company` is that company. How might I achieve this?

http://stackoverflow.com/a/49356296
upvote count: 0
downvote count: 1
has body: Most probably the 1865-Lincoln.txt refers to the inaugural speech of president Lincoln. It's available in NLTK from https://github.com/nltk/nltk_data/blob/gh-pages/packages/corpora/inaugural.zip The original source of the document comes from the Inaugural Address Corpus If we check how NLTK is reading the file using LazyCorpusReader, we see that the files are Latin-1 encoded. inaugural = LazyCorpusLoader( 'inaugural', PlaintextCorpusReader, r'(?!\.).*\.txt', encoding='latin1') If you have the default encoding set to utf8, most probably that's where the TypeError: expected string or bytes-like object is occurring You should open the file with an explicit encoding and decode the string properly, i.e. import nltk from nltk import word_tokenize, pos_tag tagged_lines = [] with open('test.txt', encoding='latin1') as fin: for line in fin: tagged_lines.append(pos_tag(word_tokenize(line))) But technically, you can access the inagural corpus directly as a corpus object in NLTK, i.e. &gt;&gt;&gt; from nltk.corpus import inaugural &gt;&gt;&gt; from nltk import pos_tag &gt;&gt;&gt; tagged_sents = [pos_tag(sent) for sent in inaugural.sents('1865-Lincoln.txt')]
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49355114
has comment: http://stackoverflow.com/comment/85712567

http://stackoverflow.com/comment/85893751
type: QuestionComment
has text: I think data is malformed and some attributes are missing. Only line which can cause this error is `loc0 = input_bag[0]` all else (loc0, loc, x) are tuples.
comment on: http://stackoverflow.com/q/49428524
score: 0
type: Comment

http://stackoverflow.com/comment/85781557
comment on: http://stackoverflow.com/a/49379266
has text: It's possibly worth mentioning that in the context of Standard ML which the OP references, this is usually what uncurrying means.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/85693125
type: QuestionComment
has text: Possible duplicate of [Python efficiency: lists vs. tuples](https://stackoverflow.com/questions/6063494/python-efficiency-lists-vs-tuples)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49346696

http://stackoverflow.com/comment/85876636
has text: Nothing guarantees you that user profiles are under `c:\users`, or that the user profile directory is called with the name of the user, or even that the documents directory is actually a subdirectory of the user profile directory.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49437335

http://stackoverflow.com/comment/94528626
has text: If you open 1.0.0 from Gthub you can see crypto.h file , the same file is missing in latest version. Also OpenSSL there is change in DLL names , [they renamed libeay32 to libcrypto](https://github.com/arvidn/libtorrent/issues/1931) You need to post code which makes use of `asn1crypto` libary in the post. Not able to reproduce your issue using `pipenv`. Make sure you are using updated libraries too.
type: QuestionComment
comment on: http://stackoverflow.com/q/49302516
score: 0
type: Comment

http://stackoverflow.com/a/49314271
score: 0
has comment: http://stackoverflow.com/comment/85633363
answers question: http://stackoverflow.com/q/49314033
type: Answer
has comment: http://stackoverflow.com/comment/85630264
has body: timeit.timeit('filter(lambda x : x &gt;= 0, {})'.format(data))
has comment: http://stackoverflow.com/comment/85630168

http://stackoverflow.com/comment/85826482
comment on: http://stackoverflow.com/q/49408644
has text: @MadPhysicist, we get these occasional recommendations to use other parsers, but never any code to show that they work better in the particular problem at hand.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49320747
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/49321008
tagged with: kivy-language
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/49334295
type: Question
has title: Python/Kivy : Call function from one class to another class in python
score: 0
has body: I am using python-2.7 and kivy.I have a file test.py. Can someone tell me how to call def abc(self): from def update(self): ? Now i am using Invoice().abc() for call then it prints calling but not showing label and value test.py from kivy.uix.label import Label from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.core.window import Window from functools import partial from kivy.uix.popup import Popup from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (600, 600) class MyLabel(Label): pass class check(Popup): mode = StringProperty("") col_data = ListProperty(["?"]) def __init__(self, obj, **kwargs): super(check, self).__init__(**kwargs) if obj.mode == "Update": cur.execute("select `column` from `table_name` where `id`=?",(edit_id,)) row = cur.fetchone() self.col_data[1] = row[0] def update(self): #do some stuff after call abc function Invoice().abc() class Invoice(Screen): def __init__(self, **kwargs): super(Invoice, self).__init__(**kwargs) def abc(self): print('calling') #fetching from database arr = [(11, 'Item1', '1001'), (12, 'Item2', '2001'), (13, 'Item3', '102')] layout = self.ids['invoices'] for row in arr: layout.add_widget(MyLabel(text=str('[ref=world]' + row[1]) + '[/ref]', size_hint_x=.35, halign='left', markup=True, on_ref_press=partial(self.open_form, row[0]))) def open_form(self, id, *args): global edit_id edit_id = id self.mode = "Update" check(self)

http://stackoverflow.com/comment/85656129
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49324062
score: 0
has text: @MrT thanks for the guideline, I am new here. And now I make the question clear.

http://stackoverflow.com/comment/85840898
comment on: http://stackoverflow.com/a/49418165
type: Comment
type: AnswerComment
has text: I recommend you not mix the .py with the .qml much, create an object made in python but manage the visibility in the QML. I mean try to do most things in the QML, and if you can not do it just in the .py. To load new components there are Loaders or Component. QML is prepared to do most things, in fact many QML things are written in python.
score: 0

http://stackoverflow.com/q/49432918
tagged with: xml-sitemap
answer count: 1
tagged with: google-api-python-client
tagged with: google-search-console
has body: I'm writing a Python script to submit sitemaps in a row to the Search Console. Python quickstart example is working OK : https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python I tried with the following code to submit my sitemaps: CLIENT_ID = 'xxxxx' CLIENT_SECRET = 'yyyyyy' OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters' # Redirect URI for installed apps REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print ('Go to the following link in your browser: ' + authorize_url) code = input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) webmasters_service = build('webmasters', 'v3', http=http) WEBSITE = 'http://www.mywebsite.com' SITEMAP_PATH = 'http://www.mywebsite.com/sitemaps/' SITEMAPS_LIST = ['sitemap1.xml','sitemap2.xml','sitemap3.xml'] print ('Adding sitemaps to website ' + WEBSITE) for sitemap in SITEMAPS_LIST: print (' '+SITEMAP_PATH + sitemap) webmasters_service.sitemaps().submit(siteUrl=WEBSITE, feedpath=SITEMAP_PATH + sitemap) No error. But the sitemaps are not added to my Search Console. If I try to add a file manually in Search Console or through the API explorer web interface, it's working.
type: Question
type: UnansweredQuestion
tagged with: python
has title: Submit sitemaps using Python and Google Search Console API
score: 0
has answer: http://stackoverflow.com/a/49945839

http://stackoverflow.com/q/49356541
has body: I am using TensorFlow for Poets to detect features in clothing images. I have trained 4 different models(sleeve, shape, length &amp; hemline). Now i pass image urls to each of the model and store the result. Since i have huge data (100k images), so using spark to broadcast 4 models once and passing image RDD to detect the features. It's taking exponential time. It starts from 3 secs/images &amp; keep increasing the execution time. When scripts already sensed 10k images, its execution time reaches to 8 secs/ images. I am new to Tensorflow, will be very thankful if get any idea to make the execution time linear. def getLabelDresses(file_name): resultDict = {} 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_name = "import/" + input_layer output_name = "import/" + output_layer with tf.Graph().as_default() as g: graph_def = tf.GraphDef() graph_def.ParseFromString(model_data_hemline.value) tf.import_graph_def(graph_def) input_operation_hemline = g.get_operation_by_name(input_name); output_operation_hemline = g.get_operation_by_name(output_name); with tf.Session() as sess: results = sess.run(output_operation_hemline.outputs[0],{input_operation_hemline.outputs[0]: t}) results = np.squeeze(results) top_k = results.argsort()[-1:][::-1] labels = load_labels(label_file_hemline) resultDict['hemline'] = labels[top_k[0]] with tf.Graph().as_default() as g: graph_def = tf.GraphDef() graph_def.ParseFromString(model_data_shape.value) tf.import_graph_def(graph_def) input_operation_shape = g.get_operation_by_name(input_name); output_operation_shape = g.get_operation_by_name(output_name); with tf.Session() as sess: results = sess.run(output_operation_shape.outputs[0],{input_operation_shape.outputs[0]: t}) results = np.squeeze(results) top_k = results.argsort()[-1:][::-1] labels = load_labels(label_file_shape) resultDict['shape'] = labels[top_k[0]] with tf.Graph().as_default() as g: graph_def …
tagged with: pyspark
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/49357995
type: AnsweredQuestion
score: 0
tagged with: deep-learning
answer count: 1
has title: TensorFlow Model takes exponential time on large dataSet
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49357995
type: Question

http://stackoverflow.com/a/49378860
accepted answer of: http://stackoverflow.com/q/49378776
has body: You need to use global count in each function that is assigning to count def gender(bot, update): global count ... and def main(): global count ... Better would be to avoid the global. Just make count a local variable in main and pass it in and out of gender etc. def gender(bot, update, count): ... return count
answers question: http://stackoverflow.com/q/49378776
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/140075431
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/79418853
has text: how is this answer different from the [accepted answer](https://stackoverflow.com/a/49329034/3157428)?
type: Comment

http://stackoverflow.com/comment/85831080
type: QuestionComment
has text: Also, the minpts value is way too high.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49381679

http://stackoverflow.com/q/49395395
has title: Web-scraping with beautifulsoup in different siblings
tagged with: selenium
tagged with: web-scraping
tagged with: python
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49395607
score: 0
has answer: http://stackoverflow.com/a/49396802
linked to: http://stackoverflow.com/q/8949252
has body: I've tried different ways to scrape Answer1 and Answer2 from a website through BeautifulSoup, urllib and Selenium, but without success. Here's the simplified version: Question1 Answer1 Question2 Answer2 In selenium, I try to find Question1, then go to its parent and scrape Answer1. Below is the code I use, although it's not correct. browser.find_elements_by_xpath("//span[contains(text(), 'Question1')]/parent::p/following::strong") I believe bs is more efficient than selenium in this case. How would you do this in bs? Thanks! Edit: @Juan's solution is perfect for my example. However, I realized it's inapplicable to the website https://finance.yahoo.com/quote/AAPL?p=AAPL . Can anyone shed some light on parsing Consumer Goods and Electronic Equipment from there? And would it be better to use urllib.requests instead? Thank you.
has comment: http://stackoverflow.com/comment/85804129
type: Question
has comment: http://stackoverflow.com/comment/85834282
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/85798584
has text: Can you use a short timeout with the call to `select`? Then, if a timeout occurs, handle events normally. I can get your code working handling events in a basic fashion after a select timeout, what does your client code look like. A [Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve) would make it easier to help you.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49389111

http://stackoverflow.com/comment/85759716
type: QuestionComment
has text: it is very hard to solve cause I don't have access to your resource, I can only suggest using a more robust client like **requests** that might solve the issue http://docs.python-requests.org/en/master/
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49379532

http://stackoverflow.com/q/49393650
has title: How can I find out what is causing vim to interpret python files?
has comment: http://stackoverflow.com/comment/85789171
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49393751
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85789049
has body: After many years, I'm finally cleaning up my .vimrc and digging into how the settings really, really work. I spent a lot of the day trimming cruft and reading help files. Now I'm down to a pretty minimal .vimrc that I'm pretty comfortable with -- and I believe I understand what each thing in it does (lots of commenting). I'll include my .vimrc at the bottom of this question. My problem is, I am working in Python (for the first time) and somehow vim has a bunch of settings (I don't like) for it--seemingly built-in. How can I either: Figure out what is causing those settings and turn it off Get it to give me a nice, blank slate for python files so I can select what settings I want? Notes: I deleted my .viminfo file (after backing it up) to get everything clean. When I open a python file and type :set, here is what I get: :set --- Options --- autoindent helplang=en modified scroll=38 smartindent textwidth=76 comments=b:#,fb:- hlsearch number scrolloff=5 softtabstop=4 ttyfast expandtab incsearch relativenumber shiftwidth=4 suffixesadd=.py ttymouse=sgr filetype=python keywordprg=pydoc ruler showmatch syntax=python wildignore=*.pyc backspace=indent,eol,start cinkeys=0{,0},0),:,!^F,o,O,e commentstring=# %s fileencoding=utf-8 fileencodings=ucs-bom,utf-8,default,latin1 include=^\s*\(from\|import\) includeexpr=substitute(v:fname,'\.','/','g') indentexpr=GetPythonIndent(v:lnum) indentkeys=0{,0},:,!^F,o,O,e,&lt;:&gt;,=elif,=except omnifunc=pythoncomplete#Complete printoptions=paper:letter runtimepath=~/.vim,~/.vim/bundle/vundle,~/.vim/bundle/tabular,~/.vim/bundle/vim- es6,/var/lib/vim/addons,/usr/share/vim/vimfiles,/usr/ share/vim/vim74,/usr/share/vim/vimfiles/after,/var/lib/vim/addons/after,~/.vim/after,~/.vim/bundle/Vundle.vim/,~/.vim/bundle/vundle/after,~/.vim/bundle/tabular/after,~/.vim/bundle/vim-es6/after Notice that shiftwidth=4 and softtabstop=4, for example. If I open a blank file, here's the :set I get: :set --- Options --- autoindent number shiftwidth=2 ttyfast expan…
has answer: http://stackoverflow.com/a/49399874
has comment: http://stackoverflow.com/comment/85789213
accepted answer: http://stackoverflow.com/a/49399874
tagged with: python
possible better answer: http://stackoverflow.com/a/49393751
tagged with: vim
type: AnsweredQuestion
answer count: 2
score: 1

http://stackoverflow.com/a/49375134
score: 5
has body: In python 3 you can specify encoding with open context. with open(file, encoding='utf-8') as f: data = f.read()
downvote count: 0
has comment: http://stackoverflow.com/comment/85752965
upvote count: 5
answers question: http://stackoverflow.com/q/49375101
type: Answer
has comment: http://stackoverflow.com/comment/85751468

http://stackoverflow.com/comment/85768398
type: AnswerComment
score: 1
has text: Sorry, I misunderstood your notation. By ```X_original``` I mean the matrix that is plugged into the ```transform()``` method, and it has nothing to do with the matrix that was used to train the model (to calculate ```W```).
type: Comment
comment on: http://stackoverflow.com/a/49383384

http://stackoverflow.com/q/49320599
tagged with: python
has comment: http://stackoverflow.com/comment/85646268
has comment: http://stackoverflow.com/comment/85644262
has comment: http://stackoverflow.com/comment/85645452
has comment: http://stackoverflow.com/comment/85642305
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85646471
has comment: http://stackoverflow.com/comment/85646739
answer count: 2
has answer: http://stackoverflow.com/a/49321145
downvote count: 0
has answer: http://stackoverflow.com/a/49320657
possible better answer: http://stackoverflow.com/a/49320657
has title: Elastic search not giving data with big number for page size
has body: Size of data to get: 20,000 approx Issue: searching Elastic Search indexed data using below command in python but not getting any results back. from pyelasticsearch import ElasticSearch es_repo = ElasticSearch(settings.ES_INDEX_URL) search_results = es_repo.search( query, index=advertiser_name, es_from=_from, size=_size) If I give size less than or equal to 10,000 it works fine but not with 20,000 Please help me find an optimal solution to this. PS: On digging deeper into ES found this message error: Result window is too large, from + size must be less than or equal to: [10000] but was [19999]. See the scrolling API for a more efficient way to request large data sets.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85642184
has comment: http://stackoverflow.com/comment/85644652
upvote count: 5
tagged with: pyelasticsearch
score: 5
accepted answer: http://stackoverflow.com/a/49321145
tagged with: elasticsearch

http://stackoverflow.com/q/49336064
has answer: http://stackoverflow.com/a/49336131
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49336178
possible better answer: http://stackoverflow.com/a/49336118
tagged with: python
has body: I have a list of lists containing: animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']] and I want to join the string elements in each list inside the animal table so that it becomes a single string: animal = [[1, 'Crocodile, Lion'],[2, 'Eagle, Sparrow'],[3,'Hippo, Platypus, Deer']] I tried using a for loop to join them: for i in range(len(animal)): ''.join(animal[1:]) #string at index 1 and so on print(animal) I'm getting a type error saying "TypeError: sequence item 0: expected str instance, list found".
has title: Joining two strings within a list of list
has answer: http://stackoverflow.com/a/49336427
has answer: http://stackoverflow.com/a/49336138
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85673518
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49336134
has answer: http://stackoverflow.com/a/49336118
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/49336198
accepted answer: http://stackoverflow.com/a/49336138

http://stackoverflow.com/comment/85636651
score: 0
type: Comment
has text: Why don't you create a [conftest.py](https://docs.pytest.org/en/2.7.3/plugins.html?highlight=re) file and move your fixtures there, so they are available in either module.
type: QuestionComment
comment on: http://stackoverflow.com/q/49303494

http://stackoverflow.com/comment/85735718
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49367347
has text: @Dark, in terms of complexity, doesn't `groupby` need O(n log n) ?
type: AnswerComment

http://stackoverflow.com/q/49393451
tagged with: while-loop
score: 1
has comment: http://stackoverflow.com/comment/85798632
tagged with: python
has comment: http://stackoverflow.com/comment/85788586
tagged with: pygame
has answer: http://stackoverflow.com/a/49393557
has comment: http://stackoverflow.com/comment/85788670
has title: Python: the While loop at the end keeps generating a new random card, how can I get it to generate once and stop?
tagged with: random
upvote count: 2
type: UnansweredQuestion
answer count: 1
has body: The code below is skeletal, it is supposed to be the beginning of a card game. I generated a random hand (1 card for now) but I can't seem to get it to only generate the first hand once. The while loop repeats and constantly generates a new random card for the first hand. edit: it no repeatedly generates a random card but now it crashes import pygame, sys, random from pygame.locals import* WINWIDTH = 1200 WINHEIGHT = 800 CARDTHUMBWIDTH = 50 CARDTHUMBHEIGHT = 80 FPS = 30 FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINWIDTH,WINHEIGHT)) pygame.display.set_caption('NBA Card Game') pygame.init() playerHandPos = [(17, 635), (75, 635), (133, 635), (191, 635), (249, 635), (307, 635), (365, 635), (423, 635), (481, 635), (539, 635)] lakersDeck = ['Lakers_01.png', 'Lakers_02.png', 'Lakers_03.png', 'Lakers_04.png', 'Lakers_05.png', 'Lakers_06.png', 'Lakers_07.png', 'Lakers_08.png', 'Lakers_09.png', 'Lakers_10.png'] turnCount = 0 font = pygame.font.SysFont(None, 30) userTextPrompt = "20, 725" playMat = pygame.image.load('playmat.png') detailBox = pygame.image.load('detailBox.png') DISPLAYSURF.blit(playMat, (0,0)) def terminate(): pygame.quit() sys.exit() ##def drawText(text, font, surface, x, y): ## textobj = font.render(text, 1, (0,0,0)) ## textrect = textobj.get_rect() ## textrect.topleft = (x,y) ## surface.blit(textobj, textrect) def getFirstHand(): random.shuffle(lakersDeck) firstHand = [lakersDeck[0], lakersDeck[1], lakersDeck[2], lakersDeck[3]] return firstHand def displayHand(): cardThumb = pygame.image.load(playerHand[0]) cardThumb = pygame.transform.scale(cardThumb, (50,80)) DISPLAYSURF.blit(cardThumb, playerHandPos[0]) pygame.display.update() def playerTurn(): placedBench = False while placedBench == False: drawText("Choose a card for your bench.", font, DISPLAYSURF, 20, 725) pygame.display.update() def cardLakers_01(): offense = 10 return offense while True: playerHand = [] mouse = pygame.mouse.get_pos() print(mouse) if turnCount == 0: getFir…
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85788753

http://stackoverflow.com/a/49427020
type: Answer
answers question: http://stackoverflow.com/q/49425997
score: 2
upvote count: 2
has body: One approach would be generating the combinations mesh out of x,y,z, then using kd-tree based quick nearest-neighbor lookup to trace back the indices. Thus, we would have one vectorized solution, like so - from itertools import product from scipy.spatial import cKDTree # Form all combinations combs = np.array(list(product(x, y, z))) # Find closest indices for each pt in coords closest_idx = cKDTree(combs).query(coords, k=1)[1] # Index into data array and retrieve the output data2Out = data.ravel()[closest_idx] Memory saving We could optimize on memory by using the kd-tree computation on the three coordinates separately, thereby avoding the combinations creating part and hopefully boosting performance, like so - I = cKDTree(x[:,None]).query(coords[:,[0]], k=1)[1] J = cKDTree(y[:,None]).query(coords[:,[1]], k=1)[1] K = cKDTree(z[:,None]).query(coords[:,[2]], k=1)[1] data2Out = data[I,J,K]
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49425997

http://stackoverflow.com/comment/85695861
score: 0
has text: Can we see the code that you are using not just the error message? And what version of Python are you using?
comment on: http://stackoverflow.com/q/49348091
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85839584
comment on: http://stackoverflow.com/q/49419009
type: Comment
type: QuestionComment
score: 1
has text: It is not clear what you expect to happen that is not happening. Try to reduce the code to the bare essentials. See https://stackoverflow.com/help/mcve

http://stackoverflow.com/q/49403119
tagged with: visa
downvote count: 0
answer count: 1
has title: Python cannot find a usbtmc device
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: usb
tagged with: python
has answer: http://stackoverflow.com/a/49415512
has body: I'm trying to communicate with a hardware device I have (Yokogawa GS200 DC source). I am using Anaconda\Spyder my development environment. I am using Win10 and a 64bit system. The device has a driver (the 64bit version) and is recognized by my PC (shown in the device manager. when I use: import visa rm = visa.ResourceManager() lst = rm.list_resources('?*') print(lst) It does not return the GS200 device. If I try to open the device by sepcifying the adress: my_instrument = rm.open_resource("USB0::0x0B21::0x0039::91U118228::INSTR") I get: VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location information or the requested device or resource is not present in the system. I tried this code (seen answered elsewhere): import serial.tools.list_ports list = serial.tools.list_ports.comports() connected = [] for element in list: connected.append(element.device) print("Connected COM ports: " + str(connected)) which returns: Connected COM ports: [] Moreover, I have reinstalled the driver. disconnected and reconnected, restarted my PC and nothing changed the status. I have tried using this code as well: import visa rmNI = visa.ResourceManager(r'C:\Windows\System32\visa32.dll') rmNI.list_resources() print(rmNI.list_resources()) and the device still is not detected. Would love to hear any suggestion! Thanks!!

http://stackoverflow.com/q/49372825
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: os.walk
type: Question
has comment: http://stackoverflow.com/comment/85747361
tagged with: for-loop
has title: This code opens and holds open the file referenced at 'oldfile'. Where does the opening of the file occur?
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/85746943
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85747028
has comment: http://stackoverflow.com/comment/85747082
has body: I'm not a frequent programmer but I have some understanding of what I'm doing so I hope I will be able to understand the answers I get! I have been creating a python script to go through a folder, find video files above a certain size/resolution ratio and re-encode them using handbrake. When I run the code below it all works fine until line 104 (which is part of the file manipulation to clean up the folder after the re-encoding has been done) # Run Program: # python "R:\Documents\Scripts\Filebot\hb-postprocess-folder.pyw" "%D" # # Test with Console: # python "R:\Documents\Scripts\Filebot\hb-postprocess-folder.pyw" "R:\Movies" import sys import subprocess import fnmatch import os import shutil import cv2 import time from subprocess import Popen, CREATE_NEW_CONSOLE sizecutoff1080p = 9 sizecutoff4K = 12 '''for line in sys.argv: print(line)''' # configuration if len(sys.argv) &gt;= 4: sizecutoff4K = int(sys.argv[3]) if len(sys.argv) &gt;=3: sizecutoff1080p = int(sys.argv[2]) if len(sys.argv)&lt;2: raise RuntimeError("Need to at least specify a folder to work on - preferably some sizes for cut offs too") print("cutoffs") print(str(sizecutoff1080p)) print(str(sizecutoff4K)) GBsize = 1073741824 hbroot = 'R:\Converted\AutoHandbrake' output = 'R:/' hbtemp = hbroot if not os.path.exists(hbroot): os.makedirs(hbroot) # required args #directory = 'R:\Movies' directory = sys.argv[1] #directory = os.getenv(radarr_movie_path) directory=os.path.abspath(directory) '''print(kind)''' head, tail = os.path.split(directory) hbtemp = os.path.join(hbroot,tail) if not os.path.exists(hbtemp): os.makedirs(hbtemp) for dirname, subdirlist, filelist in os.walk(directory): parent=os.path.abspath(dirname) print('Parent path is', str(parent)) relpath=os.path.relpath(parent, directory) hbparent= os.path.join(hbtemp,relpath) if not os.path.exists(hbparent): os.makedirs(hbparent) for fname in filelist: sizecutoff=sizecutoff1080p #print('File is', str(fname)) vid=cv2.VideoCapture(os.path.join(parent, fn…

http://stackoverflow.com/comment/85644222
type: Comment
has text: My suspicion is that `file_list` is empty or a list of tuples because the `os.walk` function returns a tuple, not just filename. You might need to use a similar `for` statement to the one used to walk the `src` dir. Also, your src path will not be correct in the second loop since all you have is the filename and not the full path. Joining the root dir of `src` will not be the correct path.
type: QuestionComment
comment on: http://stackoverflow.com/q/49321445
score: 1

http://stackoverflow.com/comment/85676110
comment on: http://stackoverflow.com/q/49337715
type: QuestionComment
type: Comment
has text: @ArndtJonasson, Thanks, It looks like the problem here.. Let me check if it's the case. Also other suggestions would be great help..
score: 0

http://stackoverflow.com/q/49419095
has answer: http://stackoverflow.com/a/49436806
type: Question
accepted answer: http://stackoverflow.com/a/49419385
answer count: 2
upvote count: 1
tagged with: python
tagged with: python-3.6
favorite count: 0
has answer: http://stackoverflow.com/a/49419385
type: AnsweredQuestion
has body: I am trying to find pid of a oracle process by using below command ps -ef | grep pmon | grep orcl | grep -v grep When trying to use python oracle_pid = os.system("echo ps -ef | grep pmon | grep %s | grep -v grep | awk '{print $2}'" %(oracle_sid)) print(oracle_pid) it is printing 0 as value Any suggestions on how to achieve just the pid as output? Regards
downvote count: 0
score: 1
has title: Find pid using python by grepping two variables
possible better answer: http://stackoverflow.com/a/49436806

http://stackoverflow.com/comment/85633476
type: QuestionComment
has text: You should listen to the `QKeyEvent` events and keep track of which keys are down.
score: 1
comment on: http://stackoverflow.com/q/49316067
type: Comment

opengl
tags question: http://stackoverflow.com/q/49339670
tags question: http://stackoverflow.com/q/49303997
tags question: http://stackoverflow.com/q/49309631
tags question: http://stackoverflow.com/q/49302201
type: Tag
tag name: opengl

http://stackoverflow.com/a/49421793
score: 1
has comment: http://stackoverflow.com/comment/85845708
has comment: http://stackoverflow.com/comment/85845347
type: Answer
has comment: http://stackoverflow.com/comment/85845746
has comment: http://stackoverflow.com/comment/85845413
has body: You can use: df = (df.drop('Col1', 1) .set_index(['ID','DAY']) .stack() .reset_index(level=2, drop=True) .unstack()) print (df) DAY Mon Tue Wed ID ABC 123.0 123.0 123.0 DEF 456.0 456.0 456.0 GHI 789.0 789.0 789.0 Explanation: Remove unnecessary column Col1 by drop Create index by set_index Reshape by stack for remove NaNs and columns names to MultiIndex Remove 2 level of MultiIndex by reset_index Reshape by unstack EDIT: df = (df.drop('Col1', 1) .set_index('DAY', append=True) .stack() .reset_index(level=2, drop=True) .unstack() ) print (df) DAY Mon Tue Wed ID ABC 123.0 123.0 123.0 DEF 456.0 456.0 456.0 GHI 789.0 789.0 789.0 EDIT1: Add reindex: df = (df.drop('Col1', 1) .set_index('DAY', append=True) .stack() .reset_index(level=2, drop=True) .unstack() .reindex(columns=['Wed','Tue','Mon']) ) print (df) DAY Wed Tue Mon ID ABC 123.0 123.0 123.0 DEF 456.0 456.0 456.0 GHI 789.0 789.0 789.0
has comment: http://stackoverflow.com/comment/85847123
has comment: http://stackoverflow.com/comment/85846273
accepted answer of: http://stackoverflow.com/q/49421753
has comment: http://stackoverflow.com/comment/85846894
has comment: http://stackoverflow.com/comment/85845578
has comment: http://stackoverflow.com/comment/85847191
has comment: http://stackoverflow.com/comment/85845832
has comment: http://stackoverflow.com/comment/85845623
has comment: http://stackoverflow.com/comment/85847160
downvote count: 0
answers question: http://stackoverflow.com/q/49421753
upvote count: 1
has comment: http://stackoverflow.com/comment/85844452
has comment: http://stackoverflow.com/comment/85844459
has comment: http://stackoverflow.com/comment/85846696
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85846749
has comment: http://stackoverflow.com/comment/85845850
has comment: http://stackoverflow.com/comment/85847146

http://stackoverflow.com/comment/85621452
type: Comment
has text: They recommended me to use Celery. Then what is the point to use Celery?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49308370

http://stackoverflow.com/a/49345288
score: 0
has body: In Python, keyword arguments names, like parameter names, have to be identifiers—the same rules as for variable names, function names, etc. This isn't really explained in the tutorial. It is described precisely in the reference, but that's not exactly novice-friendly. Anyway, this means the shorthand dict(key1=value1, key2=value2) doesn't work for all dictionaries, just dictionaries whose keys are strings that are valid identifiers. Of course you can always just use a dict display, as you did with test_dic. This usually comes up in more advanced code, where you try to call something like func(**test_dic), which expands into the equivalent of func(1='I', 2='love') and gives you a very mysterious error, so… be glad you ran into this earlier, where it's easier to understand.
type: Answer
answers question: http://stackoverflow.com/q/49345236

http://stackoverflow.com/comment/85829529
type: Comment
score: 0
type: AnswerComment
has text: this is more complex, but I will try something here
comment on: http://stackoverflow.com/a/49393396

http://stackoverflow.com/comment/93153929
score: 7
type: Comment
comment on: http://stackoverflow.com/a/53119715
has text: While I am not working with Google Colab anymore, I have to disagree. While this answer is maybe not in correct StackOverflow style, it at least provides future interested readers some material/tutorial they can follow to maybe get an answer. Thanks for the contribution
type: AnswerComment

http://stackoverflow.com/comment/86075130
has text: what do you get if you run this `curl -XGET localhost:9200`?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49526918
score: 0

http://stackoverflow.com/comment/85835936
score: 0
type: Comment
type: QuestionComment
has text: For MNIST, we have 10 classes i.e. 0,1,2,3...9. For each class, we have 6000 images, a total of 60k images. A class centre would be the centre of deep features of each class.
comment on: http://stackoverflow.com/q/49416912

http://stackoverflow.com/comment/85786663
type: QuestionComment
comment on: http://stackoverflow.com/q/49391892
score: 0
type: Comment
has text: I found the exporters.py file and added in the comma before the /n, thank you very much for your solution. Still trying to find a way to add the square brackets.

http://stackoverflow.com/comment/85918379
score: 0
comment on: http://stackoverflow.com/q/49436606
has text: @bzier, details are added.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49323616
accepted answer of: http://stackoverflow.com/q/49323171
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/49323171
has comment: http://stackoverflow.com/comment/85649593
upvote count: 3
type: AcceptedAnswer
has body: This is one way using just numpy.linalg.norm. import pandas as pd, numpy as np df1['coords1'] = list(zip(df1['latitude1'], df1['longitude1'])) df2['coords2'] = list(zip(df2['latitude2'], df2['longitude2'])) def calc_min(x): amin = np.argmin([np.linalg.norm(np.array(x)-np.array(y)) for y in df2['coords2']]) return df2['coords2'].iloc[amin] df1['closest'] = df1['coords1'].map(calc_min) # latitude1 longitude1 coords1 closest # 0 40.748043 -73.992953 (40.748043, -73.992953) (42.50779, 1.52109) # 1 42.361016 -71.020005 (42.361016, -71.020005) (42.50779, 1.52109) # 2 25.361016 54.000000 (25.361016, 54.0) (25.0657, 55.17128) Setup from io import StringIO mystr1 = """latitude1|longitude1 40.748043|-73.992953 42.361016|-71.020005 25.361016|54.0000 """ mystr2 = """latitude2|longitude2 42.50729|1.53414 42.50779|1.52109 25.56473|55.55517 25.78953|55.94320 25.33132|56.34199 25.06570|55.17128 25.59246|56.26176 25.61955|56.27291 25.33737|55.41206 24.11028|52.73056""" df1 = pd.read_csv(StringIO(mystr1), sep='|') df2 = pd.read_csv(StringIO(mystr2), sep='|') If performance is an issue, you can vectorize this calculation fairly easily via the underlying numpy arrays.
has comment: http://stackoverflow.com/comment/85650809

http://stackoverflow.com/q/49397920
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85797799
tagged with: python
has title: Matplotlib: Subplots with Dates Not Consistent Formatting
tagged with: formatting
type: Question
tagged with: graphing
has comment: http://stackoverflow.com/comment/85806609
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85798053
score: 0
linked to: http://stackoverflow.com/q/20109391
tagged with: pandas
has body: The formatting of of x-axis ticks are not consistent between the different subplots. I've tried manipulating by increasing space and formatting the dates, but nothing is working. All of the records in the date column are in fact dates. fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,10), sharey='all') plt.subplots_adjust(hspace = 0.3) daily_performance[0].plot(x='date', y='return 1 day', kind='line', ax=ax[0,0]) daily_performance[1].plot(x='date', y='return 1 day', kind='line', ax=ax[0,1]) daily_performance[2].plot(x='date', y='return 1 day', kind='line', ax=ax[1,0]) daily_performance[3].plot(x='date', y='return 1 day', kind='line', ax=ax[1,1]) plt.show() Sample Data shown below: [ date open hi lo close return 1 day return 3 day \ 0 2014-01-13 71.27 71.6000 69.49 70.12 -0.018340 -0.119869 1 2014-01-14 69.90 72.8200 69.58 72.67 0.036366 -0.013038 2 2014-01-15 72.74 73.4100 72.18 73.22 0.007568 0.025059 3 2014-01-16 73.16 73.4975 72.23 73.10 -0.001639 0.042499 4 2014-01-17 73.34 75.4500 73.06 75.42 0.031737 0.037842 return 5 day 0 -0.115986 1 -0.092306 2 -0.080959 3 -0.007198 4 0.055859 , date open hi lo close return 1 day return 3 day \ 5 2016-02-08 104.67 105.750 98.15 100.44 -0.045066 -0.097817 6 2016-02-09 99.70 101.160 94.01 96.28 -0.041418 -0.123293 7 2016-02-10 97.06 99.495 96.15 96.91 0.006543 -0.078627 8 2016-02-11 95.00 96.570 93.45 94.71 -0.022701 -0.057049 9 2016-02-12 95.51 99.040 94.36 98.63 0.041390 0.024408 return 5 day 5 -0.167302 6 -0.164164 7 -0.129525 8 -0.137589 9 -0.062274 , date open hi lo close return 1 day return 3 day \ 10 2016-02-09 99.70 101.160 94.01 96.28 -0.041418 -0.123293 11 2016-02-10 97.06 99.495 96.15 96.91 0.006543 -0.078627 12 2016-02-11 95.00 96.570 93.45 94.71 -0.022701 -0.057049 13 2016-02-12 95.51 99.040 94.36 98.63 0.041390 0.024408 14 2016-02-16 100.10 105.480 100.00 104.15 0.055967 0.074708 return 5 day 10 -0.164164 11 -0.129525 12 -0.137589 13 -0.062274 14 0.036937 , date open hi lo close return 1 day return 3 day \ 1…

http://stackoverflow.com/q/49286100
type: AnsweredQuestion
score: 0
tagged with: tkinter
upvote count: 1
has comment: http://stackoverflow.com/comment/85575212
answer count: 1
downvote count: 1
has title: how to add sound to a message receiving function
linked to: http://stackoverflow.com/q/48400158
has body: I am currently developing a Python-based chat program and I am trying to figure out how I would add a notification sound for when the user receives a message here's the message receive function for the client what i want to do is i wanna have a sound that will play when the user gets a message def receive(): """Handles receiving of messages.""" while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") msg_list.insert(tkinter.END, msg) except OSError: # Possibly client has left the chat. break
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85576339
tagged with: python
has answer: http://stackoverflow.com/a/49286200
accepted answer: http://stackoverflow.com/a/49286200
has comment: http://stackoverflow.com/comment/85575053

http://stackoverflow.com/comment/85594328
comment on: http://stackoverflow.com/q/49287794
has text: Are you sure `form.is_valid()` doesn't return`False`? Do you actually display the errors when the form is invalid? You should pass the form that you called `is_valid()` in the context. `is_valid` will modify the form object and add error messages that will be rendered in the template. Move the line `dict_DictWord = {'words': query_list,"form":form}` to just before the final `return render` line. Then the invalid `form` will be included in the context if validation failed.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/49321165
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/85643414
type: AnsweredQuestion
answer count: 3
has body: I am working with a dataframe which has a column 'Col' of type Float. The values of the columns have too many decimals (example: 1.00000000000111). How can I limit the column to save values with only 1 decimal (example: 1.0)?
has title: How can I delimit a Float type column of a dataframe to have no more than 1 decimal in Pyspark?
has answer: http://stackoverflow.com/a/49321795
possible better answer: http://stackoverflow.com/a/49321795
has answer: http://stackoverflow.com/a/49321339
has comment: http://stackoverflow.com/comment/85648574
linked to: http://stackoverflow.com/q/48832493
type: Question
has answer: http://stackoverflow.com/a/49321780
accepted answer: http://stackoverflow.com/a/49321780
tagged with: decimal
score: 0
tagged with: apache-spark-sql

http://stackoverflow.com/q/49397373
has title: Tensorflow GPU - ImportError: Could not find 'nvcuda.dll'
tagged with: anaconda
upvote count: 9
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49397448
tagged with: scripting
tagged with: python
downvote count: 5
has comment: http://stackoverflow.com/comment/85796529
score: 4
answer count: 2
has body: ImportError: Could not find 'nvcuda.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Typically it is installed in 'C:\Windows\System32'. If it is not present, ensure that you have a CUDA-capable GPU with the correct driver installed. please solve this error i am doing FYP
has comment: http://stackoverflow.com/comment/85796560
has answer: http://stackoverflow.com/a/51509608
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/85805116
type: Comment
has text: No, I can't honestly see any way that would help. The Cython docs recommend that if you want to use numeric Python types like `int` instead of their C counterparts, simply omit the type declaration and let them be objects.
comment on: http://stackoverflow.com/q/49401640
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85700016
has text: I've attached the logs and the error above, 'NoneType' is not subscriptable
comment on: http://stackoverflow.com/a/49328156
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85679929
has text: I re-run the cycle-finding method on sub-graphs *after* shuffling the list of nodes to remove the potential bias you suggested. The results remain roughly the same - I observed more variability in the base of the powers. The conclusions remain the same, of course. To follow-up on your last comment: if `k <= 4`, then I think a brute-force solution may be computable. I do not know about the graph libraries available in Python - it might be worth asking on SO about it? Or maybe you can try to write a brute-force algorithm in python?
type: Comment
comment on: http://stackoverflow.com/a/49336096
score: 0
type: AnswerComment

http://stackoverflow.com/a/49327718
upvote count: 3
downvote count: 0
score: 3
has body: Here is one way. Create a temp DataFrame by sorting the columns and re-indexing. Then use the new index as the rank and join back to the original df. temp_df = df.sort_values(['col_a', 'col_b']).reset_index() temp_df['rank'] = temp_df.index + 1 print(temp_df) # index col_a col_b rank #0 1 0 2 1 #1 0 0 5 2 #2 2 0 8 3 #3 3 1 3 4 #4 5 1 4 5 #5 4 1 7 6 The column 'index' corresponds to the index in the original DataFrame. Use this to join temp_df back to df and select the columns you want: df = df.join(temp_df.set_index('index'), rsuffix="_r")'col_a', 'col_b', 'rank' print(df) # col_a col_b rank #0 0 5 2 #1 0 2 1 #2 0 8 3 #3 1 3 4 #4 1 7 6 #5 1 4 5
type: Answer
answers question: http://stackoverflow.com/q/49327240

http://stackoverflow.com/comment/85745111
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49349544
has text: because it is a cyclic graph.

http://stackoverflow.com/comment/85834232
type: Comment
type: QuestionComment
has text: You print it by suit and number. Don't do that (mainly because it's useless); print a *deck* instead. You can choose how to arrange the number of rows and columns by changing the number of iterations in the major (row-wise) and minor (column-wise) print operations.
score: 0
comment on: http://stackoverflow.com/q/49416016

http://stackoverflow.com/q/49304400
has comment: http://stackoverflow.com/comment/85610949
type: Question
has body: In Python 3, I am trying to connect attributes of an object to equivalent attributes of its proxy object (identified by its "_proxy" suffix). Here's the code: import maya.cmds as mc attributes = ['.t', '.r', '.s'] controllers = mc.ls('ctrl_Lip*') def corresponding_proxy(controller): corresponding_proxy = mc.ls(controller+'_proxy') return corresponding_proxy for controller in controllers : for attr in attributes : mc.connectAttr(controller+attr, corresponding_proxy(controller)+attr) The error returned is : # Error: TypeError: file &lt;maya console&gt; line 13: can only concatenate list (not "str") to list # I don't understand, because I thought controller, corresponding_proxy and attr were all strings. What did I miss? Ok jasonharper is right, returning controller+'_proxy' makes it work ! However it now throws another error at me : # Error: RuntimeError: file &lt;maya console&gt; line 14: The destination attribute 'ctrl_Lip_Up_1_proxy_proxy.t' cannot be found. # ...and it's not doing the operation on the entire list of objects, just the first one and then there's the error. Ok nevermind ! The ´ls´ command also returned the proxies I had created, so my loop was trying to iterate over the proxies themselves as well... Thanks a lot everybody ! Solved ! This is the working code : import maya.cmds as mc attributes = ['.t', '.r', '.s'] controllers = mc.ls('ctrl_Lip*', tr=True) for controller in controllers: mc.duplicate(controller, n=controller+'_proxy') def corresponding_proxy(controller): return controller+'_proxy' for controller in controllers: for attr in attributes: mc.connectAttr(controller+attr, corresponding_proxy(controller)+attr)
tagged with: python-3.x
has title: Python - a type error caused by what?
has comment: http://stackoverflow.com/comment/85611670
has comment: http://stackoverflow.com/comment/85611528
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85611665
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85611784
has comment: http://stackoverflow.com/comment/85611533
tagged with: types
has comment: http://stackoverflow.com/comment/85611445
has comment: http://stackoverflow.com/comment/85611458
tagged with: maya
has comment: http://stackoverflow.com/comment/85611205
has comment: http://stackoverflow.com/comment/85611597

http://stackoverflow.com/comment/85620796
score: 0
comment on: http://stackoverflow.com/a/49308849
type: AnswerComment
has text: @JingLi okay, third time's the charm.
type: Comment

http://stackoverflow.com/q/49323689
tagged with: scrapy
has title: Request not getting expected response
type: Question
has answer: http://stackoverflow.com/a/49323870
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85648850
tagged with: python
score: 0
has body: I'm using scrapy, a python framework for web crawling to extract info from a website. The website I want to extract the information from is: http://apps.who.int/classifications/icd10/browse/2016/en From the index tree in the left of the website, I want to extract both L## codes as well as L##.# codes with their names (where L represents a letter and # a number). So the first two extractions I want are: A00 Cholera A00.0 Cholera dure to Vibrio cholerae 01, biovar cholerae The problem is, when I open the scrapy shell and run: fetch('http://apps.who.int/classifications/icd10/browse/2016/en') view(response) The response don't seem to include the index I want. Why isn't scrapy able to get this index and is there a way to fix it?
answer count: 1

http://stackoverflow.com/comment/85705156
type: QuestionComment
has text: @Niels The problem is I don't even know which file doesn't work. It converted the files in a random order even I set a for loop of converting the files according to their file names.
comment on: http://stackoverflow.com/q/49352303
type: Comment
score: 0

http://stackoverflow.com/q/49437589
type: Question
has comment: http://stackoverflow.com/comment/85878664
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85911531
tagged with: neural-network
has title: Initializing and using a tf.placeholder(tf.string), feeding a value to it and converting it back to a string when necessary
has body: I am having trouble implementing a model in tensorflow. I want to program a model that predicts the polarity of a sentiment. To do this I first have to train the model. This is where an error occurs. I use three variables: sentence (or sentiment), target (the word in the sentence on which the polarity applies) and the polarity itself. The first two variables are strings and the polarity is a vector ([1,0,0] when positive, [0,0,1] when negative). To make these variables I use tf.placeholder(tf.string). When I run the model I get the following error: "You must feed a value for placeholder tensor 'Placeholder_1' with dtype string" I also think I have an issue when I want to do operations on the sentence variable: I need to split the sentence in its words, but since sentence is a placeholder, I first have to convert it back to a string. The input of the model are three vectors: sVec (a vector of all sentences as strings), tVec (a vector of all targets as strings) and pVec (a vector of all polarities as vectors) I have been dealing with this error for quite some time now, so any help is appreciated. Below you find the code. Thanks in advance. polarity = tf.placeholder(tf.float32, shape=[1, c_cardi])#label sentence = tf.placeholder(tf.string) #inputdata target = tf.placeholder(tf.string) def multilayer_perceptron(mi, target, weights, biases): # This method works correctly def modelA(sentence, target): # The error might refer to this: sess2 = tf.Session() sentence = sess2.run(sentence) # I need to get the value of the tensor here sess2.close() words = sentence.split() # Code goes on, no error here return prediction def trainModelA(sVec, tVec, pVec): prediction = modelA(sentence, target) cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=polarity)) optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost_function) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(epochs): # The er…
tagged with: python
has comment: http://stackoverflow.com/comment/85896129
tagged with: deep-learning
downvote count: 0
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/85578301
comment on: http://stackoverflow.com/a/49287568
has text: @user2357112: If you don't break out of loop, it will load them all. That's the point of the infinite loop in the generator, and the point of the answer the OP linked.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85572521
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49284124
type: QuestionComment
has text: @ForceBru Thank you for somewhat of an answer! I assumed storeObj was syntax specific to tkinter and not just simply a variable, in hindsight that was dumb, but as I said I'm very new to programming so. As far as lambda I was hoping for someone to take one specific lambda statement eg ' lambda storeObj=display, s=' %s ' %Equals: storeObj.set(storeObj.get()+s))' and explain in layman terms what's actually happening, I'll swat up on lambda stuff see if I can make any sense of it.

http://stackoverflow.com/comment/85582954
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49289835
has text: That is because they *are* the same. You are using the same figure for both. In order to fix this (1) do not use `pyplot` at all in PyQt GUIs (2) create two figures, one for each figure canvas.
score: 0

http://stackoverflow.com/comment/85626005
score: 0
type: Comment
type: QuestionComment
has text: What kind of `parameters` are you seeking? Neither of your functions takes an argument.
comment on: http://stackoverflow.com/q/49311085

http://stackoverflow.com/q/49418248
possible better answer: http://stackoverflow.com/a/49418271
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85838600
has comment: http://stackoverflow.com/comment/85838400
has comment: http://stackoverflow.com/comment/85838239
upvote count: 6
tagged with: numpy
type: AnsweredQuestion
answer count: 2
score: 5
tagged with: pandas
has title: Plot the x-axis as a date
has comment: http://stackoverflow.com/comment/85838562
has answer: http://stackoverflow.com/a/49418271
accepted answer: http://stackoverflow.com/a/49418672
has comment: http://stackoverflow.com/comment/85838619
linked to: http://stackoverflow.com/q/40815238
linked to: http://stackoverflow.com/q/12608788
has body: I am trying to perform some analysis on data. I got csv file and I convert it into pandas dataframe. the data looks like this. Its has several columns, but I am trying to draw x-axis as date column. . the pandas dataframe looks like this print (df.head(10) cus-id date value_limit 0 10173 2011-06-12 455 1 95062 2011-09-11 455 2 171081 2011-07-05 212 3 122867 2011-08-18 123 4 107186 2011-11-23 334 5 171085 2011-09-02 376 6 169767 2011-07-03 34 7 80170 2011-03-23 34 8 154178 2011-10-02 34 9 3494 2011-01-01 34 I am trying to plot date data because there are multiple values for same date. for this purpose I am trying to plot x-asis ticks as date. since the minimum date in date column is 2011-01-01 and maximum date is 2012-04-20. I tried something like this import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime import matplotlib.dates as mdates df = pd.read_csv('rio_data.csv', delimiter=',') print (df.head(10)) d = [] for dat in df.date: # print (dat) d.append(datetime.strptime(df['date'], '%Y-%m-%d')) days = dates.DayLocator() datemin = datetime(2011, 1, 1) datemax = datetime(2012, 4, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.xaxis.set_major_locator(days) ax.set_xlim(datemin, datemax) ax.set_ylabel('Count values') But I am getting this error. AttributeError: 'DataFrame' object has no attribute 'date' I am trying to draw date as x-axis, it should look like this. Can someone help me to draw the x-axis as date column. I would be grateful.
downvote count: 1
has answer: http://stackoverflow.com/a/49418672
favorite count: 0
type: Question

http://stackoverflow.com/comment/85776686
comment on: http://stackoverflow.com/a/49367908
score: 0
type: Comment
type: AnswerComment
has text: The tutorial only shows how we can create test data using tf.data but doesn't say how to predict on test data using tf.layers. This combination of tf. Data and tf.layers is missing in the tutorial. I have already tried this tutorial. If you have a answer pls post the code and I will accept it as answer

http://stackoverflow.com/comment/85919740
comment on: http://stackoverflow.com/q/49436765
type: Comment
has text: @Jello I think that result like https://www.youtube.com/watch?v=9QQCGLKuUxc would be nice. However I am open to implement a system that would work for another type of obstacles. What do you mean by 'large ones' and man made? I know that complex and unflawed system of obstacle avoidance is impossible to implement only with one regular camera. One thing I haven't written - all calculations will be done on laptop - not unit inside drone (project is based on Robot Operating System)
type: QuestionComment
score: 0

http://stackoverflow.com/a/49280863
has comment: http://stackoverflow.com/comment/85596596
has comment: http://stackoverflow.com/comment/85595721
score: 0
has comment: http://stackoverflow.com/comment/85593692
has comment: http://stackoverflow.com/comment/85596236
answers question: http://stackoverflow.com/q/49280143
has comment: http://stackoverflow.com/comment/85594293
has comment: http://stackoverflow.com/comment/85603939
type: Answer
has body: Do this, keep your original response as it is, and replace its body with the new one you want. response.replace(body = data['html'].encode("utf8").decode('string_escape'))

http://stackoverflow.com/comment/85708369
type: Comment
type: QuestionComment
has text: How are you calling and what are you passing into methods? Your methods `return` nothing. Also, why not use an `INSERT INTO ... SELECT ... ` with one query?
score: 0
comment on: http://stackoverflow.com/q/49352527

http://stackoverflow.com/q/49341240
has comment: http://stackoverflow.com/comment/85682633
has comment: http://stackoverflow.com/comment/85682688
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85682603
accepted answer: http://stackoverflow.com/a/49341273
tagged with: getter-setter
has answer: http://stackoverflow.com/a/49341273
has title: How to access Magic Methods inside a Class python
has comment: http://stackoverflow.com/comment/85682722
score: 1
has body: I am having hard time understanding this. Let's say we have a snippet of code as such class Animal: def __init__(self, name, food): self.name = name self.__food = food def getFood(self): return self.__food Then we initialize it &gt;&gt;&gt; animal = {} &gt;&gt;&gt; animal["dog"] = Animal("rusty", "delicious thing you never know") Now, while accessing the attributes, It seems to not let me access __food &gt;&gt;&gt; animal["dog"].name 'rusty' &gt;&gt;&gt; animal["dog"].__food Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: Animal instance has no attribute '__food' Why does that fail. As we can clearly see I am using self.__food = food where __ is magic method. So how do I print the __food Magic attribute ?
tagged with: python
tagged with: class
has comment: http://stackoverflow.com/comment/85682588
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85682750
has comment: http://stackoverflow.com/comment/85682721
downvote count: 0
has comment: http://stackoverflow.com/comment/85682540
answer count: 1
upvote count: 1

http://stackoverflow.com/q/49425956
tagged with: function
downvote count: 0
upvote count: 1
has body: This is a function in python3 that prints 1 through 10. There are a few things I don't understand about this, since I'm a programming noob. This function will subtract 1 from a given number as long as that number is above 1. So if number = 10 it will subtract 1 from 10 to give 9 and then 1 from 9 to give 8 and so on... until it reaches 1, which will be printed to the screen. I don't understand is why the function subsequently prints 2, 3, 4, 5, 6, 7, 8, 9 and 10. Since these numbers are above one, shouldn't they enter the if-statement and then not be printed? According to my understanding of the code, only numbers that are equal to or below 1 will be printed. In other words: "Why is the output of this function, not "1" alone?" def print_numbers(number): if number &gt; 1: print_numbers(number-1) print(number) print_numbers(10) You can try out the code in python to see that the output is 1 through 10?
accepted answer: http://stackoverflow.com/a/57719635
has answer: http://stackoverflow.com/a/49426462
possible better answer: http://stackoverflow.com/a/49426343
has title: Can someone explain the output of this recursive function in python?
favorite count: 0
has answer: http://stackoverflow.com/a/57719635
tagged with: python-3.x
type: AnsweredQuestion
tagged with: recursion
has answer: http://stackoverflow.com/a/49426348
score: 1
tagged with: python
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/49426343

http://stackoverflow.com/q/49374819
upvote count: 1
duplicate of: http://stackoverflow.com/q/20002503
downvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49374870
has title: Why won't my if, else statment work in python in the while loop
tagged with: while-loop
type: Question
tagged with: if-statement
duplicate of: http://stackoverflow.com/q/319426
tagged with: python
type: UnansweredQuestion
has body: I have this code: print("Christian Dooley") print("Lab #5") import sys def calculation(): counter = 0 NumberOfElements = 1 numbers = [] sum = (0) for i in range(NumberOfElements): value=eval(input("Enter a new number:")) numbers.append(value) while counter <= value: print(counter) sum+=counter counter+=1 if counter % 2 != 0: print("This number is even") else: print("This number is odd") print(sum) while True: calculation() repeat = input("Do you want to 'count' another number \n Awnser yes or no: ") if repeat == "Yes" or "yes": calculation() elif repeat == str("no") or str("No"): break When the code runs, it should ask the user to input a number; print every number leading up to it; tell if the number is even or odd; print the sum; and finally have the user enter if he wants to repeat the process or not. This part of the code is giving me trouble: if repeat == "Yes" or "yes": calculation() elif repeat == str("no") or str("No"): break The if statement will keep running over and over, no matter what I enter for the repeat variable. Why does this happen?
has comment: http://stackoverflow.com/comment/85750871
linked to: http://stackoverflow.com/q/148042
score: 0
has comment: http://stackoverflow.com/comment/85750826

http://stackoverflow.com/comment/85869498
score: 2
type: Comment
type: QuestionComment
has text: Oops, you are mistaking `NaN` with `"NaN"`, one is a float and the other, a string. _Very_ different.
comment on: http://stackoverflow.com/q/49433777

http://stackoverflow.com/comment/85644150
type: Comment
comment on: http://stackoverflow.com/a/49320996
score: 0
type: AnswerComment
has text: The second solution works great! Thank you for your help!

http://stackoverflow.com/a/49344765
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49344582
has comment: http://stackoverflow.com/comment/85689739
has comment: http://stackoverflow.com/comment/85690616
answers question: http://stackoverflow.com/q/49344582
has comment: http://stackoverflow.com/comment/85689980
has comment: http://stackoverflow.com/comment/85689951
has body: You're trying to synchronize something that's asynchronous... This is massively more complicated than it should be. Your dbmon is only storing a boolean flag... why not just asynchronously modify the "database" instead? For example, if the "database" was a thread-safe buffer, you could just append to that buffer or modify that buffer without synchronizing each thread individually, pull the information written to that buffer and write it to the client socket they belong to in another event loop (this is pretty much what asyncore does) That said, I have some (probably nonworking, but I hope you get the idea) reference modified code for you to go off of if you want to continue pursing this avenue. Basically, dbmon will keep a mapping of thread ids to [creation time, modified flag] Our predicate returns true iff all threads created before a certain threshold have ALL set the modified flag. We set the modified flag when we send the response in the data = client.recv(size) portion of your code. And then we wait on that condition in the server send. We keep notifying all waiting threads on each client receive so that when the condition is finally met, our waiting server threads will all unblock and send the subsequent response. import socket, threading, time, select, os import collections class dbMonitor: def __init__(self): self.isDBAltered = {} self.lock = threading.Lock() def newThread(self, tid): self.lock.acquire() # time of creation, boolean whether that thread has sent response self.isDBAltered[tid] = [time.time(), False] self.lock.release() def threadDone(self, tid): self.lock.acquire() self.isDBAltered.pop(tid, None) self.lock.release() def altered(self, tid): self.lock.acquire() self.isDBAltered[tid][1] = True self.lock.release() def reset(self, tid): self.lock.acquire() self.isDBAltered(tid)[1] = False self.lock.release() def __str__(self): return str(self.isDBAltered) class ThreadedServer(object): def __init__(self, port,dbMon): self.port = port self.sock = soc…
type: Answer
has comment: http://stackoverflow.com/comment/85689776
has comment: http://stackoverflow.com/comment/85690033
has comment: http://stackoverflow.com/comment/85690017
has comment: http://stackoverflow.com/comment/85705435
has comment: http://stackoverflow.com/comment/85689885
score: 0

http://stackoverflow.com/comment/85672814
score: 0
comment on: http://stackoverflow.com/q/49335507
type: Comment
has text: So is the problem the memory consumption, rather than speed? The allocation will take a tiny fraction of the time that the elementwise "==" takes.
type: QuestionComment

http://stackoverflow.com/comment/85641609
has text: @MarcelZoll It is not very complex as you can refer my solution to get the idea to solve in simple and easy steps.
type: QuestionComment
comment on: http://stackoverflow.com/q/49296114
type: Comment
score: 0

http://stackoverflow.com/comment/85686688
comment on: http://stackoverflow.com/q/49342838
score: 0
has text: @Johan: https://onlinegdb.com/rkH_A7iFM
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85744770
has text: I try from admin page in Django 2.0.2
comment on: http://stackoverflow.com/q/49371790
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49300902
tagged with: python
has comment: http://stackoverflow.com/comment/85603952
has answer: http://stackoverflow.com/a/49301025
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49301025
has body: For my university project, I've described several models for e-commerce of goods: Item, Book(Item), Stationery(Item), and ItemImage (related by ForeignKey for all Item-like models). I need to filter the set of item images in the following way: def home(request): goods_images = ItemImage.objects.filter(is_active=True, is_main=True) goods_images_books = ItemImage.objects.filter(is_active=True, is_main=True) goods_images_stationeries = ItemImage.objects.filter(is_active=True, is_main=True) return render(request, 'landing/home.html', locals()) The question is what the additional parameter I should add to filter()? Or is there another way of solving this problem?
tagged with: filter
downvote count: 0
has comment: http://stackoverflow.com/comment/85603768
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85603547
favorite count: 0
has title: Django: How to filter my models (by child)?
type: Question
answer count: 1
tagged with: django

http://stackoverflow.com/q/49370093
has title: Find Percentage of Task Completed
tagged with: percentage
tagged with: celery
type: Question
tagged with: python-3.x
has body: Is there any way to find the percentage of the task completed provided the ID in celery? Something like: &gt;&gt;&gt; a4654.percentage() 93%
tagged with: python
has answer: http://stackoverflow.com/a/49370287
accepted answer: http://stackoverflow.com/a/49370287
type: AnsweredQuestion
score: 0
answer count: 1

keyboard-events
tags question: http://stackoverflow.com/q/49342573
tag name: keyboard-events
type: Tag
tags question: http://stackoverflow.com/q/49399940

http://stackoverflow.com/a/49288480
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85580399
answers question: http://stackoverflow.com/q/49287073
downvote count: 0
score: 1
type: Answer
has body: This related question may be useful to you: tkinter gui layout using frames and grid1 Applying this to your code you might get something like this: import glob from Tkinter import * root = Tk() root.title('Model Definition') root.geometry('{}x{}'.format(600, 600)) # create all of the main containers center = Frame(root, bg='gray2', width=590, height=590, padx=3, pady=3) # layout all of the main containers root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=1) center.grid(row=1, sticky="nsew") # create the center widgets center.grid_rowconfigure(0, weight=1) center.grid_columnconfigure(1, weight=1) ctr_left = Frame(center, bg='blue', width=295, height=590, padx=50, pady=50) ctr_right = Frame(center, bg='green', width=295, height=590, padx=70, pady=50) ctr_left.grid(row=0, column=0, sticky="ns") ctr_right.grid(row=0, column=2, sticky="ns") # create right sub widgets ctr_right.grid_rowconfigure(1, weight=1) ctr_right.grid_columnconfigure(0, weight=1) right_top = Frame(ctr_right, bg='yellow', width=295, height=194) right_center = Frame(ctr_right, bg='red', width=295, height=194) right_bottom = Frame(ctr_right, bg='purple', width=295, height=194) right_top.grid(row=0, column=0, sticky="ew") right_center.grid(row=1, column=0, sticky="ew") right_bottom.grid(row=2, column=0, sticky="ew") # # make the Listbox and buttons # # Creates Listbox of existing subjects, from .txt files in directory of program subjects = Listbox(ctr_left, width=32, height=30) for this_file in glob.glob("*.txt"): subjects.insert(0, this_file.split('.')[0]) subjects.grid(column=0, row=0, sticky="e") # Creates a button for selecting the subject in the Listbox select_subject = Button(right_top, text='Select subject', command=lambda: subject_menu(subjects, root), width=20, height=3) select_subject.grid(column=0, row=0, sticky="e") # Creates a "make new subject" button make_subject = Button(right_center, text='Make new subject', command=lambda: new_subject(root), width=20, height=3) mak…
accepted answer of: http://stackoverflow.com/q/49287073

http://stackoverflow.com/a/49397308
type: Answer
answers question: http://stackoverflow.com/q/49396973
has body: Let's clarify something. The fact you have a list is not important, and these are the same &gt;&gt;&gt; '"quote"' == "\"quote\"" True &gt;&gt;&gt; '"quote"' == '\"quote\"' True Now, let's use a raw string. &gt;&gt;&gt; '\"quote\"' == r'\"quote\"' False As expected, so we print the raw string, also expected. &gt;&gt;&gt; print(r'\"quote\"') \"quote\" But how is that raw string represented? &gt;&gt;&gt; repr(r'\"quote\"') =&gt; '\'\\\\"quote\\\\"\'' Weird, right? And how about we print the representation? &gt;&gt;&gt; print(repr(r'\"quote\"')) '\\"quote\\"' That's better, but can you remove the \\" with just \"? No - you cannot. \" is an escape character, and the backslash itself needs escaped, and that is what you are seeing in the output. To answer the question, list2 is stored correctly, you are just looking at the output incorrectly. See &gt;&gt;&gt; list2 ['\\"quote\\"'] &gt;&gt;&gt; print(list2[0]) \"quote\" &gt;&gt;&gt; list2[0] '\\"quote\\"'
score: 0

http://stackoverflow.com/q/49364202
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49364737
tagged with: python
type: Question
tagged with: xpath
has body: What is a good way to select multiple nodes from with in a node in a html code using xpath? I have this code (actually this repeated 23 times); Google text Status: Under development I am trying to get both Title and Date and have two different XPATH querys like this; //a[@class="Title"]/@href //p[@class="Date"] But when I do this I get two returns with 23 and 22 values each. This is because at one point in the HTML code Date is not present. Therefore I would like to stay inside the li and search for Title and Date within that li so I can check if there are any values. I changed my XPATH to this; //li In my return Element I can see that there are two sub elements, a and div but I cannot seem to figure out how I am supposed to handle what is inside the return Element?
has comment: http://stackoverflow.com/comment/85729182
answer count: 1
type: AnsweredQuestion
has title: Python: XPATH searching within a node
score: 0
accepted answer: http://stackoverflow.com/a/49364737

http://stackoverflow.com/a/49402034
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49401941
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49401941
has body: You can use: df = df.set_index('Uid').pop('PreviousPostCodes').str.split(',\s*', expand=True) df.columns = [df.columns % 2 + 1, df.columns // 2] df = df.stack().add_prefix('P').reset_index(level=1, drop=True).reset_index() print (df) Uid P1 P2 0 1 NE11 7HS NE5 8MN 1 1 NE1 7UJ NE14 8YU 2 2 LS6 8PJ None 3 3 M6 7JH M14 1HF 4 4 B17 8KA LE5 7UZ 5 4 LE9 9GF None Explanation: Create index from column Uid by set_index and split to DataFrame Create MultiIndex in columns by floor and modulo division Reshape by stack Change columns names by add_suffix Last reset_index for remove first level of MultiIndex and column from index

http://stackoverflow.com/comment/85861974
score: 1
has text: Nice! I knew crosstab was the way to go but couldn't figure it out.
type: AnswerComment
comment on: http://stackoverflow.com/a/49430091
type: Comment

http://stackoverflow.com/q/49366880
has comment: http://stackoverflow.com/comment/85734418
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49366973
accepted answer: http://stackoverflow.com/a/49366973
tagged with: python-3.x
downvote count: 0
has title: Bundling python dependencies in the project folder itself so as it can be easily shared and start application without downloading any dependencies
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/85739228
type: AnsweredQuestion
upvote count: 1
score: 1
has body: Whenever we download any python dependencies i.e django,MySQL by using 'pip' it get install in the root folder that would be c drive on windows( where we have install python). How can I install this dependencies in my project folder itself, so when I start my application it will read the dependencies from project folder rather from c drive. My purpose is whenever i give my application to user or third person he should directly start application instead of downloading all dependencies.
tagged with: python

http://stackoverflow.com/comment/85832507
type: Comment
type: QuestionComment
score: 0
has text: That depends on the IDE or tool you are using, there is no general response.
comment on: http://stackoverflow.com/q/49413607

http://stackoverflow.com/a/49297915
has comment: http://stackoverflow.com/comment/85597649
answers question: http://stackoverflow.com/q/49297830
has body: python3 -m pip install pandas This is advice from Raymond Hettinger.
score: 1
has comment: http://stackoverflow.com/comment/85597880
upvote count: 1
has comment: http://stackoverflow.com/comment/85598382
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85685579
has text: ok, instead of extracting the text content for each tr tag (that concatenates all text nodes), loop over the td tags to obtain each information separately for each tr tag.
score: 0
comment on: http://stackoverflow.com/q/49333206
type: Comment
type: QuestionComment

backpropagation
tags question: http://stackoverflow.com/q/49403023
type: Tag
tag name: backpropagation

http://stackoverflow.com/comment/85592964
type: QuestionComment
has text: Or maybe it's really another person, doing the same homework?
score: 0
comment on: http://stackoverflow.com/q/49293348
type: Comment

http://stackoverflow.com/a/49297963
answers question: http://stackoverflow.com/q/49297106
has comment: http://stackoverflow.com/comment/85626082
has body: Try this: with open("bintest.dat", "rb") as f: # this is exactly the same as 'n = 4' in R code n = 4 count = 0 byte = f.read(4) while count &lt; n and byte != b"": i = int.from_bytes(byte, byteorder='little', signed=False) print(i) count += 1 # this is analogue of 'size=8' in R code byte = f.read(4) byte = f.read(4) Or you can do it as a function. Some parameters are not used at the moment, work for later :) def readBin(file, fun, n, size, endian, signed): with open(file, "rb") as f: r = [] count = 0 byte = f.read(4) while count &lt; n and byte != b"": i = int.from_bytes(byte, byteorder=endian, signed=signed) r.append(i) count += 1 byte = f.read(4) byte = f.read(4) return r And then here will be the usage: i = readBin('bintest.dat', int, n = 4, size = 8, endian = 'little', signed = False) print(i) [1, 3, 5, 7] Some links for you to examine: Working with binary data Reading binary file
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85628188
score: 1
has comment: http://stackoverflow.com/comment/91809246
type: Answer

http://stackoverflow.com/a/49360357
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49359952
upvote count: 1
has comment: http://stackoverflow.com/comment/85728282
has body: Consider using numpy structured arrays for mixed types. You will have no issues if you explicitly set data types. This is often necessary, and certainly advisable, with numpy. import numpy as np country = ['India','USA','UK'] gdp = [22,33,4] a = np.array(list(zip(country, gdp)), dtype=[('Country', '|S11'), ('Number', '&lt;i8')]) res_asc = np.sort(a, order='Number') # array([(b'UK', 4), (b'India', 22), (b'USA', 33)], # dtype=[('Country', 'S11'), ('Number', '&lt;i8')]) res_desc = np.sort(a, order='Number')[::-1] # array([(b'USA', 33), (b'India', 22), (b'UK', 4)], # dtype=[('Country', 'S11'), ('Number', '&lt;i8')])
score: 0

http://stackoverflow.com/comment/85743449
has text: @GarrettGutierrez it does print an output.
comment on: http://stackoverflow.com/q/49371170
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49395701
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49395884
score: 0
has title: Replacing a string with another using regex in Python
answer count: 3
has answer: http://stackoverflow.com/a/49395961
has body: I am trying to replace a selected text with a single word from that selected text using regex. I tried re.sub() but it seems that it takes the second argument "The word that I want to replace it with the text" as a string, not as regex. Here is my string: I go to Bridgebrook i go out &lt;ERR targ=sometimes&gt; some times &lt;/ERR&gt; on Tuesday night i go to Youth &lt;ERR targ=club&gt; clob &lt;/ERR&gt; . And here is my code: # The regex of the form &lt;ERR targ=...&gt; .. &lt;/ERR&gt; select_text_regex = r"&lt;ERR[^&lt;]+&lt;\/ERR&gt;" # The regex of the correct word that will replace the selected text of teh form &lt;ERR targ=...&gt; .. &lt;/ERR&gt; correct_word_regex = r"targ=([^&gt;]+)&gt;" line = re.sub(select_text_regex, correct_word_regex, line.rstrip()) I get: I go to Bridgebrook i go out targ=([^&gt;]+)&gt; on Tuesday night i go to Youth targ=([^&gt;]+)&gt; . My goal is: I go to Bridgebrook i go out sometimes on Tuesday night i go to Youth club . Does Python support replacing two strings using Regex?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49395874
possible better answer: http://stackoverflow.com/a/49395874
accepted answer: http://stackoverflow.com/a/49395961
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/8934477

http://stackoverflow.com/comment/85638290
comment on: http://stackoverflow.com/q/49318551
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by "it doesn't work"? Could you provide examples of correct and actual output?

http://stackoverflow.com/q/49438948
type: Question
has comment: http://stackoverflow.com/comment/85942511
has body: I was developing a basic web crawler and wanted to use 'import requests' in my code. This throws an error. I am using pycharm and it is not able to work there. I searched around on Google and saw many people have the same issues. I tried following their solutions and still couldn't figure it out. I tried downloading pip, pip3, pip3.4 using the Windows 10 cmd but I couldn't get the problem to go. Even after installing these packages, I am getting the same error. Error is Traceback (most recent call last): File "C:/Users/Paras/PycharmProjects/Monty/First.py", line 1, in &lt;module&gt; import requests ImportError: No module named 'requests' Process finished with exit code 1
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85879918
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/85879971
score: 0
has comment: http://stackoverflow.com/comment/85879842
has title: When using Python 3.4 I get error no module "requests"
has comment: http://stackoverflow.com/comment/85899477
tagged with: python-requests
tagged with: import

http://stackoverflow.com/comment/85612712
type: QuestionComment
has text: Any reason `np.column_stack(all_vectors)` doesn't work?
comment on: http://stackoverflow.com/q/49305174
score: 2
type: Comment

http://stackoverflow.com/comment/85655106
score: 0
type: AnswerComment
has text: I'm not entirely sure, but I think this question is a dupe. I can't seem to fine it googling though, and I can't remember the name.
type: Comment
comment on: http://stackoverflow.com/a/49326695

opencsv
tag name: opencsv
tags question: http://stackoverflow.com/q/49405831
type: Tag

http://stackoverflow.com/a/49334898
has body: IIUC: In [89]: from scipy.signal import argrelextrema In [90]: a = np.array([1,2,3,4,5,6,8,9,10,9,7,6,5.50,5,6,7,8,10,12,15,14 ,13.50, 12]) In [91]: idx = np.sort(np.concatenate((argrelextrema(a, np.greater)[0], argrelextrema(a, np.less)[0]))) In [92]: np.split(a, idx) Out[92]: [array([1., 2., 3., 4., 5., 6., 8., 9.]), array([10. , 9. , 7. , 6. , 5.5]), array([ 5., 6., 7., 8., 10., 12.]), array([15. , 14. , 13.5, 12. ])] or In [93]: np.split(a, idx+1) Out[93]: [array([ 1., 2., 3., 4., 5., 6., 8., 9., 10.]), array([9. , 7. , 6. , 5.5, 5. ]), array([ 6., 7., 8., 10., 12., 15.]), array([14. , 13.5, 12. ])] Points of interest: In [97]: np.concatenate((a[[0]], a[idx], a[[-1]])) Out[97]: array([ 1., 10., 5., 15., 12.]) UPDATE: In [129]: df = pd.DataFrame({'Value':Values, 'Date':pd.date_range('2018-01-01', periods=len(Values))}) In [130]: df Out[130]: Date Value 0 2018-01-01 1.0 1 2018-01-02 2.0 2 2018-01-03 3.0 3 2018-01-04 4.0 4 2018-01-05 5.0 .. ... ... 18 2018-01-19 12.0 19 2018-01-20 15.0 20 2018-01-21 14.0 21 2018-01-22 13.5 22 2018-01-23 12.0 [23 rows x 2 columns] In [131]: idx = np.sort(np.concatenate((argrelextrema(df['Value'].values, np.greater)[0], argrelextrema(df['Value'].values, np.less)[0]))) In [132]: idx Out[132]: array([ 8, 13, 19], dtype=int64) In [133]: df.iloc[idx] Out[133]: Date Value 8 2018-01-09 10.0 13 2018-01-14 5.0 19 2018-01-20 15.0 In [134]: poi = np.concatenate(([0], idx, [len(df)-1])) In [135]: df.iloc[poi] Out[135]: Date Value 0 2018-01-01 1.0 8 2018-01-09 10.0 13 2018-01-14 5.0 19 2018-01-20 15.0 22 2018-01-23 12.0
has comment: http://stackoverflow.com/comment/85671492
answers question: http://stackoverflow.com/q/49334810
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85682084
has comment: http://stackoverflow.com/comment/85671590
has comment: http://stackoverflow.com/comment/85742731
score: 2
has comment: http://stackoverflow.com/comment/85742736
has comment: http://stackoverflow.com/comment/85671626
has comment: http://stackoverflow.com/comment/85694825
has comment: http://stackoverflow.com/comment/85694753

http://stackoverflow.com/q/49282595
tagged with: os.walk
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/49334280
tagged with: python-imaging-library
has title: cannot open resource: OS Error
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: for-loop
upvote count: 2
has answer: http://stackoverflow.com/a/49334280
has body: OSError Traceback (most recent call last) in () 21 draw = PIL.ImageDraw.Draw(img) 22 print(os.path.join(path, filename)) ---> 23 draw.font = PIL.ImageFont.truetype((os.path.join(path, filename))+ '.ttf', 44) 24 t2 = get_display(t1) 25 w, h = draw.textsize(t2) () OSError: cannot open resource I have this error in following does it PIL or i did some mistake. it only shows first file path and then this error appears. unicode_text = u"\u0627" list_of_letters = list (unicode_text) folder = 1 n=1 i=0 for i in range(0,158): path = r"E:\Dummy\fonts" dirs = os.listdir( path ) for files in dirs: char = u''.join(list_of_letters) t1 = arabic_reshaper.reshape(char) W,H= (100, 100) img= PIL.Image.new('RGBA', (W, H), (255, 255, 255),) draw = PIL.ImageDraw.Draw(img) print(os.path.join(path, filename)) draw.font = PIL.ImageFont.truetype((os.path.join(path, filename)), 44) t2 = get_display(t1) w, h = draw.textsize(t2) draw.text(((W-w)/2,(H-h)/2),t2, fill="#000000") path = 'E:\Dummy\sam\\'+ str(folder) if not os.path.exists(path): os.makedirs(path) img.save(path + '\\' + char+'.png', "PNG") folder+=1 #i+=1
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85666204
has text: For anyone interested in the simpler case of finding the next composite number with only the factors 2, 3, and 5, there is [`scipy.fftpack.next_fast_len`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.next_fast_len.html).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49325820
score: 2

http://stackoverflow.com/a/49287473
has comment: http://stackoverflow.com/comment/85578652
has comment: http://stackoverflow.com/comment/85579228
has body: self.otherImages doesn't return anything! When a function does not return an explicit value in python, it returns None. You cannot iterate over None.
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85578587
has comment: http://stackoverflow.com/comment/85578973
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49287434

http://stackoverflow.com/a/49336118
downvote count: 0
upvote count: 1
has body: animal could be called table, and should indicate that it's not just a single animal. It also shouldn't be called animals, because it's not just a list of animals. Thanks to unpacking, you can split your sub-lists directly into an integer and a list of animals: &gt;&gt;&gt; table = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']] &gt;&gt;&gt; [[i, ', '.join(animals)] for (i, *animals) in table] [[1, 'Crocodile, Lion'], [2, 'Eagle, Sparrow'], [3, 'Hippo, Platypus, Deer']]
answers question: http://stackoverflow.com/q/49336064
score: 1
type: Answer

http://stackoverflow.com/comment/85627688
has text: @Floydian I'm getting an error : **def prod_data(row): return row.groupby(pd.Grouper(freq='12M')).tail(12).prod() -1 df[‘prod'] = df.apply(prod_data, axis=1)**
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49300590
type: AnswerComment

http://stackoverflow.com/q/49357270
has title: Python-pptx: issue with insert_picture() function - 'sha1' AttributeError
tagged with: python
has comment: http://stackoverflow.com/comment/88723535
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50953115
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I am trying to write a basic script to update a PowerPoint (2016) presentation, template.pptx, which contains predefined place holders for images. I am running into issues with the insert_picture() function. As an example, the 4th slide of template.pptx contains a Picture Placeholder: from pptx import Presentation prs = Presentation('template.pptx') slide4 = prs.slides[3] for shape in slide4.placeholders: print('%d %s' % (shape.placeholder_format.idx, shape.name)) which gives the following output &gt;&gt;&gt; 0 Title 3 10 Picture Placeholder 7 I proceed with placeholder = slide4.placeholders[10] # idx key, not position picture = placeholder.insert_picture('test.jpg') Which throws the following error(s): File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 323, in insert_picture pic = self._new_placeholder_pic(image_file) File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 334, in _new_placeholder_pic rId, desc, image_size = self._get_or_add_image(image_file) File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 345, in _get_or_add_image image_part, rId = self.part.get_or_add_image_part(image_file) File "C:\Python273\lib\site-packages\pptx\parts\slide.py", line 42, in get_or_add_image_part image_part = self._package.get_or_add_image_part(image_file) File "C:\Python273\lib\site-packages\pptx\package.py", line 50, in get_or_add_image_part return self._image_parts.get_or_add_image_part(image_file) File "C:\Python273\lib\site-packages\pptx\package.py", line 159, in get_or_add_image_part image_part = self._find_by_sha1(image.sha1) File "C:\Python273\lib\site-packages\pptx\package.py", line 171, in _find_by_sha1 if image_part.sha1 == sha1: AttributeError: 'Part' object has no attribute 'sha1' I have seen this 'sha1' error mentioned in these forums but don't fully understand it (I am a bit of a novice). Interestingly (frustratingly), I don't run into this issue when creating a PowerPoint from scratch (as per the example …
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49383508
has comment: http://stackoverflow.com/comment/85775254
tagged with: macos
type: Question
has comment: http://stackoverflow.com/comment/85767671
has title: scons can't work on Mac throw python SyntaxError
has answer: http://stackoverflow.com/a/49449661
has comment: http://stackoverflow.com/comment/85825298
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44096321
linked to: http://stackoverflow.com/q/32135869
has comment: http://stackoverflow.com/comment/85772453
has comment: http://stackoverflow.com/comment/85853581
tagged with: python
has comment: http://stackoverflow.com/comment/85825734
has comment: http://stackoverflow.com/comment/85778288
linked to: http://stackoverflow.com/q/48185262
score: 0
has comment: http://stackoverflow.com/comment/85770578
has comment: http://stackoverflow.com/comment/85825229
tagged with: scons
has body: My Mac have python2.7 by default, and the scons3 have been installed successfully.However when compile the code, it still throws a SyntaxError: invalid syntax. i just go into the project folder and type scons -q then it shows scons: Reading SConscript files ... File "/Users/andromedae/physbam/PhysBAM_Tools/SConstruct", line 428 print "%s has %d symbols exported"%(library_name,len(defs.keys())) ^ SyntaxError: invalid syntax like it using python3? i have python3 installed by anaconda. but all i have done is: python setup.py install cd \project scons -q
answer count: 1
has comment: http://stackoverflow.com/comment/85901201

http://stackoverflow.com/q/49294655
has answer: http://stackoverflow.com/a/49632271
has comment: http://stackoverflow.com/comment/85592081
has comment: http://stackoverflow.com/comment/85591760
tagged with: python
has comment: http://stackoverflow.com/comment/85592166
has body: I have a CSV file with 20501 rows and 26 columns. I want to select 5 column and 9 columns data. Here is what i have import csv filename = 'feed_data.csv' f = open(filename) readCSV = csv.reader(f, delimiter=',') names = [] confidence_score = [] for row in readCSV: names.append(row[8]) confidence_score.append(row[4]) here is the error Traceback (most recent call last): File "C:/Users/raady/PycharmProjects/feeder_Classification/test.py", line 10, in &lt;module&gt; for row in readCSV: File "C:\Users\raady\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1009: character maps to &lt;undefined&gt; how to rectify the error? I don't want to use pandas. Is there any way that both columns can be copied only to one variable, instead of names and confidence_score seperately? Edit: I have installed python 3.6 and pycharm environment. I have installed all the packages from the pycharm environment. Edit 2: I have tried in the suggested link by modifying f=open(filename,encoding='utf8'), but I still have the error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 934: invalid start byte. The CSV file has been encoded in utf8. Edit 3: I slightly modified code like this import csv filename = 'feed_data.csv' # filename = 'test.csv' with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') data2 = [] for row in readCSV: data = [] data.append(row[14]) # appending names data.append(row[5]) # appending confidence data2.append(data) print(data2) I am adding the two files test.py and feed_data( directly downloaded from kaggle). When I try with test.py it is working fine and I am able to select required column data but not with feed_data.py and it gives the error mentioned above.
linked to: http://stackoverflow.com/q/9233027
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49632271
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85591638
answer count: 1
has comment: http://stackoverflow.com/comment/85591842
tagged with: multiple-columns
type: Question
has title: selecting columns from csv file error

http://stackoverflow.com/q/49368994
type: Question
has body: I took a programming class in python so I know the basics of the language. A project I'm currently attempting involves submiting a form repeatedly untill the request is successful. In order to achieve a faster success using the program, I thought cutting the browser out of the program by directly sending and recieving data from the server would be faster. Also the website I'm creating the program for has a tendency to crash but I'm pretty sure i could still receive and send response to the server. Currently, im just researching different resources I could use to complete the task. I understand mechanize is easy to fill forms and submit them, but it requires a browser. So my question is what would be the best resource to use within python to communicate directly with the server without a browser. I apologize if any of my knowledge is flawed. I did take the class but I'm still relatively new to the language.
tagged with: mechanize
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49369234
has answer: http://stackoverflow.com/a/49369049
has answer: http://stackoverflow.com/a/49369122
has title: Using python, Is it possible to directly send form data to a website server and receive response without using a browser?
has comment: http://stackoverflow.com/comment/85739555
answer count: 3
score: 0
tagged with: python-requests

http://stackoverflow.com/a/49401566
answers question: http://stackoverflow.com/q/49393300
score: 0
has body: I fixed the issue by downgrading to pip version 9.0.1. It appears anaconda doesn't like pip version 9.0.2 I ran: pip install pip==9.0.1
has comment: http://stackoverflow.com/comment/85820666
type: Answer

http://stackoverflow.com/a/49439315
answers question: http://stackoverflow.com/q/49439008
type: Answer
has body: One solution is to iterate over the dataframe, populating each XML element individually: import pandas as pd from lxml import etree as et df = pd.DataFrame({'id_profile': [439, 444654, 56454, 12222], 'ServiceDate': ['2017-12-05', '2017-01-25', '2017-12-05', '2017-01-25'], 'PrimaryServiceCategory': [25, 25, 33, 25]}) root = et.Element('root') for row in df.iterrows(): report = et.SubElement(root, 'ClientReport') idnum = et.SubElement(report, 'ID') prime_serv = et.SubElement(report, 'ServiceCategory') serv_date = et.SubElement(report, 'ServiceDate') idnum.text = str(row[1]['id_profile']) prime_serv.text = str(row[1]['PrimaryServiceCategory']) serv_date.text = str(row[1]['ServiceDate']) print(et.tostring(root, pretty_print=True).decode('utf-8'))
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49439008

http://stackoverflow.com/a/49309796
answers question: http://stackoverflow.com/q/49309527
upvote count: 1
score: 1
has body: not sure there's an elegant way. OrderedDict has a move_to_end method to move keys at start or end, but not at a random position. I'd try to be as efficient as possible, and minimze loops get a list of the keys find the index of the key you want to merge with the following one remove the next key of the dictionary create a list with d items alter this list with the new value at the stored index rebuild an OrderedDict from it like this (I removed some keys because it shortens the example): from collections import OrderedDict d = OrderedDict([ ("Sample Code", "Vendor Sample ID"), ("Donor ID", "Vendor Subject ID"), ("Format", "Material Format"), ("Sample Type", "Sample Type"), ("Age", "Age"), ("Gender", "Gender"), ]) lk = list(d.keys()) index = lk.index("Sample Type") v = d.pop(lk[index+1]) t = list(d.items()) t[index] = ("new key",t[index][1]+" "+v) d = OrderedDict(t) print(d) result: OrderedDict([('Sample Code', 'Vendor Sample ID'), ('Donor ID', 'Vendor Subject ID'), ('Format', 'Material Format'), ('new key', 'Sample Type Age'), ('Gender', 'Gender')])
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85677212
type: Comment
type: QuestionComment
has text: i thought their may be people who know c language that also understand and familier with python
comment on: http://stackoverflow.com/q/49295110
score: 0

http://stackoverflow.com/q/49308803
has body: some packages like numpy are installed as default in Google Colab. is there any way to not installing new packages and make it default just like numpy?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85634830
answer count: 1
downvote count: 0
has title: is there any way to not installing packages on Google Colab every time?
tagged with: pip
tagged with: python
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/49313978
accepted answer: http://stackoverflow.com/a/49313978
type: AnsweredQuestion
upvote count: 1
score: 1

http://stackoverflow.com/comment/86058311
comment on: http://stackoverflow.com/a/49499867
type: AnswerComment
score: 0
type: Comment
has text: @CristiFati After I upgraded `pip` to 9.0.3, I can do `pip install pywin32` too. I was using an older version which couldn't.

http://stackoverflow.com/q/49410333
has answer: http://stackoverflow.com/a/49411212
tagged with: python
has comment: http://stackoverflow.com/comment/85823412
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49415011
answer count: 2
has title: transform the shape from (X, 1) to (X)
has answer: http://stackoverflow.com/a/49415011
accepted answer: http://stackoverflow.com/a/49411212
tagged with: scipy
has comment: http://stackoverflow.com/comment/85823244
type: Question
has comment: http://stackoverflow.com/comment/85822533
tagged with: numpy
has comment: http://stackoverflow.com/comment/85822410
has body: There is an existing train_labels, which has the following attributes ('labels_train shape ', (3000,)) ('type of labels_train ', &lt;type 'numpy.ndarray'&gt;) and another array is Y, which has the following attributes ('Y ', (3000,1)) ('type of Y ', &lt;type 'numpy.ndarray'&gt;) How to assign Y to labels_train, or how to make Y has the same shape as labels_train?
has comment: http://stackoverflow.com/comment/85822311

http://stackoverflow.com/q/49340713
has body: I am trying to create a search button in a responsive navigation bar. The navigation bar has a media query in the CSS file that reduces it to a dropdown list according to the dimension of the reader's screen. The html of the navigation bar is the following: &lt;nav class="navbarSection"&gt; &lt;div class="topnav" id="myTopnav"&gt; &lt;a href="#home" class="active"&gt;Home&lt;/a&gt; &lt;a href="http://www..."&gt;Chi Siamo e Cosa Facciamo&lt;/a&gt; &lt;a href="http://www..."&gt;Storia di Gabriella&lt;/a&gt; &lt;a href="#articles"&gt;Tutti gli Articoli&lt;/a&gt; &lt;a href="http://www..."&gt;Video Gallery&lt;/a&gt; &lt;a href="http://www..."&gt;Photo Gallery&lt;/a&gt; &lt;a href="http://www..."&gt;Dicono di Noi&lt;/a&gt; &lt;a href="http://www..."&gt;Come Contattarci&lt;/a&gt; &lt;a href="javascript:void(0);" class="icon" onclick="respScreen()"&gt;&amp;#9776;&lt;/a&gt; &lt;a class="material-icons" style="font-size:32px;color:white;"&gt;search&lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; And this is the CSS related: /* Add a red background color to the top navigation */ .topnav { background-color: #aa2222; overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; display: block; color: #fff; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 15px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #d9bb56; color: black; } /* Add an active class to highlight the current page */ .active { background-color: #d9bb56; color: white; } /* Hide the link that should open and close the topnav on small screens */ .topnav .icon { display: none; } /* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */ @media screen and (max-width: 1500px) { .topnav a {display: none;} .topnav a.icon { float: left; display: block; } } /* The "responsive" class is added to the topnav with JavaScript when the use…
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49357218
has answer: http://stackoverflow.com/a/49357218
tagged with: http://stackoverflow.com/tag/html
has title: Django: Creating a navigation bar splitted in two parts with elements styled differently (HTML, CSS, Javascript)
tagged with: django
tagged with: javascript
tagged with: python
score: -1
tagged with: css
type: AnsweredQuestion

http://stackoverflow.com/comment/85866920
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49382515
has text: @Zen you should get the square deviations by calling `res( sol, x, y )**2` or the total `chi2` by `sum( res( sol, x, y )**2 )`

http://stackoverflow.com/q/49317431
score: 0
has body: I am using Python to parse an excel spreadsheet and write documentation to a word document. I want to highlight binary substrings e.g. '001' by having the numbers appear in dark red. I can find the substrings using re being any text which is a binary number sequence between single quotes, that is not my question. The question is how do I put the highlighting on just those characters within the paragraph? The format I would like to end up with is like the following: Any help would be appreciated.
has comment: http://stackoverflow.com/comment/85653763
type: Question
accepted answer: http://stackoverflow.com/a/49317981
has answer: http://stackoverflow.com/a/49317981
has answer: http://stackoverflow.com/a/49365629
has title: How to change the font of particular text in a paragraph when writing a word document using Python-docx?
tagged with: python
tagged with: python-docx
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49365629
answer count: 2

http://stackoverflow.com/q/49399648
answer count: 0
tagged with: apache-spark
type: UnansweredQuestion
has body: i tried to run this code as a python script import findspark findspark.init() from pyspark import SparkContext sc = SparkContext('local') from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['POST']) #can set first param to '/' def toyFunction(): return 'HELLO WORLD' if __name__ == '__main_': app.run(port=8080) #note set to 8080! then what this came out. D:\opt\spark\spark-2.2.0-bin-hadoop2.7>python app.py Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 18/03/21 14:28:25 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable D:\opt\spark\spark-2.2.0-bin-hadoop2.7>SUCCESS: The process with PID 7656 (child process of PID 3876) has been terminated. SUCCESS: The process with PID 3876 (child process of PID 4436) has been terminated.SUCCESS: The process with PID 4436 (child process of PID 1148) has been terminated. any solution? Also tried spark-submit but an error also appeared which I posted here Pyspark in Flask I also read in the post How to run a script in PySpark that running python applications through pyspark is not supported as of Spark 2.0. I am using 2.2.0. one of the solutions was by another person pyspark 2.0 and later execute script file in environment variable PYTHONSTARTUP, so you can run: PYTHONSTARTUP=code.py pyspark Compared to spark-submit answer this is useful for running initialization code before using the interactive pyspark shell. but I do not understand how to do that? can anyone guide me? thank you
has comment: http://stackoverflow.com/comment/85802459
has comment: http://stackoverflow.com/comment/85800682
has comment: http://stackoverflow.com/comment/85802164
linked to: http://stackoverflow.com/q/40028919
has comment: http://stackoverflow.com/comment/85800594
has title: how to run pyspark as py script
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/49390292
score: 0

http://stackoverflow.com/comment/85643820
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49318157
has text: Care to add some data?.. a few rows are sufficient. Also try and fix your indentation in your existing code.
score: 0

http://stackoverflow.com/q/49294519
has comment: http://stackoverflow.com/comment/85591415
type: AnsweredQuestion
score: 0
tagged with: matplotlib-widget
tagged with: matplotlib
has body: I have been trying to add a matplotlib.widget.Button to my matplotlib plotting canvas, which is integrated in wxPython, but without succes. This is the code that generates the canvas: from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas import matplotlib.pyplot as plt import matplotlib matplotlib.use('WXAgg') from matplotlib.widgets import Button import wx self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, proportion=1, flag=wx.ALL | wx.GROW) self.SetSizer(self.sizer) self.Fit() self.canvas.draw() plot_object = self.axes.pcolormesh(combo_value.T, cmap='rainbow', norm=colors.LogNorm(vmin=vmin_value, vmax=vmax_value)) self.canvas.draw() How can I add a button to the axes of this matplotlib plot in wxPython? I have tried to follow this example: https://matplotlib.org/examples/widgets/buttons.html, but without succes since you do not use plt.axes in matplotlib in wxPython I have tried the following which in fact does add a button to the canvas but it is not interactive. axprev = self.figure.add_axes([0.7, 0.01, 0.1, 0.075]) bprev = Button(axprev, 'Previous') bprev.on_clicked(self.test()) def test(self): print('Called') This is what the GUI canvas now looks like: Button that's not interactive
has title: How do I add a matplotlib.widget.Button to my wxpython plotting canvas?
type: Question
has comment: http://stackoverflow.com/comment/85591348
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/49296332
tagged with: python
linked to: http://stackoverflow.com/q/23172916
answer count: 1
has answer: http://stackoverflow.com/a/49296332

http://stackoverflow.com/comment/85575072
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49282819
type: Comment
has text: @user2357112 "TypeError: 'SwigPyObject' object is not iterable" is what I get when I try that...

http://stackoverflow.com/comment/85876209
type: QuestionComment
comment on: http://stackoverflow.com/q/49437153
has text: yeah `dct = {'key': ['500']}.` to create a list-value. And don't use `dict` since it would mask the type.
score: 3
type: Comment

http://stackoverflow.com/a/49399313
has comment: http://stackoverflow.com/comment/85799950
score: 1
has comment: http://stackoverflow.com/comment/85806376
has comment: http://stackoverflow.com/comment/85806328
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85816404
type: Answer
answers question: http://stackoverflow.com/q/49399124
has body: Two answers in one: If you really want to get it parsed quickly, you can do something like this: import ast s = ast.literal_eval('"' + comment.replace('"', '\\"') + '"') s will contain what you want - it will process the string, as if you wrote it in your code this way. (this is safer than actual eval, because it will not allow comment to execute any functions - but you can still break it by including a \" in the comment) To process it correctly though, you'd have to write a proper lexer/parser to analyse it character by character. But really, if you ended up with that string, something is wrong somewhere before. You ended up with a string with escaped unicode instead of actual contents. If it comes from somewhere in your application, the best way would be to trace back to where it originates and ensure you don't end up in this situation in the first place.

http://stackoverflow.com/q/49369192
has body: I am trying to convert a string (utf-8) using French date format to datetime using strptime: import datetime as dt from __future__ import unicode_literals a = "Février 2017".encode('utf-8') dt.datetime.strptime(a,"%B %Y") Result: ValueError: time data 'F\xc3\xa9vrier 2017' does not match format '%B %Y' Problem is, strptime doesn't seem to handle unicode very well: import datetime as dt from __future__ import unicode_literals a = "Février 2017" dt.datetime.strptime(a,"%B %Y") Result: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128) Is there either an accepted format or an alternative to strptime?
downvote count: 0
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/26294333
has comment: http://stackoverflow.com/comment/85741070
duplicate of: http://stackoverflow.com/q/26294333
type: Question
answer count: 0
upvote count: 1
type: UnansweredQuestion
has title: Trouble using strptime with French date format in Python 2.7.14
favorite count: 0

http://stackoverflow.com/q/49371026
has comment: http://stackoverflow.com/comment/85744068
has comment: http://stackoverflow.com/comment/85752169
tagged with: python
has title: Python: Rewriting query within TCP payload using nfqueue/scapy
linked to: http://stackoverflow.com/q/27293924
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85787955
type: UnansweredQuestion
tagged with: tcp
tagged with: scapy
answer count: 1
has body: I'm in no way a networking expert so there is possibly something obvious I am missing here. I'm attempting to rewrite a database query within a TCP payload. I have been able to get this to work for a single scenario but for others it is not working and I don't know why. Got to Work: Changing - 'select * from test1' TO 'select * from test2' Doesn't Work: Changing - 'Select * from test1' TO 'select * from test50' Is this not working due to a change in the size of the payload? Here is an example of my code: import nfqueue from scapy.all import * import os import sys iptable_change = "iptables -A OUTPUT -p tcp --dport 8008 -j NFQUEUE" os.system(iptable_change) def callback(payload): data = payload.get_data() pkt = IP(data) if pkt.src == '127.0.0.1': if 'test1' in pkt[Raw].load: pkt[TCP].payload = str(pkt[TCP].payload).replace("test1", "test50") del pkt[IP].chksum del pkt[TCP].chksum payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(pkt), len(pkt)) def main(): q = nfqueue.queue() q.open() q.bind(socket.AF_INET) q.set_callback(callback) q.create_queue(0) try: q.try_run() except KeyboardInterrupt: q.unbind(socket.AF_INET) q.close() if __name__ == "__main__": main() Is there something I am missing here? Because I am changing a db query do packets need to be handled differently?
has comment: http://stackoverflow.com/comment/85752887
has answer: http://stackoverflow.com/a/49470237
tagged with: payload

liquidsoap
type: Tag
tag name: liquidsoap
tags question: http://stackoverflow.com/q/49319996

http://stackoverflow.com/q/49393683
tagged with: counter
has title: How to count items in a nested dictionary
has comment: http://stackoverflow.com/comment/85789196
type: Question
tagged with: defaultdict
has comment: http://stackoverflow.com/comment/85789242
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85789109
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49393892
tagged with: python
has comment: http://stackoverflow.com/comment/85789228
favorite count: 0
tagged with: dictionary
tagged with: python-3.x
has body: I want to collect results for each date. For each date increment pass fail results and add date in dict if not there. Should I go with dict in dict or defaultdict? e.g. dates= {'2018-03-20': [{'pass': 2}, {'fail': 3}]} And I want to add new date if not in dates and updates 'pass'/ 'fail' value for specific date.
downvote count: 0
accepted answer: http://stackoverflow.com/a/49393892
answer count: 1

http://stackoverflow.com/comment/85792505
score: 0
type: Comment
type: QuestionComment
has text: @pault I use Pyspark and Jupyter. notebook
comment on: http://stackoverflow.com/q/49394396

http://stackoverflow.com/q/49330581
accepted answer: http://stackoverflow.com/a/49476551
type: AnsweredQuestion
has title: User model other than AUTH_USER_MODEL in Django REST Framework
possible better answer: http://stackoverflow.com/a/49445677
has answer: http://stackoverflow.com/a/49476551
answer count: 3
has body: I have an architectural problem. I'm using Django (with admin panel) and DRF (api with stateless authentication using JWT). Django has Admin users represented by model which is more or less the same as default Django User Model. Admins work with Django Admin only and can't use DRF api. DRF has API users that are allowed to use only api through DRF and can't interact with Django Admin or Django Session etc. I know that the best approach is to use multi model inheritance, like: class User(DjangoUserModel): pass class Admin(User): pass class API(User): pass AUTH_USER_MODEL = "User" but the problem is that, those users are completly different. Eg: API user has complex composite key as an username field which is impossible in combination to simple Admin username field. And many other differences. .. The question is: may I use a user object that is not an AUTH_USER_MODEL instance in DRF? So self.request.user will store a model instance that isn't connect in any way with an AUTH_USER_MODEL. Has any of you done something similar?
has answer: http://stackoverflow.com/a/49445677
tagged with: python
favorite count: 0
type: Question
upvote count: 8
score: 8
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/49432747
tagged with: django-rest-framework

http://stackoverflow.com/comment/92383455
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49345499
type: AnswerComment
has text: TensorFlow 2.0 should have a different notion of graph that will be more intuitive and closer to pytorch

http://stackoverflow.com/q/49342038
upvote count: 0
tagged with: python
type: UnansweredQuestion
score: -3
answer count: 1
has body: I'm using Python, csvReader to read from a CSV. One of my columns have multiple variables separated by a "|", and would like to write into separate columns. For example, the 3rd column contains rows of different transportation "cars|trains|airplanes|cabs", and would like to write to a new csv with four separate columns. Each cell can have anywhere from 1-5 variables. Thanks for your help!
has answer: http://stackoverflow.com/a/49342121
type: Question
downvote count: 3
has title: need to split a string within a cell into separate columns using csvReader
has comment: http://stackoverflow.com/comment/85684404
favorite count: 0

http://stackoverflow.com/comment/85826479
type: AnswerComment
comment on: http://stackoverflow.com/a/49317156
has text: Please check this and give me some suggestions https://stackoverflow.com/questions/49412281/how-to-view-the-eliminated-data-after-preprocessing?noredirect=1#comment85826328_49412281
score: 0
type: Comment

http://stackoverflow.com/comment/85572231
type: QuestionComment
comment on: http://stackoverflow.com/q/49284640
has text: Really, you don't. You can work with the dictionary directly.
type: Comment
score: 1

http://stackoverflow.com/a/49389643
answers question: http://stackoverflow.com/q/49389332
has comment: http://stackoverflow.com/comment/85782167
has body: List is a python object. Type help(list) in your interpreter. You would see your screen Usually for some programming languages calling className() would create object of the type class. For example in C++ class MyClass{ var declarations method definitions } MyObj=MyClass() The MyObj in above code is object for your class MyClass. Apply same thing for your code lst is object type of list class that is predefined in Python which we call it as builtin data structure. So your above lst definition would initialize lst to be a empty list. The help section shows two types of constructors for list class those are used in different ways. The second type of constructor list(iterable) would create a list with already created sequence. For example tuple1=(1,'mars') new_list=list(tuple1) print(new_list) would create new list new_list using the tuple which is a iterable.
score: 0
type: Answer

http://stackoverflow.com/q/49345907
type: UnansweredQuestion
score: -2
tagged with: python
duplicate of: http://stackoverflow.com/q/49259470
tagged with: list
has comment: http://stackoverflow.com/comment/85691713
upvote count: 0
has body: Let's assume I have a function that imports the file containing the following numbers: 18.18 18.25 17.5 . . .` where each number has it own line. Then I use the append function on these numbers and I get the following output. My question is if there is a command to save the end list, i.e. the list that is generated when all elements of the data structure have been added? I only want to have the final list.
downvote count: 2
has comment: http://stackoverflow.com/comment/85691725
answer count: 1
has comment: http://stackoverflow.com/comment/85691699
has answer: http://stackoverflow.com/a/49345978
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85691625
has comment: http://stackoverflow.com/comment/85691614
linked to: http://stackoverflow.com/q/49259470
has comment: http://stackoverflow.com/comment/85691674
has title: Get the last list using append

http://stackoverflow.com/comment/85852165
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49425537
score: 0
has text: Well, same technique: `re.findall('Dist(?:[:.]|ance:)(.*?)(?:feet|$)', string, re.DOTALL)` or something. Do you have the "words" in some list variable?

http://stackoverflow.com/q/49374723
type: Question
tagged with: ternary
has body: Could someone help me with the proper format of a python ternary operation on a vector? I have two dataframes temperature: df_today and df_yesterday. I am trying to calculate a new column for df_today to determine whether the temperature is warmer than yesterday: df["warmer_than_yesterday"] = 'yes, warmer' if df["temp_celsius"] &gt; df_yesterday["temp_celsius"] and df["temp_celsius"] &gt; 10 else 'nah, not warmer' However, I keep getting the error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Does anyone know what I might be doing wrong? Thanks in advance!
tagged with: python
accepted answer: http://stackoverflow.com/a/49374761
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49374761
tagged with: vector
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Python ternary operation on vectors
favorite count: 0

http://stackoverflow.com/q/49375356
has comment: http://stackoverflow.com/comment/85755223
has title: Dimension 1 in both shapes must be equal, but are 128 and 164. Shapes are [8,128] and [8,164]
has comment: http://stackoverflow.com/comment/85759703
has body: I got that problem when I used keras to try training virtual car to avoid obstacles from flat_game import carmunk import numpy as np from nn import neural_net NUM_SENSORS = 8 def play(model): car_distance = 0 game_state = carmunk.GameState(display_hidden=False) # Do nothing to get initial. _, state = game_state.frame_step((2)) # Move. while True: car_distance += 1 # Choose action. action = (np.argmax(model.predict(state, batch_size=1))) # Take action. _, state = game_state.frame_step(action) # Tell us something. if car_distance % 1000 == 0: print("Current distance: %d frames." % car_distance) if __name__ == "__main__": saved_model = 'saved-models/164-150-100-50000-625000.h5' model = neural_net(NUM_SENSORS, [128, 128], saved_model) play(model) I got a problem in line model = neural_net(NUM_SENSORS, [128, 128], saved_model) Here is my neural_net function: def neural_net(num_sensors, params, load=''): model = Sequential() print(params) # First layer. model.add(Dense( params[0], init='lecun_uniform', input_shape=(num_sensors,) )) model.add(Activation('relu')) model.add(Dropout(0.2)) # Second layer. model.add(Dense(params[1], init='lecun_uniform')) model.add(Activation('relu')) model.add(Dropout(0.2)) # Output layer. # Output layer. 5 actions left, right, accelerate, decelerate, forward model.add(Dense(5, init='lecun_uniform')) model.add(Activation('linear')) rms = RMSprop() model.compile(loss='mse', optimizer=rms) if load: model.load_weights(load) return model and i am getting this error when i run main in the first code: File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2404, in call_with_requiring return call_cpp_shape_fn(op, require_shape_fn=True) File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 627, in call_cpp_shape_fn require_shape_fn) File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 691, in _call_cpp_shape_fn_impl raise ValueError(err.message) ValueError: …
answer count: 0
score: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85752565
tagged with: keras
type: Question
has comment: http://stackoverflow.com/comment/85755351
has comment: http://stackoverflow.com/comment/85752581
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85910585
score: 0
comment on: http://stackoverflow.com/q/49412931
type: Comment
type: QuestionComment
has text: Int64Index: 710719 entries, 0 to 710718 Data columns (total 5 columns): monthenddate 710719 non-null object lastweekday 710719 non-null object item 710719 non-null object sedols 710719 non-null object value 710719 non-null float64 dtypes: float64(1), object(4) memory usage: 32.5+ MB None

http://stackoverflow.com/q/49368553
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: avx
accepted answer: http://stackoverflow.com/a/49368608
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49368608
tagged with: python
has comment: http://stackoverflow.com/comment/118274686
type: AnsweredQuestion
score: 1
answer count: 1
has title: Tensorflow for mac AVX
has body: I'm using TensorFlow but I'm getting the following warning The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations I installed it using pip. How can I fix it?

http://stackoverflow.com/a/49378858
answers question: http://stackoverflow.com/q/49378851
score: 0
type: Answer
has body: After you use replace you need to save it back to the variable. Ex: lines = lines.replace("&lt;header &gt;", "&lt;header style=background-color:red &gt;")

http://stackoverflow.com/comment/85826963
score: 0
type: QuestionComment
has text: I don't see such fields in data which are all array types
comment on: http://stackoverflow.com/q/49396558
type: Comment

http://stackoverflow.com/q/49439303
answer count: 1
has title: Preparing my own picture data into Tensorflow
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49440751
accepted answer: http://stackoverflow.com/a/49440751
tagged with: python
type: AnsweredQuestion
score: 0
has body: I am new to Tensorflow and NN. I played something with MNIST, but now I want to use own pictures to build my own Network. I made black pictures with white points on it and I want to train the Network to count the points. My Problem is to put get my image data into Tensorflow. I googeld a lot and found some informations and put it together to my own code. Put it didn't work as I expected. So do you have a tip for me to get my picture data into tensorflow? Traceback (most recent call last): File "C:...", line 490, in apply_op preferred_dtype=default_dtype) File "C:...", line 741, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "C:...", line 614, in _TensorTensorConversionFunction % (dtype.name, t.dtype.name, str(t))) ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("Variable_2/read:0", shape=(5000, 100), dtype=float32)' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "...", line 83, in trainnetwork(x) File "...", line 74, in trainnetwork prediction = neuralnetworkmodel(x) File "...", line 69, in neuralnetworkmodel output = tf.matmul (11,output_layer['weights']) + output_layer['biases'] File "...", line 1816, in matmul a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) File "C:...", line 1217, in _mat_mul transpose_b=transpose_b, name=name) File "C:...", line 526, in apply_op inferred_from[input_arg.type_attr])) TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'. import numpy as np import glob import scipy.ndimage import tensorflow as tf n_nodes_hl= 5000 n_classes = 101 x=tf.placeholder(tf.float32, [None, 22400]) y=tf.placeholder(tf.int32,[None, n_classes]) label_dataset = [] img_dataset = [] for image_file_name in glob.glob("C:\\Users\\Thorsten\\Desktop\\InteSystem\\Seg\\Baum???_sw_*.png"): print("loading ... ", image_file_name) # filename for the co…

http://stackoverflow.com/a/52498491
score: 0
has body: You are trying to solve two distinct problems Managing knowledge base for answering questions for users to learn/understand providing the status of a particular ticket The first part can be comprehensively managed by using Q&amp;A maker service without employing a line of code. refer... https://www.qnamaker.ai/ The second part has a sole purpose of fetching a value from the database based on the entity value (ticket). Focus on building and fine-tuning the bot only for the second part and integrate Q&amp;A maker as a knowledge base which will take care of first part.
type: Answer
answers question: http://stackoverflow.com/q/49362788

http://stackoverflow.com/q/49371489
downvote count: 0
tagged with: output
answer count: 1
favorite count: 0
tagged with: format
type: Question
accepted answer: http://stackoverflow.com/a/49371724
tagged with: python
has answer: http://stackoverflow.com/a/49371724
tagged with: numpy
has body: Not sure about the syntax of the output I am receving. Any help would be appreciated. Here is my code: import numpy def g(): #generate random complex values return numpy.random.random(1) + numpy.random.random(1) *1j p = numpy.poly1d(numpy.squeeze([g(),g(),g()])) # test function p pprime = numpy.polyder(p) #derivative of p print 'Our p(x) is {} '. format(p) print('\n') # new line print'Our pprime(x) is {} '. format(pprime) #apply newtons method to p print('\n') # new line #apply newtons method to p def root_newton ( f, df, tolerance = 1.0e-6): dx = 2 * tolerance x=0 while dx &gt; tolerance: x1 = x - f(x)/df(x) dx = abs (x - x1) x = x1 return x print('Our first root is at {}'.format(root_newton(p,pprime))) print('\n') # new line Here's the output: Our p(x) is 2 (0.6957 + 0.683j) x + (0.3198 + 0.5655j) x + (0.9578 + 0.1899j) Our pprime(x) is (1.391 + 1.366j) x + (0.3198 + 0.5655j) Our first root is at (0.00925817978737+0.830966156841j) The correct roots are [-0.64968928-1.01513333j 0.00925818+0.83096616j] What does the 2 above the second component in my first line outputted mean? I can't find anything similar to my question online. I am guessing it may mean the x component is squared but I'm not sure? This is python 3 by the way.
has title: Python output formatting issues
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/85750154
type: AnswerComment
comment on: http://stackoverflow.com/a/49374352
score: 2
has text: No, can't use pandas, my response was made before your edit. Numpy solution works.
type: Comment

http://stackoverflow.com/comment/85630824
type: AnswerComment
score: 0
has text: It works fine :) but i'm wondering how to solve this by pivot table? can't I keep multiple column as index in pivot?
comment on: http://stackoverflow.com/a/49314719
type: Comment

http://stackoverflow.com/comment/85764023
has text: Now that I look at it, I think your gif image is indeed a false color one. Hang on, I'll draft an answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49375502
score: 0

http://stackoverflow.com/q/49322289
accepted answer: http://stackoverflow.com/a/49372356
tagged with: python
has answer: http://stackoverflow.com/a/49372356
has body: I am trying to get messages from a topic on a message hub on bluemix using Confluent Kafka Python. My code is found below, but something is not working. The topic and the message hub is up and running, so there is probably something with the code. from confluent_kafka import Producer, KafkaError, Consumer consumer_settings = { 'bootstrap.servers': 'broker-url-here', 'group.id': 'mygroup', 'default.topic.config': {'auto.offset.reset': 'smallest'}, 'sasl.mechanisms': 'PLAIN', 'security.protocol': 'ssl', 'sasl.username': 'username-here', 'sasl.password': 'password-here', } c = Consumer(**consumer_settings) c.subscribe(['topic-here']) running = True while running: msg = c.poll() if msg.error(): print("Error while retrieving message") c.close() sys.exit(10) elif (msg is not None): for x in msg: print(x) else: sys.exit(10) When I run the code, it seems to get stuck at msg = c.poll(). So I guess it is either failing to connect, or failing to retrieve messages. The credentials themselves are correct.
score: 2
type: AnsweredQuestion
tagged with: confluent-platform
upvote count: 2
has title: Retrieve messages from a topic on a message hub
tagged with: message-hub
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: apache-kafka
tagged with: ibm-cloud

http://stackoverflow.com/comment/85567387
type: Comment
comment on: http://stackoverflow.com/a/49282061
has text: @handavidbang - I add explanation to your functions, it return something else.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85752609
has text: 1. Code in an endless loop is not suited for cron. 2. It you run in an endless loop you should add some sleep time to prevent full CPU usage.
comment on: http://stackoverflow.com/q/49375721
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85838962
has text: Thanks a lot kabanus! Your answer was really helpful and I completely understand why my program messed up here. Thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49402944
type: Comment

http://stackoverflow.com/comment/85626706
comment on: http://stackoverflow.com/q/49312256
score: 0
has text: I've updated the question to display the bare bones problem at hand.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85574927
has text: thank you, but i want solution with pillow and django
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49286042

http://stackoverflow.com/q/49431271
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49557447
accepted answer: http://stackoverflow.com/a/49557447
has body: I'm trying to use win32security module. More precisely, I need to use GetEffectiveRightsFromAcl()(PyACL Object). How can I get the PyTRUSTEE trustee that needs to call this function?
has title: How to use GetEffectiveRightsFromAcl function in python?
score: 2
tagged with: python
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/a/55499092
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49361591
has body: As YUV 4:2:2 has some variants, it would be easier if you can find exactly what is your YUV format. I use Logitech Brio Webcam to shoot YUV videos with ffmpeg which gives me the YUV in (YUY2 / 0x32595559), yuyv422. This is also the YUV 4:2:2 but has some differences in the order of bytes. As YUV 4:2:2 compression ratio is 2/3, you were correct to use 2 bytes for 1 pixel. This worked for me. frame_len = int(width * height * 2) shape = (height, width, 2) And to convert from YUV to BGR (opencv format): bgr = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR_YUY2)

http://stackoverflow.com/q/49353289
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/30163830
has comment: http://stackoverflow.com/comment/85706840
accepted answer: http://stackoverflow.com/a/53582015
tagged with: python
has comment: http://stackoverflow.com/comment/85708779
has body: I want to iteratively fill a scipy sparse coo_matrix # Constructing an empty matrix import numpy as np from scipy.sparse import coo_matrix m = coo_matrix((3, 4), dtype=np.int8) by a for loop and some rules, e.g. all ones (I know there's a constructor with data but I can't use it since the rule is more complex). How can I do that? I haven't found any documentation about it.
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/53582015
has title: Fill scipy sparse.coo_matrix by for loop
score: 1
upvote count: 1
answer count: 1
tagged with: scipy
tagged with: sparse-matrix

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49383711
tags question: http://stackoverflow.com/q/49358270
tags question: http://stackoverflow.com/q/49355204
tags question: http://stackoverflow.com/q/49336607
tags question: http://stackoverflow.com/q/49310483
tags question: http://stackoverflow.com/q/49425805
tags question: http://stackoverflow.com/q/49408048
type: Tag
tags question: http://stackoverflow.com/q/49370550
tags question: http://stackoverflow.com/q/49307927

http://stackoverflow.com/a/49382268
type: Answer
type: AcceptedAnswer
downvote count: 1
score: 17
accepted answer of: http://stackoverflow.com/q/49381899
has body: The glob will not magically start working with a remote server, just because you have instantiated SSHClient before. You have to use Paramiko API to list the files, like SFTPClient.listdir: import fnmatch sftp = client.open_sftp() for filename in sftp.listdir('/home/test'): if fnmatch.fnmatch(filename, "*.txt"): print filename You can also use a regular expression for the matching, if it suits your needs better. See Using wildcard in remote path using Paramiko's SFTPClient. Side note: Do not use AutoAddPolicy. You lose security by doing so. See Paramiko "Unknown Server".
answers question: http://stackoverflow.com/q/49381899
upvote count: 18

http://stackoverflow.com/q/49374375
has body: I'm trying to implement the built in Django authentication views in my site to help with the password resets for users. I've set the root urls to include the provided URLconf in django.contrib.auth.urls like so: path('', include('django.contrib.auth.urls')) I've set all the templates in a registration folder in my templates directory. So, if i go to /password_reset, i get the correct page to change my password If i enter an email, i DO receive the change password email. If i click the link in the email, i get to the reset/***/set-password page But if i try to enter a new password it submits and goes to reset/done but i get following error: NoReverseMatch at /reset/done/ Reverse for 'sign_in' not found. 'sign_in' is not a valid view function or pattern name. I do also have an 'accounts' app in my project which includes a custom 'sign_in' url. Could this be the issue? Is this overriding some sort of prebuilt sign_in page from Django? app_name = "accounts" urlpatterns = [ url(r'sign_in/$', views.sign_in, name='sign_in'), url(r'sign_up/$', views.sign_up, name='sign_up'), url(r'sign_out/$', views.sign_out, name='sign_out'), url(r'profile/$', views.view_profile, name='profile'), url(r'profile/edit/$', views.edit_profile, name='edit_profile'), url(r'profile/change_password/$', views.change_password, name='change_password'), url(r'favorites/$', views.view_favorites, name='favorites'), url(r'^subscribe/', views.subscribe, name = "subscribe"),
tagged with: django
tagged with: python
score: 0
has title: No Reverse Match When Resetting Password in Django
answer count: 1
has answer: http://stackoverflow.com/a/49374734
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49385363
has comment: http://stackoverflow.com/comment/85790538
tagged with: python
has answer: http://stackoverflow.com/a/49385475
has body: I have the following json object I am trying to parse with python 3: customerData = { "Joe": {"visits": 1}, "Carol": {"visits": 2}, "Howard": {"visits": 3}, "Carrie": {"visits": 4} } I am using the following python code to parse the object: import json def greetCustomer(customerData): response = json.loads(customerData) I'm getting the following error: TypeError: the JSON object must be str, bytes or bytearray, not 'dict'
accepted answer: http://stackoverflow.com/a/49385417
score: 4
has answer: http://stackoverflow.com/a/49385417
has comment: http://stackoverflow.com/comment/85771881
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85771500
has comment: http://stackoverflow.com/comment/85771550
possible better answer: http://stackoverflow.com/a/49385475
has comment: http://stackoverflow.com/comment/85771505
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has comment: http://stackoverflow.com/comment/85772178
has title: Error while trying to load a JSON object with python 3
favorite count: 0
type: Question
upvote count: 4
answer count: 2

http://stackoverflow.com/a/49306979
has comment: http://stackoverflow.com/comment/85637460
downvote count: 0
type: Answer
has body: Assuming the final order is not important, you could use a collections.Counter(): &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c = Counter(dict(zip(coins, quantity))) &gt;&gt;&gt; list(c.elements()) [10, 100, 50, 50] &gt;&gt;&gt; c Counter({50: 2, 10: 1, 100: 1})
score: 2
answers question: http://stackoverflow.com/q/49306694
upvote count: 2

http://stackoverflow.com/comment/85640108
has text: yes, or you could use `irb -r ./filename.rb` directly, to more closely mimic python's command-line behaviour.
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49319560

http://stackoverflow.com/a/49354697
answers question: http://stackoverflow.com/q/49354618
type: Answer
upvote count: 1
has body: The problem with your code is that you are comparing each letter to words. In your example, set(myList) results in {'hello', 'world'}. You then compare each letter in 'old' to this set. As you can see, this will fail (e.g. the letter 'o' is not in the set {'hello', 'world'} even though it is in a word in the set). &gt;&gt;&gt; 'o' in set(my_list) False You may find this useful, where your a set of unique letters are created from the list of words using a set comprehension, and then another set is taken of the unique letters in your string. my_list = ["hello","world"] my_string = 'old' list_letters = {letter for letter in word for word in my_list} # {'d', 'e', 'h', 'l', 'o', 'r', 'w'} word_letters = set(my_string) # {'d', 'l', 'o'} &gt;&gt;&gt; word_letters.issubset(list_letters) # Output: True Turning this into a one liner: &gt;&gt;&gt; set(my_string).issubset({letter for letter in word for word in my_list}) True The other problem with your code is that you do not want to return True when it finds a letter in my_list (i.e. the last line of your code). You can return False if a letter is not in my_list, but must then return True if you've iterated through all the letters, e.g. for word in myList: if x not in word: return False return True You could also use all: if all(x in word for word in myList): return True return False # Not really needed, since it would return None which is a falsey.
downvote count: 0
score: 1

http://stackoverflow.com/a/49418546
answers question: http://stackoverflow.com/q/49414976
upvote count: 7
downvote count: 0
score: 7
type: Answer
has body: At the moment because you are using a ForeignKey field on the person attribute, it means that its returning a list when you access the reverse relation. One solution would be to use a slug related field, though this must have many and read_only set to True, and will return a list because of the ForeignKey field. class PersonSerializer(serializers.ModelSerializer): employee_code = serializers.SlugRelatedField( source='person_info', slug_field='code', many=True, read_only=True, ) class Meta: model = Person fields = ('name', 'address', 'employee_code') The other option is to change your ForeignKey into a OneToOneField, which would still need read_only set to True but it will not return a list. class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Employee(models.Model): person = models.OneToOneField(Person, related_name='person_info') code = models.CharField() class PersonSerializer(serializers.ModelSerializer): employee_code = serializers.SlugRelatedField( source='person_info', slug_field='code', read_only=True, ) class Meta: model = Person fields = ('name', 'address', 'employee_code') Or, if you don't want to change the ForeignKey, you could add a employee_code property method to the model instead to return the first employee code in the person_info relation. class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) @property def employee_code(self): employees = self.person_info.filter() if employees.exists(): return employees.first().code return '' class Employee(models.Model): person = models.OneToOneField(Person, related_name='person_info') code = models.CharField() class PersonSerializer(serializers.ModelSerializer): employee_code = serializers.CharField( read_only=True, ) class Meta: model = Person fields = ('name', 'address', 'employee_code')

http://stackoverflow.com/comment/85845962
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49422283
has text: What is the textedit ?, I see that the problem is caused before doing it.

http://stackoverflow.com/comment/85798178
comment on: http://stackoverflow.com/q/49398282
score: 1
type: Comment
type: QuestionComment
has text: @BurhanKhalid what do you mean by prime the while loop? `while value < n: value=random.random()`?

http://stackoverflow.com/comment/85815892
score: 0
has text: I've fumbled through numpy.linalg.lstsq, linalg.norm and a few attempts at manually calculations to solve the following equation: ∥r∥2=∥Xθ∗−y∥2 but with no luck. Any suggestions?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49407029

http://stackoverflow.com/a/49284671
downvote count: 0
has comment: http://stackoverflow.com/comment/85581111
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85582809
answers question: http://stackoverflow.com/q/49284466
has comment: http://stackoverflow.com/comment/85581379
has body: IIUC New = df_update[df_update.C == 'na'] s=New.reset_index().groupby('A').apply(lambda x : x['index'].diff().ne(1)).cumsum() df_update.loc[df_update.C == 'na','C']+='_'+s.astype(str).str.pad(2,fillchar='0').values df_update Out[124]: A B C 0 2 11 abc 1 2 13 cdd 2 2 15 na_01 3 2 19 na_01 4 2 25 na_01 5 2 35 cdd 6 2 41 cdd 7 2 47 cdd 8 2 46 na_02 9 2 51 na_02 10 3 9 cdd 11 3 15 cdd 12 3 17 cdd 13 3 23 cdd 14 3 25 na_03 15 3 29 na_03 16 5 4 na_04 17 5 23 na_04 18 5 28 na_04

http://stackoverflow.com/comment/85697462
type: QuestionComment
has text: add form in the template to upload the mat file. Inside the views get the file and use your python code to process through it and send the result back to the template
comment on: http://stackoverflow.com/q/49348234
score: 0
type: Comment

http://stackoverflow.com/q/49396558
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85810282
favorite count: 0
has comment: http://stackoverflow.com/comment/85811153
type: Question
has comment: http://stackoverflow.com/comment/85798492
tagged with: apache-spark-sql
has body: I'm trying to work with JSON file on spark (pyspark) environment. Problem: Unable to convert JSON to expected format in Pyspark Dataframe 1st Input data set: https://health.data.ny.gov/api/views/cnih-y5dw/rows.json In this file metadata is defined at start for of the file with tag "meta" and then followed by data with tag "data". FYI: Steps taken to download data from web to local drive. 1. I've downloaded file to my local drive 2. then pushed to hdfs - from there I'm reading it to spark environment. df=sqlContext.read.json("/user/train/ny.json",multiLine=True) df.count() out[5]: 1 df.show() df.printSchema() root |-- data: array (nullable = true) | |-- element: array (containsNull = true) | | |-- element: string (containsNull = true) |-- meta: struct (nullable = true) | |-- view: struct (nullable = true) | | |-- attribution: string (nullable = true) | | |-- attributionLink: string (nullable = true) | | |-- averageRating: long (nullable = true) | | |-- category: string (nullable = true) | | |-- columns: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- cachedContents: struct (nullable = true) | | | | | |-- average: string (nullable = true) | | | | | |-- largest: string (nullable = true) | | | | | |-- non_null: long (nullable = true) | | | | | |-- null: long (nullable = true) | | | | | |-- smallest: string (nullable = true) | | | | | |-- sum: string (nullable = true) | | | | | |-- top: array (nullable = true) | | | | | | |-- element: struct (containsNull = true) | | | | | | | |-- count: long (nullable = true) | | | | | | | |-- item: string (nullable = true) | | | | |-- dataTypeName: string (nullable = true) | | | | |-- description: string (nullable = true) | | | | |-- fieldName: string (nullable = true) | | | | |-- flags: array (nullable = true) | | | | | |-- element: string (containsNull = true) | | | | |-- format: struct (nullable = true) | | | | | |-- align: string (nullable = true) | | | | | |-- mask: string (nullable = true) | | …
upvote count: 2
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/49397849
has comment: http://stackoverflow.com/comment/85796541
score: 2
has comment: http://stackoverflow.com/comment/85812487
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85827069
has title: Json file to pyspark dataframe
has comment: http://stackoverflow.com/comment/85815093
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85826963
accepted answer: http://stackoverflow.com/a/49397849
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/85612337
type: QuestionComment
score: 2
has text: Your posted code suggests you actually have a 1-item list, containing a dict?
comment on: http://stackoverflow.com/q/49305060
type: Comment

http://stackoverflow.com/q/49377809
has comment: http://stackoverflow.com/comment/85760012
has comment: http://stackoverflow.com/comment/85757046
tagged with: lstm
linked to: http://stackoverflow.com/q/54176051
has comment: http://stackoverflow.com/comment/85760072
tagged with: deep-learning
answer count: 0
upvote count: 3
downvote count: 0
tagged with: keras
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/85761963
type: Question
has comment: http://stackoverflow.com/comment/86033037
has body: It worked well with MLP for binary classification. In LSTM and in convolution however it gives the InvalidArgumentError. I found that y needs to be reshaped and I did it. I tried x with all positive values, and model worked well. So what is the problem with negative values? The data is given in the code. Any ideas? The error is like: --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) /usr/local/src/conda3_runtime/home/envs/DSX-Python35-Spark/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1326 try: -&gt; 1327 return fn(*args) 1328 except errors.OpError as e: .... File "/usr/local/src/conda3_runtime/home/envs/DSX-Python35-Spark/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): indices[0,0] = -1 is not in [0, 10) [[Node: embedding_11/Gather = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, validate_indices=true, _device="/job:localhost/replica:0/task:0/cpu:0"](embedding_11/embeddings/read, _arg_embedding_11_input_0_3)]] Code: from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM max_features=10 maxlen=4 embedding_size=4 lstm_output_size = 1 batch_size = 2 epochs = 2 x=([[ 0, 6, 1, 0], [-1, 0, 0, 1], [ 4, -4, 3, 0], [-1, 9, 1, -5], [-2, 0, 0, 0], [ 2, 0, 4, 1], [ 4, 10, -4, -4], [ 0, 10, -1, -4], [ 3, -2, 2, 1], [ 0, -1, 0, 0]]) y=([[0, 1, 0, 0, 1, 0, 0, 0, 0, 1]]) x, y = np.array(x), np.array(y) y = y.reshape((10, 1)) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) print('Build model...') model = Sequential() model.add(Embedding(max_features, 64, input_length = maxlen )) model.add(LSTM(64, activation="sigmoid", return_sequences=True, recurrent_activation=…
score: 3
has title: InvalidArgumentError: indices[0,0] = -1 is not in [0, 10)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/124168412

http://stackoverflow.com/q/49404916
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/39812384
tagged with: postgresql
has answer: http://stackoverflow.com/a/49408970
has comment: http://stackoverflow.com/comment/85813450
has title: Django & Postgres: persisting 'ProgrammingError: column does not exist'
answer count: 1
downvote count: 0
has body: I know this question has been asked on SO before however I have tried everything that has been suggested in the answers and none seem to work. Problem: I have a model class called 'Accomm' in my Django project where I have a number of objects stored. On the web pages where I try to retrieve one or more instances of 'Accomm' then the following error is raised... ProgrammingError at / column objects_accomm.description does not exist LINE 1: ...omm"."id", "objects_accomm"."mapped_location_id", "objects_a... This problem started to occur when I migrated a new field 'description' to the 'Accomm' model. Tried solutions: I have attempted to do the following things... clear all Django migrations (using the --zero and --empty commands); clear the database (PostgreSQL 10); clear both the migrations and database; changing the name of my database in the Django project settings.py file. None of these seem to work. I have also followed tutorials here, here and here. Full error: Django Version: 1.11.7 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'rest_framework', 'accounts', 'maps', 'objects', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. …
score: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/42613536
has comment: http://stackoverflow.com/comment/85810767
has comment: http://stackoverflow.com/comment/85812998
has comment: http://stackoverflow.com/comment/85812061
type: UnansweredQuestion

http://stackoverflow.com/comment/85873715
has text: forgot to add, im using Python
type: Comment
comment on: http://stackoverflow.com/q/49435909
type: QuestionComment
score: 0

http://stackoverflow.com/q/49290333
type: Question
has answer: http://stackoverflow.com/a/49291478
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49290453
has comment: http://stackoverflow.com/comment/85584047
tagged with: python
has title: Why does my code keep returning none instead of the barcode?
has comment: http://stackoverflow.com/comment/85583802
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85583783
has comment: http://stackoverflow.com/comment/85583808
has comment: http://stackoverflow.com/comment/85583785
has body: This code is supposed to print out a "barcode" from a given zip code. The problem is that it is only printing out none after it is done. No visible errors to me. Could you take a look? def printDigit(d , x): if x &lt;= 5: if d[x] == 0: return "||:::" + printDigit(d , x + 1) elif d[x] == 1: return ":::||" + printDigit(d , x + 1) elif d[x] == 2: return "::|:|" + printDigit(d , x + 1) elif d[x] == 3: return "::||:" + printDigit(d , x + 1) elif d[x] == 4: return ":|::|" + printDigit(d , x + 1) elif d[x] == 5: return ":|:|:" + printDigit(d , x + 1) elif d[x] == 6: return ":||:|" + printDigit(d , x + 1) elif d[x] == 7: return "|:::|" + printDigit(d , x + 1) elif d[x] == 8: return "|::|:" + printDigit(d , x + 1) elif d[x] == 9: return "|:|::" + printDigit(d , x + 1) else: return zipCode = str(input("Input a zip code: ")) print(printDigit(zipCode , 0))

http://stackoverflow.com/q/49310466
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/49310865
type: UnansweredQuestion
has body: I'd like to save a calculated histogram from a file so that I can reopen it without having to recompute it, but I'm not sure how I would go about saving and then reading it again. image_path = "/Users/..../test.jpg" image = cv2.imread(image_path, 0) if image is not None: hist = cv2.calcHist([image], [0], None, [256], [0, 256]) cv2.imwrite("/Users/.../hist.jpg", hist) # What should this be? hist = cv2.imread("/Users/.../hist.jpg", 0) # And this? EDIT: So I'd like to do something like this, but I'm not sure what the syntax would be. with open('hist.txt', 'a') as fp: fp.write('%s %s %s', [hist_id, list(hist), color]) with open('hist.txt', 'r') as fp: lines = fp.readlines() for line in lines: hist_id = line[0] hist = np.array(eval(line[1])) color = line[2] cv2.compare(hist.....) EDIT 2: new_entry = [image, list(hist1), list(hist2)] for item in new_entry: fd.write("%s\t" % item) fd.write("\n") with open('hist.txt', 'r') as fd: lines = fd.readlines() for line in lines: line = line.split('\t') cv2.compareHist(numpy.array(line[1]), numpy.array(line[2]))
tagged with: python
tagged with: python-2.7
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/49310737
downvote count: 0
upvote count: 1
has title: How can I save a OpenCV histogram to a file in Python?
favorite count: 0

http://stackoverflow.com/comment/85662141
comment on: http://stackoverflow.com/a/49322470
score: 0
type: Comment
has text: I am getting the following error: KeyError: 'the label [<function <lambda> at 0x0000000007EB1B38>] is not in the [index]'
type: AnswerComment

http://stackoverflow.com/a/49368626
has comment: http://stackoverflow.com/comment/85745333
accepted answer of: http://stackoverflow.com/q/49368348
has comment: http://stackoverflow.com/comment/85745277
upvote count: 2
has comment: http://stackoverflow.com/comment/85740083
has body: The site is dymamic, which means you need to use a browser manipulation tool such as selenium. Then, extract text from multiple class names for each search: import urllib import re from bs4 import BeautifulSoup as soup from selenium import webdriver def get_table(): d = webdriver.Chrome('path/to/driver') #or webdriver.Firefox(), depending on your browser d.get('http://www.megamillions.com/winning-numbers/search?startDate=1/1/2017&amp;endDate=3/31/2018') table = [i.text for i in soup(d.page_source, 'lxml').find_all('td', {'class':re.compile('dates|number|mega|details')})] final_table = [table[i:i+9] for i in range(0, len(table), 9)] last_data = [dict(zip(['draw_date', 'balls', 'megaball', 'megaplier', 'details'], [a, b, c, d, e])) for a, *b, c, d, e in final_table] return last_data print(get_table()) Output: [{'draw_date': '12/29/2017', 'balls': ['4', '10', '18', '28', '62'], 'megaball': '7', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/26/2017', 'balls': ['10', '12', '20', '38', '41'], 'megaball': '25', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/22/2017', 'balls': ['1', '20', '30', '33', '42'], 'megaball': '16', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/19/2017', 'balls': ['28', '37', '39', '42', '58'], 'megaball': '2', 'megaplier': '3', 'details': 'Details'}, {'draw_date': '12/15/2017', 'balls': ['4', '12', '36', '44', '57'], 'megaball': '19', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/12/2017', 'balls': ['8', '23', '24', '25', '27'], 'megaball': '9', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/8/2017', 'balls': ['6', '37', '46', '60', '70'], 'megaball': '24', 'megaplier': '2', 'details': 'Details'}, {'draw_date': '12/5/2017', 'balls': ['14', '15', '37', '42', '67'], 'megaball': '22', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '12/1/2017', 'balls': ['16', '22', '40', '41', '59'], 'megaball': '8', 'megaplier': '4', 'details': 'Details'}, {'draw_date': '11/28/2017', 'balls': ['1…
has comment: http://stackoverflow.com/comment/85746273
type: AcceptedAnswer
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49368348
downvote count: 0

tracd
tag name: tracd
type: Tag
tags question: http://stackoverflow.com/q/49412064

http://stackoverflow.com/comment/85584785
type: QuestionComment
has text: Yes, I'll post something in a bit. no idea why the two modes work differently though.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49290456

http://stackoverflow.com/q/49411277
has comment: http://stackoverflow.com/comment/85824537
answer count: 3
tagged with: anaconda
linked to: http://stackoverflow.com/q/24712994
downvote count: 0
has comment: http://stackoverflow.com/comment/85824460
has body: I'm using Python to automate some reporting, but I am stuck trying to connect to an SSAS cube. I am on Windows 7 using Anaconda 4.4, and I am unable to install any libraries beyond those included in Anaconda. I have used pyodbc+pandas to connect to SQL Server databases and extract data with SQL queries, and the goal now is to do something similar on an SSAS cube, using an MDX query to extract data, but I can't get a successful connection. This first connection string is very similar to the strings that I used to connect to the SQL Server databases, but it gives me an authentication error. I can access the cube no problem using SQL Server Management Studio so I know that my Windows credentials have access. connection = pyodbc.connect('Trusted_Connection=yes',DRIVER='{SQL Server}',SERVER='Cube Server', database='Cube') query = "MDX query" report_df = pandas.read_sql(query, connection) Error: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '*****'. (18456) (SQLDriverConnect)") When I tried to replicate the attempts at Question1 and Question2 I got a different error: Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Any help/guidance would be greatly appreciated. My experience with SSAS cubes is minimal, so it is possible that I am on the completely wrong path for this task and that even if the connection issue gets solved, there will be another issue loading the data into pandas, etc.
linked to: http://stackoverflow.com/q/64461817
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85824346
has answer: http://stackoverflow.com/a/65434851
tagged with: ssas
has title: Connect to SQL Server Analysis Cube with Python (Anaconda)
tagged with: python
has comment: http://stackoverflow.com/comment/85824470
has answer: http://stackoverflow.com/a/65971744
has answer: http://stackoverflow.com/a/49411531
score: 2
tagged with: sql-server
linked to: http://stackoverflow.com/q/38985729
has comment: http://stackoverflow.com/comment/115685924

http://stackoverflow.com/q/49350870
has comment: http://stackoverflow.com/comment/85731825
favorite count: 0
has comment: http://stackoverflow.com/comment/85702960
has body: I am creating a program that takes user input through raw_input and puts it into a text file in code (as in a = 2, c = 6 for example). I want to be able to hide what the user is typing into the program before they hit enter (and are then shown the coded text) Here is the code: #!/usr/bin/python npt = raw_input (("26 Char Cyper Sentence: ").lower()) L = list(npt) r = raw_input ('{name of file}: ') txt='.txt' me=r+txt folder = open(me, 'a') while True: a = L[0];b = L[1];c = L[2];d = L[3];e = L[4];f = L[5];g = L[6];h = L[7]; i = L[8];j = L[9];k = L[10];l = L[11];m = L[12];n = L[13];o = L[14];p = L[15]; q = L[16];r = L[17];s = L[18];t = L[19];u = L[20];v = L[21];w = L[22];x = L[23];y = L[24];z = L[25] txtt = raw_input (('{\n').lower()) txt = txtt.lower () new1 = txt.replace ('a', a) new2 = new1.replace ('b', b) new3 = new2.replace ('c', c) new4 = new3.replace ('d', d) new5 = new4.replace ('e', e) new6 = new5.replace ('f', f) new7 = new6.replace ('g', g) new8 = new7.replace ('h', h) new9 = new8.replace ('i', i) new10 = new9.replace ('j', j) new11 = new10.replace ('k', k) new12 = new11.replace ('l', l) new13 = new12.replace ('m', m) new14 = new13.replace ('n', n) new15 = new14.replace ('o', o) new16 = new15.replace ('p', p) new17 = new16.replace ('q', q) new18 = new17.replace ('r', r) new19 = new18.replace ('s', s) new20 = new19.replace ('t', t) new21 = new20.replace ('u', u) new22 = new21.replace ('v', v) new23 = new22.replace ('w', w) new24 = new23.replace ('x', x) new25 = new24.replace ('y', y) new26 = new25.replace ('z', z) print (new26.lower ()) folder.write ((new26).lower ()) I am using Python 2.7 on Windows 10 and have already tried the 'getpass' module and the 'curses' module (I couldn't get either to work:( ). Unfortunatly I cannot show you how I used these as I scrapped the copy I made with each one in it but feel free to show me how I can (correctly) use these modules on the code above. What can I do? And also, would it work if I just changed the color of the i…
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85702878
has comment: http://stackoverflow.com/comment/85731801
has comment: http://stackoverflow.com/comment/85741485
score: -1
has comment: http://stackoverflow.com/comment/85702658
has comment: http://stackoverflow.com/comment/85731966
type: Question
has comment: http://stackoverflow.com/comment/85741171
has comment: http://stackoverflow.com/comment/85741468
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49370319
downvote count: 2
answer count: 1
has title: How can I hide the user input being typed into raw_input
has comment: http://stackoverflow.com/comment/85701487
tagged with: input
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85702937
has comment: http://stackoverflow.com/comment/85741128

http://stackoverflow.com/comment/85597092
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49297523
has text: wanted to send this i to my functian and then add it ass a favourite channel . Its just part of my code so wanted to add it as a favourite channel and ı will write __str__ function will output my favourite channels

http://stackoverflow.com/comment/85745275
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49372005
has text: Have you tried anything? Please include your code and describe what does not work.
type: Comment

http://stackoverflow.com/comment/85824562
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49394134
has text: If the shadows are not very sharp, the edge detection won't find them (you may need to adjust the parameters or do a threshold afterwards). For example, if an image is black in one side and white in the other, but there is a smooth transition, there will be no edges (edge detection should detect nothing), but background subtraction would see many differences if your robot turns.
type: Comment

http://stackoverflow.com/comment/85811983
type: AnswerComment
comment on: http://stackoverflow.com/a/49403928
has text: maybe you have more typo's in your code, or din't you post the code you are actually using?
score: 0
type: Comment

python-requests
tags question: http://stackoverflow.com/q/49413362
tags question: http://stackoverflow.com/q/49311281
tags question: http://stackoverflow.com/q/49434359
tags question: http://stackoverflow.com/q/49350136
tags question: http://stackoverflow.com/q/49318696
tags question: http://stackoverflow.com/q/49298254
tags question: http://stackoverflow.com/q/49332610
tags question: http://stackoverflow.com/q/49336477
tags question: http://stackoverflow.com/q/49333881
type: Tag
tags question: http://stackoverflow.com/q/49378547
tags question: http://stackoverflow.com/q/49353752
tags question: http://stackoverflow.com/q/49293306
tags question: http://stackoverflow.com/q/49407797
tags question: http://stackoverflow.com/q/49394007
tags question: http://stackoverflow.com/q/49310922
tags question: http://stackoverflow.com/q/49392258
tags question: http://stackoverflow.com/q/49286760
tags question: http://stackoverflow.com/q/49438948
tags question: http://stackoverflow.com/q/49366437
tags question: http://stackoverflow.com/q/49408762
tags question: http://stackoverflow.com/q/49319528
tags question: http://stackoverflow.com/q/49290704
tags question: http://stackoverflow.com/q/49298342
tag name: python-requests
tags question: http://stackoverflow.com/q/49327856
tags question: http://stackoverflow.com/q/49305436
tags question: http://stackoverflow.com/q/49353923
tags question: http://stackoverflow.com/q/49413151
tags question: http://stackoverflow.com/q/49431565
tags question: http://stackoverflow.com/q/49281249
tags question: http://stackoverflow.com/q/49429211
tags question: http://stackoverflow.com/q/49359903
tags question: http://stackoverflow.com/q/49415480
tags question: http://stackoverflow.com/q/49391687
tags question: http://stackoverflow.com/q/49368994
tags question: http://stackoverflow.com/q/49389812
tags question: http://stackoverflow.com/q/49332408
tags question: http://stackoverflow.com/q/49304323
tags question: http://stackoverflow.com/q/49349186
tags question: http://stackoverflow.com/q/49341670
tags question: http://stackoverflow.com/q/49343473
tags question: http://stackoverflow.com/q/49388892
tags question: http://stackoverflow.com/q/49311393
tags question: http://stackoverflow.com/q/49338811
tags question: http://stackoverflow.com/q/49356195
tags question: http://stackoverflow.com/q/49304356
tags question: http://stackoverflow.com/q/49283825
tags question: http://stackoverflow.com/q/49389930
tags question: http://stackoverflow.com/q/49404266
tags question: http://stackoverflow.com/q/49354262
tags question: http://stackoverflow.com/q/49432371

http://stackoverflow.com/comment/85824110
type: AnswerComment
score: 0
has text: @Jean-FrançoisFabre CPython uses an ArrayList with pointers, simply said. So a list implemented with an array, yes. Don't really know how to put it in a simple manner.
comment on: http://stackoverflow.com/a/49411167
type: Comment

http://stackoverflow.com/comment/85586741
has text: can you compare two files instead of images ? If it is the path you want to compare you can return the url of the image file and then compare it. Otherwise can you compare two files ? I haven't seen an image returning in the response any time.
comment on: http://stackoverflow.com/q/49291934
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49291048
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49333392
score: 1
tagged with: flask-socketio
answer count: 1
downvote count: 0
tagged with: snowflake-cloud-data-platform
has body: I receive the following errors when attempting to run a query against snowflake using the snowflake connector for python with flask_socketio and eventlet.. It appears to occur only when monkey patching eventlet. Any help with this is greatly appreciated. import snowflake.connector as scon from flask import Flask from flask_socketio import SocketIO import eventlet eventlet.monkey_patch() def query(): # Gets the version ctx = scon.connect( user='xxx', password='xxxxxxxx', account='xxxxxx', ) cs = ctx.cursor() try: cs.execute("SELECT current_version()") one = cs.fetchone() return 'Snowflake version={}'.format(one[0]) finally: cs.close() app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def query_route(): return query() socketio.run(app,debug=False, host='localhost', port=5000) Error Received: Traceback (most recent call last): File "/home/chad/miniconda2/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/home/chad/miniconda2/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/home/chad/miniconda2/lib/python2.7/multiprocessing/pool.py", line 327, in _handle_workers while thread._state == RUN or (pool._cache and thread._state != TERMINATE): AttributeError: '_MainThread' object has no attribute '_state' Exception in thread Thread-6: Traceback (most recent call last): File "/home/chad/miniconda2/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/home/chad/miniconda2/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/home/chad/miniconda2/lib/python2.7/multiprocessing/pool.py", line 363, in _handle_tasks cache[job]._set(ind + 1, (False, ex)) TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48218396
upvote count: 1
tagged with: python
has title: Multiprocessing error Snowflake Python Connector with flask_socketio
accepted answer: http://stackoverflow.com/a/49333392

http://stackoverflow.com/comment/85650615
type: Comment
comment on: http://stackoverflow.com/q/49324358
type: QuestionComment
has text: your problem is not clear for me. can you give us the resulting `with_count` and `without_count` using your simple example ?
score: 0

http://stackoverflow.com/comment/85689600
has text: This gives me an error: list index out of range for some reason
type: Comment
comment on: http://stackoverflow.com/a/49344619
score: 0
type: AnswerComment

http://stackoverflow.com/a/49371280
answers question: http://stackoverflow.com/q/49371147
type: Answer
has comment: http://stackoverflow.com/comment/85743974
accepted answer of: http://stackoverflow.com/q/49371147
has body: I am working on getting the first image (default placeholder) and the button to appear when I run the program. I am currently getting an empty window with no widgets inside of it. What part of code am I missing, or what is not written properly? You never call pack, place, or grid on the instance of userDisplay. Since it is an instance of Frame, it will only be visible once it has been added to the screen with one of those geometry managers. Assuming that you want userDisplay to fill the entire window, add this inside of main: interface.pack(fill="both", expand=True)
has comment: http://stackoverflow.com/comment/85744095
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49312403
score: -2
has comment: http://stackoverflow.com/comment/85626620
tagged with: python
linked to: http://stackoverflow.com/q/6193498
tagged with: ipython
accepted answer: http://stackoverflow.com/a/49312450
type: AnsweredQuestion
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/85627526
has title: Python - Get largest number from a list of numbers in a file
has comment: http://stackoverflow.com/comment/85626626
has body: I apologize but I searched and could not find an existing question/answer that solved this. Simply put, I just need to take a list of numbers in a file and grab the largest number.I would typically use bash but i have a Python requirement. I know how to open a file for reading and output the contents of the file but I can't get it to process the for loop output. Thank you in advance. Here's the bash equivalent of what i need to do in python: chrisk@kihei:~$ cat foo 214101721792 214101675361 214101684152 214101743134 214101718688 214101731297 214101715541 214101743273 214101722035 214101703116 214101696928 214101687776 chrisk@kihei:~$ sort foo | tail -1 214101743273 chrisk@kihei:~$
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85626740
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49312450
has comment: http://stackoverflow.com/comment/85627582
has comment: http://stackoverflow.com/comment/85626839

http://stackoverflow.com/comment/85588003
comment on: http://stackoverflow.com/q/49292064
type: QuestionComment
score: 0
has text: The content is different.
type: Comment

http://stackoverflow.com/q/49285277
type: Question
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has body: I am a little bit stuck on a project that I want to complete if someone could help me it would be great, the project is creating a graph for the sense hat temperature sensor with matplotlib. What I can do is create a graph with the following code; import matplotlib.pyplot as plt plt.rcParams['toolbar'] = 'None' plt.plot([], [], 'b-')#Plots go inside the square brackets plt.axis([0, 24, -5, 30]) plt.ylabel('Tempreture')#Label of the Y axis 'ylabel' plt.xlabel('Time (Hours)')#Label of the X axis 'xlabel' plt.show()#Displays the graph And I can also collect a large range of tempreture with this simple loop; from sense_hat import SenseHat temperature = [] while True: temp = sense.get_temperature() temp1 = round(temp, 2) temperature.append(temp1) But my problem is putting these two pieces of code together as I have tried to insert my list tempreture unto the y axis however it came up with the error ValueError: x and y must have the same first dimension so if anyone could help me to create a graph for my sense hat tempreture sensor I would be greatful.
has title: Drawing a graph for the tempreture sensor with sense hat and matplotlib module
has comment: http://stackoverflow.com/comment/85573463
tagged with: valueerror
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/85573707
answer count: 0
tagged with: loops

http://stackoverflow.com/a/49352112
has comment: http://stackoverflow.com/comment/85704944
has body: you could achieve it using the code below: def multiply_perimeter(L: int, multiplier: int) -&gt; None: size = len(L) if size &gt; 0: # multiply only the first and last element in the lists L[1]...L[size-2] for _ in range(1, size-1): L[_][0] *= multiplier L[_][-1] *= multiplier # multiply first and last line elements by multiplier L[0] = [item*multiplier for item in L[-1]] L[-1] = [item*multiplier for item in L[-1]]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49352018

http://stackoverflow.com/q/49319808
tagged with: python
has comment: http://stackoverflow.com/comment/85657704
tagged with: conda
type: AnsweredQuestion
has title: install package from tar.gz in Anaconda
tagged with: anaconda
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/85652737
upvote count: 1
has comment: http://stackoverflow.com/comment/85654357
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85657045
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49331347
accepted answer: http://stackoverflow.com/a/49331347
has comment: http://stackoverflow.com/comment/85657198
has comment: http://stackoverflow.com/comment/85662136
has comment: http://stackoverflow.com/comment/85655981
score: -2
has body: I got *.tar.gz file and how to install that package in conda virtual environment ? I've tried the following: $ source activate env01 (env01)$ conda install /installers/anaconda/cassandra-driver-3.11.0.tar.gz Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - cassandra-driver-3.11.0.tar.gz Current channels: ... If I use pip install, it wasn't stored in environment directory. See below: (env01)$ pip install /installers/anaconda/cassandra-driver-3.11.0.tar.gz Processing /installers/anaconda/cassandra-driver-3.11.0.tar.gz Requirement already satisfied: six&gt;=1.9 in /dataplatform/software/anaconda/lib/python3.6/site-packages (from cassandra-driver==3.11.0) Building wheels for collected packages: cassandra-driver Running setup.py bdist_wheel for cassandra-driver ... done Stored in directory: /home/linknet/.cache/pip/wheels/e9/ff/17/ebfd2f04dfac5206db48c1520c6f669ec225ddc2c192aada17 Successfully built cassandra-driver Installing collected packages: cassandra-driver Successfully installed cassandra-driver-3.11.0 My conda env01 directory is: /dataplatform/software/anaconda/envs/env01

http://stackoverflow.com/a/63005557
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49400426
score: 1
has body: In addition to @sean.hudson's answer I was trying to figure out how to override the child serializer validation. It might be possible to "skip" or more accurately ignore children serializer validation errors, by overriding to_internal_value of the ParentSerialzer: class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) def to_internal_value(self, *args, **kwargs): try: # runs the child serializers return super().to_internal_value(*args, **kwargs) except ValidationError as e: # fails, and then overrides the child errors with the parent error return self.validate(self.initial_data) def validate(self, attrs): errors = {} errors['custom_override_error'] = 'this ignores and overrides the children serializer errors' if len(errors): raise ValidationError(errors) return attrs class Meta: model = Parent
type: Answer

http://stackoverflow.com/comment/85855695
type: AnswerComment
comment on: http://stackoverflow.com/a/49427178
score: 0
has text: yes exactly, i would like to acces as you said, but dinamically
type: Comment

http://stackoverflow.com/comment/85736633
score: 0
type: Comment
type: QuestionComment
has text: Have you looked at `drop_duplicates`?
comment on: http://stackoverflow.com/q/49367296

http://stackoverflow.com/comment/85811844
comment on: http://stackoverflow.com/q/49404275
type: QuestionComment
score: 0
has text: Please go through this link. Check if this helps you : https://stackoverflow.com/questions/45947375/why-does-starting-a-streaming-query-lead-to-exitcodeexception-exitcode-1073741
type: Comment

http://stackoverflow.com/comment/85675735
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49336649
has text: The pipeline operation may not work the way you expect it to, since it's designed to vectorize text features, but you're also contemplating adding pre-vectorized features features before it hits the pipeline. May be worth running some cross val without the pipeline to verify it outperforms just the tweets data.
score: 0

http://stackoverflow.com/comment/85801120
type: Comment
has text: I would argue exactly the opposite, because if you use many regex implementations (not just Python's) there is no way to know really whether backslashes do what you want in a character range.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49399137

http://stackoverflow.com/comment/85697375
comment on: http://stackoverflow.com/a/49346462
type: Comment
score: 0
type: AnswerComment
has text: Works Perfectly Fine! Thanks alot. Just last thing. it creates this blank file. http://prntscr.com/isubbc can it be avoided?

http://stackoverflow.com/comment/85751468
has text: Of course I know, but it's not the problem. In _with_ context the problem still exists.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49375134
score: 0

http://stackoverflow.com/comment/85712661
has text: What if I want any particular value, let's say the third value from the **difference** column? Can I use this value = Difference[3]
comment on: http://stackoverflow.com/a/49356283
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49353537
type: Question
tagged with: healpy
type: UnansweredQuestion
tagged with: python
has title: How to draw blank map using Healpy
has body: I am new in it, and cant fully understand the manual. I am running test code, but I want to make blank map, without this gradient colors. I think it's not hard for those who know. Help me please.Here what i got import numpy as np import healpy as hp import pylab as pl import matplotlib as plt NSIDE = 32 m = np.arange(hp.nside2npix(NSIDE)) hp.mollview(m) pl.show()
score: 0
has answer: http://stackoverflow.com/a/49361007
answer count: 1

http://stackoverflow.com/a/63804020
has body: Definitely took me a while to look for where the template is, but here it is, link. I believe this includes all the CSS for notebook cell outputs, so you just need the table related parts (table, thead, tbody, th, etc) and tweak them to your liking. You still need to turn it in python, but to illustrate it works, here's the raw HTML 0 first second bar one -0.466253 two -0.579658 baz one 1.868159 two 0.392282 foo one -2.427858 two -0.813941 qux one 0.110564 two 0.834701
has comment: http://stackoverflow.com/comment/113662323
downvote count: 0
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/49324569
type: Answer

http://stackoverflow.com/comment/85784561
comment on: http://stackoverflow.com/q/49390202
score: 0
type: Comment
type: QuestionComment
has text: so what's stopping you from applying `expand` for bam's `{path}` in `rule bamdiagnostics` similar to bai's `{path}`. That's what the error obtained is referring to.

http://stackoverflow.com/a/49350352
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85700448
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49350245
type: Answer
has body: I am soory, noob's mistake, first project in python. I totaly forgot that in cmd I should include text using ' " ' whenever it contains spaces. wrong way: python re-encoder.py ['1','11','11 1'] ['cpp','h'] 'utf-8' 500 right way: python re-encoder.py "['1', '1 1', '11 1']" "['cpp','h']" 'utf-8' 500 to call the script in cmd
answers question: http://stackoverflow.com/q/49350245
downvote count: 0
has comment: http://stackoverflow.com/comment/85700394

http://stackoverflow.com/comment/85783627
score: 0
comment on: http://stackoverflow.com/q/49377836
type: Comment
has text: a local wont be initialised when on function entry. when are you evaluating the local?? . An assign to the local will only be effective after its initial initialisation has occured within the function scope
type: QuestionComment

http://stackoverflow.com/comment/85702610
score: 0
type: AnswerComment
has text: Thanks @TimD, atru's solution is good but atru's solution assumes that number of pool processes and numbers for which you need to do calculation can be same. What if you can only pool 5 processes and you have to do calculations for 100 numbers(more than 5)? You have to write extra code to zip the numbers to output filename.
type: Comment
comment on: http://stackoverflow.com/a/49347823

http://stackoverflow.com/comment/85616655
score: 0
has text: @DanielRoseman updated my post and added wsgi.py
comment on: http://stackoverflow.com/q/49306996
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85582980
type: QuestionComment
has text: Would `pd.set_option('float_format',lambda x: "%.6f" % x)` work? https://github.com/pandas-dev/pandas/issues/6842
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49289812

http://stackoverflow.com/comment/85679910
type: Comment
has text: oh, cuz i have a lot of those lists and those are defined by users. I want to keep them more organized so I used a loop to create l_all.
type: AnswerComment
comment on: http://stackoverflow.com/a/49339776
score: 0

sqlalchemy
tags question: http://stackoverflow.com/q/49414667
tags question: http://stackoverflow.com/q/49314573
tags question: http://stackoverflow.com/q/49372413
tags question: http://stackoverflow.com/q/49390553
tags question: http://stackoverflow.com/q/49385744
tags question: http://stackoverflow.com/q/49333656
tags question: http://stackoverflow.com/q/49409691
tags question: http://stackoverflow.com/q/49332759
tags question: http://stackoverflow.com/q/49382913
tags question: http://stackoverflow.com/q/49288255
tags question: http://stackoverflow.com/q/49417784
tags question: http://stackoverflow.com/q/49413062
tags question: http://stackoverflow.com/q/49425985
tags question: http://stackoverflow.com/q/49395490
tags question: http://stackoverflow.com/q/49391557
tags question: http://stackoverflow.com/q/49391192
tags question: http://stackoverflow.com/q/49293712
tags question: http://stackoverflow.com/q/49430570
tags question: http://stackoverflow.com/q/49409592
tags question: http://stackoverflow.com/q/49357971
tags question: http://stackoverflow.com/q/49305293
tags question: http://stackoverflow.com/q/49394150
tags question: http://stackoverflow.com/q/49388628
tags question: http://stackoverflow.com/q/49324388
tags question: http://stackoverflow.com/q/49438529
tags question: http://stackoverflow.com/q/49415023
tags question: http://stackoverflow.com/q/49358868
tags question: http://stackoverflow.com/q/49424261
tags question: http://stackoverflow.com/q/49362017
tags question: http://stackoverflow.com/q/49333279
tags question: http://stackoverflow.com/q/49375744
tags question: http://stackoverflow.com/q/49340778
tags question: http://stackoverflow.com/q/49383985
tags question: http://stackoverflow.com/q/49360525
tags question: http://stackoverflow.com/q/49365147
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/49412460
tags question: http://stackoverflow.com/q/49288254
type: Tag

http://stackoverflow.com/q/49290046
favorite count: 0
has answer: http://stackoverflow.com/a/49290175
type: Question
tagged with: ord
has body: I have a table containing: table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] and I want to convert the words in each list in table into its numeric representation (ASCII). I've tried: movie = 'THEINCREDIBLES' h = 0 for c in movie: h = h + ord(c) print(h) and it works but if I were to use a list of lists as table above, I'm getting an error saying ord expected string of length 1 table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] h = 0 for c in table: h = h + ord(c) print(h) edit for @Sphinx I've done: table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']] h = 0 ordlist = [] for row in table: for c in row[1]: h = h + ord(c) ordlist.append(row[0]) oralist.append(h) h = 0 print(ordlist) and my output is now: [1,1029,2,532] which is almost close to what I've wanted which is: [[1,1029],[2,532]] how do i enclose each ordinal representation into individual list within a list as above? Do i introduce a new list for this purpose?
has answer: http://stackoverflow.com/a/49290080
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49290148
tagged with: python
has comment: http://stackoverflow.com/comment/85583793
score: 0
has answer: http://stackoverflow.com/a/49290100
has title: Ordinal representation of nested strings
has comment: http://stackoverflow.com/comment/85583892
has comment: http://stackoverflow.com/comment/85583903
has answer: http://stackoverflow.com/a/49290126
has comment: http://stackoverflow.com/comment/85583848
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/49347654
has comment: http://stackoverflow.com/comment/85697308
type: Answer
accepted answer of: http://stackoverflow.com/q/49347266
has comment: http://stackoverflow.com/comment/85700500
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49347266
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85701588
has body: There are several ways you can handle this, but the cleanest In my opinion is to create an abstract BaseProject model and make that the parent class of the Project model and a DemoProject model. class BaseProject(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') applicant = models.ManyToManyField(MyUser, related_name="applicant") created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs={'pk1': self.pk}) Now create the DemoProject as a child of BaseProject class DemoProject(BaseProject): project_hr_admin = models.ManyToManyField('registration.MyUser', blank=True, null=True) Then you can update your registration code to use the new model. def registerManager(request): registered = False if request.method == "POST": Manager_form = ManagerForm(data=request.POST) if Manager_form.is_valid(): user = Manager_form.save() user.set_password(user.password) user.is_manager = True user.save() registered = True login(request, user) demo_project = DemoProject.objects.get(name="Demo Project") request.user.project_set.add(demoProject) return HttpResponseRedirect(reverse('website:hr_index')) else: print("Error!") else: Manager_form = ManagerForm() return render(request, 'HR_registration_form.html', {'Manager_form': Manager_form, 'registered': registered}) This way, you've seperated the two entities and managed to preserve the behaviour/identitiy of the DemoProject (A DemoProject is still a Project). This also means you can modify the main Project model without affecting the DemoProject model. Your main Project model should look like this now class Project(BaseProject): # any custom stuff that's unique to a project pass
has comment: http://stackoverflow.com/comment/85697533

http://stackoverflow.com/a/49351912
answers question: http://stackoverflow.com/q/49351729
has body: A Python program should have the following skeleton: # import statements # ... # global constants # ... # functions # ... def main(): # TODO: the main task: parse command line arguments, etc pass if __name__ == "__main__": main() Now, your task is to implement date validation. Think of the big steps, and create some more functions accordingly: def main(): year, month, day = inputYearMonthDay() print(isValidYearMonthDay(year, month, day)) You already have the content of inputYearMonthDay, it could be something like this: def inputYearMonthDay(): print("This program will check if a date is correct and output what day of the week it was.") dayStr = input("Please input the day&gt;") monthStr = input("Please input the month in number format&gt;") yearStr = input("Please input the year, it must be after 1900&gt;") return int(year), int(month), int(day) What would be the big steps of isValidYearMonthDay? def isValidYearMonthDay(year, month, day): if not validateSaneYear(year) or not validateSaneMonth(month) or not validateSaneDay(day): return False # TODO validate days per month, with special treatment for february in leap years return False validateSaneYear could be: def validateSaneYear(year): if 1900 &lt;= year &lt; 2018: return True print("Invalid year: {}; expected to be in the range [1900,2018)".format(year)) return False validateSaneMonth and validateSaneDay could be implemented similarly. And so on. If you break down the problem to its big steps, and each step to its big own big steps, you can reduce the big problem to tiny sub-problems that can be easily solved and tested individually, building up to a complete program that does something interesting. Good luck!
type: Answer
score: 0

http://stackoverflow.com/comment/85758529
type: Comment
has text: Many thanks @Jon Clements and Doodle, in used the following: CT = C.T CT_unique = CT.drop_duplicates(subset=[CT.columns[0]], keep = 'first') . You guys helped me loads, I implemented the changes successfully. Super happy with your small (but potent!) advice.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49367923

http://stackoverflow.com/comment/85869706
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49433916
has text: This solution is not complete.

http://stackoverflow.com/a/49363800
score: 0
has comment: http://stackoverflow.com/comment/85728226
has comment: http://stackoverflow.com/comment/85729278
has comment: http://stackoverflow.com/comment/85728868
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49363631
has body: Just suggesting another approach: Have you tried with list comprehension + groupy from itertools? from itertools import groupby print([(key, len(list(group))) for key, group in groupby([x.split(' ')[0] for x in data.split('\n')])]) # where [x.split(' ')[0] for x in data.split('\n')] generates a list of all starting number # and groupy counts them Or if you want that exact output: from itertools import groupby mylist = [(key, len(list(group))) for key, group in groupby([x.split(' ')[0] for x in data.split('\n')])] for key, repetition in mylist: print(key, repetition)
has comment: http://stackoverflow.com/comment/85728902
accepted answer of: http://stackoverflow.com/q/49363631
has comment: http://stackoverflow.com/comment/85728358
type: Answer

http://stackoverflow.com/q/49419603
tagged with: python
has answer: http://stackoverflow.com/a/49419671
accepted answer: http://stackoverflow.com/a/49419671
has comment: http://stackoverflow.com/comment/85840764
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49419634
possible better answer: http://stackoverflow.com/a/49419634
linked to: http://stackoverflow.com/q/5424716
favorite count: 0
type: Question
has body: I am in the process of creating a basic budget program in Python 3. It needs to create a series of three people and give them a salary, 2 expenses, and their left over cash at the end of the week. You will also be comparing their left over expenses to an amount of money they need to save every week. I believe I have it all finished except for this problem whenever I run the program, I get the following message: Traceback (most recent call last): File "/Users/----/Desktop/BudgetProgramTest.py", line 42, in personOneLeftOver = personOneSalary - personOneExpenses TypeError: unsupported operand type(s) for -: 'str' and 'tuple' How can I solve this error? What would be the correct way to code this? It would be easier to understand with the original code for my program: &lt;prev&gt; # Ask for each person's name personOne = input("What is your name?") personTwo = input("What is your name?") personThree = input("What is your name?") # Ask for each person's weekly salary personOneSalary = input("What is your weekly salary?") personTwoSalary = input("What is your weekly salary?") personThreeSalary = input("What is your weekly salary?") # Ask for personOne's expenditures personOneGas = input("How much do you spend on gas per week?") personOneGroc = input("How much do you spend on groceries per week?") personOneFast = input("How much do you spend on fast food per week?") personOneHob = input("How much do you spend on hobbies per week?") personOneExpenses = personOneGas, personOneGroc, personOneFast, personOneHob # Ask for personTwo's expenditures personTwoGas = input("How much do you spend on gas per week?") personTwoGroc = input("How much do you spend on groceries per week?") personTwoFast = input("How much do you spend on fast food per week?") personTwoHob = input("How much do you spend on hobbies per week?") personTwoExpenses = personTwoGas, personTwoGroc, personTwoFast, personTwoHob # Ask for personThree's expenditures personThreeGas = input("How much do you spend on gas pe…
tagged with: python-3.x
has title: Beginner Budget Program Error In Python

http://stackoverflow.com/comment/85704118
has text: @AndyMorgan And you know that you're sending it correctly, and that you're not reading a MIME envelope rather than its contents, and so on, because…? You've tried writing the result to a file named `image.jpg`; can you open that file in xv or Paint or whatever?
comment on: http://stackoverflow.com/q/49345303
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49418271
type: Answer
downvote count: 1
has body: You missed a ' line 12. It cause the SyntaxError. This should correct the error. import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime import matplotlib.dates as mdates df = pd.read_csv('rio_data.csv', delimiter=',') print (df.head(10)) d = [] for dat in df.date: # print (dat) d.append(datetime.strptime(df['date'], '%Y-%m-%d')) days = dates.DayLocator() datemin = datetime(2011, 1, 1) datemax = datetime(2012, 4, 20) fig = plt.figure() ax = fig.add_subplot(111) ax.xaxis.set_major_locator(days) ax.set_xlim(datemin, datemax) ax.set_ylabel('Count values')
has comment: http://stackoverflow.com/comment/85838347
score: 3
has comment: http://stackoverflow.com/comment/85838365
answers question: http://stackoverflow.com/q/49418248
upvote count: 4
has comment: http://stackoverflow.com/comment/85838285

http://stackoverflow.com/a/57882222
has body: The command listed earlier: conda install -c cogsci pygame will install pygame 1.9.2a0 which is an older package. I was able to find 1.9.5 at this channel: conda install -c delichon pygame But, since that version might be old by the time you read this, you might be better off going to https://anaconda.org/anaconda/repo and searching for pygame there. That way you'll be able to see which versions are available on which channel (like cogsci or delichon).
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49348949
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85600794
has text: hi, I get this error AttributeError: ("'GeoSeries' object has no attribute '_geom'", u'occurred at index 0'). It seems he does not read the point_data as a geometry.
score: 0
comment on: http://stackoverflow.com/q/49298505
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49312048
score: 0
has answer: http://stackoverflow.com/a/49312107
has comment: http://stackoverflow.com/comment/85625947
upvote count: 1
answer count: 1
has title: Error: 'int' is not subscriptable [Python]
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85625920
type: Question
has comment: http://stackoverflow.com/comment/85625956
has comment: http://stackoverflow.com/comment/85625910
has body: I'm writing a text adventure game as an exercise. I'm new to Python. I'm trying to save enemy damage in a dictionary as a range as so: giant_rat = {'name':'Giant Rat', 'Health':15, 'attack':random.randrange(1, 4)} player = {'health':20, 'weapon':None, 'holding':None} So what I want to do later is access this range and pick a random number in that range and subtract it from the player's health. atkDmg = giant_rat['attack'] player['health'] -= atkDmg This gives me the error. Shouldn't this work? atkDmg is an integer and so is player['health'] so I'm not sure why it's giving me an error? Also, if there's a smarter way to implement this then I'm open to suggestions. I want to write the program so that all i have to do is add a new enemy (instead of just putting in the range I want in the battle function loop.) I hope this makes sense. Thanks! EDIT: Okay so here's the actual code. I thought the code above was equivalent to my code but I guess it isn't: # Weapon Stats weapon = {'Bone':(4, 9), 'None':random.randrange(2, 5)} # Player Stats player = {'weapon':'None', 'Health':20, 'Holding':'None'} # enemy giant_rat = {'name':'Giant Rat', 'Health':15, 'attack':(1, 4)} And then this is the code that gives me the error: atkDmg = weapon[player['weapon']] enemy['Health'] -= atkDmg def battleLoop(): enemyList = [giant_rat, giant_spider] enemy = random.randrange(2) stdio.writeln('Suddenly a ' + enemyList[enemy]['name'] + ' appears!') attackLoop(enemy) UPDATE 2: I've figured it out, actually. In the code above I forgot to assign a value of enemyList to enemy. I think that should fix my problem. Thanks for your help!
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85804034
has text: What you have in b) is an optimization, but it's not a huge one. How long is the inner loop when N is 0? When N is 1? When it's len(songs)/2? When it's len(songs)-1? Average them all. Is the answer a small constant times 1, or, log N, or sqrt N, or N, or something else? And meanwhile, how many steps are in your outer loop? The only way you could have log N total time is if one loop were O(1) and the other were O(log N).
type: Comment
comment on: http://stackoverflow.com/q/49400897
type: QuestionComment
score: 0

http://stackoverflow.com/a/49608941
upvote count: 1
has comment: http://stackoverflow.com/comment/86229648
downvote count: 1
has comment: http://stackoverflow.com/comment/86228771
has comment: http://stackoverflow.com/comment/86228639
type: Answer
has comment: http://stackoverflow.com/comment/86229077
has comment: http://stackoverflow.com/comment/86227213
has comment: http://stackoverflow.com/comment/86228920
score: 0
has comment: http://stackoverflow.com/comment/86230492
has body: Django already allows for a Group, User permissions which we can customize for our needs. Create the groups you need (form the admin panel for example, or by following this SO post.): 'country-admin-group` 'state-admin-group' 'user-group' Create custom permissions for your user groups and add them accordingly: from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from your_app_name.models import CustomUserModel ct = ContentType.objects.get_for_model(CustomUserModel) permission_sl = Permission.objects.create( codename='can_add_sl_user', name='Can add SL user', content_type=ct ) permission_user = Permission.objects.create( codename='can_add_simple_user', name='Can add simple user', content_type=ct ) ... cl_group = Groups.get(name='country-admin-group') cl_group.permissions.add(permission_sl) cl_group,permissions.add(permission_user) sl_group = Groups.get(name='state-admin-group') sl_group,permissions.add(permission_user) ... Create views (and the corresponding urls) for each type of user. Personally I prefer to use class based views when applicable. We will control the access to each view with the method_decorator and permission_required decorators: from django.http import HttpResponse from django.views import View class CountryAdminView(View): @login_required def list(self, request): """ Can access only users created by him """ content = Users.objects.filter(parent_id=request.user.id) return HttpResponse(content) @method_decorator(@permission_required('your_app_name.can_add_sl_user')) def create(self, request): ... Logic for creating an SL admin user. ... Keep in mind that the above is a simplified example to set you in the path to the solution. As @BurhanKhalid points out, you can skip a part of the above by using django-guardian. You can also use django-role-permissions to define per user roles and add permissions to those roles.
has comment: http://stackoverflow.com/comment/86228237
has comment: http://stackoverflow.com/comment/86227199
answers question: http://stackoverflow.com/q/49300215

http://stackoverflow.com/comment/85881086
comment on: http://stackoverflow.com/q/49436063
score: 1
type: Comment
type: QuestionComment
has text: "How to start" questions really are too broad here. If you can cut your question down to something smaller, that is ideal. Some hints on how to ask questions [are here](https://stackoverflow.com/help/how-to-ask).

http://stackoverflow.com/comment/85715783
type: Comment
type: QuestionComment
has text: If you want any more clarification on question please ask
comment on: http://stackoverflow.com/q/49357893
score: 0

http://stackoverflow.com/q/49292397
tagged with: tkinter-entry
has body: Really simple code, but not working using tkinder in Python. This code has been copied just as seen in a video tutorial, so I think it could be any config: from tkinter import* root=Tk() miFrame=Frame(root, width=500, height=400) miFrame=pack() Label(miFrame, text="Hola alumnos de Python", fg="red", font=("Comic Sans MS", 18)).place(x=100, y=200) root.mainloop() The error: Traceback (most recent call last): File "Prueba2.py", line 7, in miFrame=pack() NameError: name 'pack' is not defined
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49292527
tagged with: python-3.x
tagged with: tkinter
answer count: 2
has answer: http://stackoverflow.com/a/49292527
has answer: http://stackoverflow.com/a/49292457
accepted answer: http://stackoverflow.com/a/49292457
tagged with: python
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
has title: Python Tkinter not working. Name error

http://stackoverflow.com/q/49291664
score: 1
has title: check value of a tensor in tensorflow
downvote count: 0
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am trying to check a value of tensor : ytrue = y_true[0][0] if ytrue[index] == 1: # which to check if the label is a particular value do something here, y_true is a tensor corresponding to a model with 4 outputs(say) y_true[0th out put][output corresponding to 0th data point] I face the following Value Error: Index out of range using input dim 0; input has only 0 dims for 'loss/dense_5_loss/strided_slice_2' (op: 'StridedSlice') with input shapes: [], [1], [1], [1] and with computed input tensors: input[3] = &lt;1>.
answer count: 0

http://stackoverflow.com/q/49343231
has comment: http://stackoverflow.com/comment/85686746
tagged with: python
has body: I have the following code that generates numpy list, writes it, and later reads it back as a numpy list again: filepath = 'vectors.txt' rows = 10 dim = 5 V = np.random.choice(np.array([0, 1], dtype=np.uint8), size=(rows, dim)) M = np.unique(V.view(V.dtype.descr * dim)) Matrix = M.view(V.dtype).reshape(-1, dim) with open(filepath, 'w') as f: for i in Matrix: f.write("{}\n".format(i)) f.close() with open(filepath, "r") as f: contents = [] for line in f: l = np.asarray(line.strip()) contents.append(l) contents = np.asarray(contents) print(contents) The output looks like this: ['[0 0 0 1 0]' '[0 0 1 0 1]' '[0 0 1 1 1]' '[0 1 0 1 1]' '[0 1 1 0 0]' '[0 1 1 0 1]' '[0 1 1 1 0]' '[1 1 1 0 0]' '[1 1 1 0 1]'] How can I remove single quotation mark around each vector so that it become a numpy vector? In other word, instead of '[0 0 0 1 0]', it must be [0 0 0 1 0]. I tried using l = np.asarray(line.strip()) but it seems it has no effect when appending. Note that I do looping while read and write on purpose. Thank you
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49343311
has comment: http://stackoverflow.com/comment/85686736
has title: Reading numpy list of vectors from file causes a change of vectors to be string
has comment: http://stackoverflow.com/comment/85686777
has comment: http://stackoverflow.com/comment/85686827
answer count: 1
accepted answer: http://stackoverflow.com/a/49343311
type: Question
tagged with: numpy
tagged with: python-3.x

http://stackoverflow.com/a/49411275
answers question: http://stackoverflow.com/q/49410785
has comment: http://stackoverflow.com/comment/85832489
has body: Replace this part of code Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData']) with this Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData'])) You need to insert your data in the treeview as a tuple so i converted your dic value to tuple Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData'])) full code from tkinter import * from collections import OrderedDict from tkinter import filedialog, ttk GuiWindow = Tk() TestDict = OrderedDict() TestDict["MsgID"] = 1 TestDict["OtherData"] = 2 Errortree = ttk.Treeview(GuiWindow,columns=('Message ID', 'Other Data'),show="headings") Errortree.heading('#1', text='Message ID') Errortree.heading('#2', text='Other Data') Errortree.column('#1', stretch=YES) Errortree.column('#2', stretch=YES) def TreeInsert(): print(TestDict) #Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData']) Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData'])) scanvar = BooleanVar() scanbtn = Checkbutton( GuiWindow,text="scan",variable=scanvar, command=TreeInsert,indicatoron=0) Errortree.grid(row=0, columnspan=5, sticky='nsew') scanbtn.grid(row=1, column=0) GuiWindow.geometry('{}x{}'.format(400, 300)) GuiWindow.mainloop()
has comment: http://stackoverflow.com/comment/85826492
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49410785
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49427446
has comment: http://stackoverflow.com/comment/85856008
score: -2
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/49427495
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/18072759
has title: List comprenhension help python
favorite count: 0
type: Question
has body: I am trying to understand better the list comprehension: I have the following code: deck = [] for rank in ranks: for suit in suits: deck.append(('%s%s')%(rank, suit)) How can I transform in list comprehension? And is it more pythonic to have as list comprehension or not?
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/18072759
type: UnansweredQuestion

http://stackoverflow.com/a/49427920
has body: You should be able to get what you need with: f, ax = plt.subplots(figsize=(8,8)) ax.plot_date(x = myDates, y = myValues) ax.set_xticklabels(myDates, rotation=45, size=20) ax.set_ylabel('Cumulative # of wallet addresses') plt.show() Just change the size and rotation set in line: ax.set_xticklabels() EDIT: f, ax = plt.subplots(figsize=(20,10)) ax.plot_date(x=myDates, y=myValues) ax.set_ylabel('Cumulative # of wallet addresses') ax.yaxis.set_tick_params(labelsize=14) # Sets size of the y ticklabels ax.set_xticks(myDates) # Sets the positions of the ticks ax.set_xticklabels(myDates, rotation=45, size=20, ha="right") # Sets a label on each tick ax.xaxis.set_tick_params(length=12) # Sets length of the ticks # Hides ticks and labels according to their position (here 1 in 7 is shown) x = 0 for label, tick in zip(ax.xaxis.get_ticklabels(), ax.xaxis.majorTicks): if x % 7 != 0 : label.set_visible(False) tick.set_visible(False) x += 1 plt.show() Changing the modulo value in if x % 7 != 0 modifies the number of ticks you will show on the plot. Bigger value for fewer ticks and labels. It is important to set ha="right" otherwise the rotation makes it uncomfortable to see which label goes with which tick.
has comment: http://stackoverflow.com/comment/85857410
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49427683
type: Answer

http://stackoverflow.com/q/49354699
has answer: http://stackoverflow.com/a/49356426
has answer: http://stackoverflow.com/a/49354774
favorite count: 0
type: Question
has title: Modify a list within a list, using map and lambda through list comprehension
has body: Hi everyone I am new to Python and have been trying out how to create lists within lists containing multiples from 1 to 4, with each of them containing the same number of multiples as the number they are being multiplied with. In particular, applying the use of lambda and map function. [[0], [0, 2], [0, 3, 6], [0, 4, 8, 12], [0, 5, 10, 15, 20]] I have tried several ways and this is the code that I am currently working on, but I have received NameError: name 'x' is not defined error. I will really be grateful if someone can point out the mistakes that I have overlooked! list_1 = [[0], [0,1], [0,1,2]] result = list(map(lambda x, i ,j ,k: x[i][j] * k, list_1, range(3),items in x[i], range(1,3))) print(result)
has answer: http://stackoverflow.com/a/49354792
has comment: http://stackoverflow.com/comment/85709837
tagged with: python
tagged with: list-comprehension
answer count: 4
has answer: http://stackoverflow.com/a/49354806
tagged with: python-3.x
tagged with: list
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/85723918
has text: @dreamerboy there are also another options to compute this see [Building a logarithm function in C without using float type](https://stackoverflow.com/a/42108287/2521214)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49353928
type: QuestionComment

http://stackoverflow.com/q/49437057
type: Question
accepted answer: http://stackoverflow.com/a/49437741
has title: extracting dataframe out of json file with same key values
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49437587
possible better answer: http://stackoverflow.com/a/49437587
tagged with: dataframe
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/49515298
has body: i have a json file(given below), i need to extract a dataframe with column names as value of "jive_label" inside profile[] and values as its values, expected output given below. also i have given the sample code where i try to print just one column, but that code clearly doesnt work. import requests import pandas as pd import numpy as np from pandas.io.json import json_normalize import sys import json r=requests.get(url,data=payload,headers=headers,params=querystring,verify=False) json_data=r.json() df=pd.DataFrame([]) for i in json_data.get('profile',[]): if i.get('jive_label')=='Title': dfDict={'Title': i.get('value') } df=df.append(pd.DataFrame(dfDICT,index=[0]),ignore_index=True) print(df.head())* { "jive": { "enabled": true, "external": false, "federated": true, "lastProfileUpdate": "2017-08-14T17:07:35.491+0000", "level": { "description": "Level 1", "imageURI": "https:", "name": "Newbie", "points": 0 }, "locale": "en_US", "externalContributor": false, "profile": [ { "jive_label": "Title", "value": "Analyst", "jive_displayOrder": 0, "jive_showSummaryLabel": false }, { "jive_label": "COMPANY ID", "value": "333333", "jive_displayOrder": 5, "jive_showSummaryLabel": false }, { "jive_label": "Department", "value": "46152", "jive_displayOrder": 6, "jive_showSummaryLabel": false }, { "jive_label": "BUFUGU", "value": "C06", "jive_displayOrder": 9, "jive_showSummaryLabel": false }, { "jive_label": "XYZ Company Code", "value": "DA01", "jive_displayOrder": 10, "jive_showSummaryLabel": false }, { "jive_label": "Business Purpose", "value": "C0820", "jive_displayOrder": 11, "jive_showSummaryLabel": false }, { "jive_label": "Company", "value": "XYZ", "jive_displayOrder": 19, "jive_showSummaryLabel": false }, { "jive_label": "Street Address", "value": "30 NY NY", "jive_displayOrder": 20, "jive_showSummaryLabel": false }, { "jive_label": "City", "value": "NYC", "jive_displayOrder": 21, "jive_showSummaryLabel": false }, { "jive_label": "Province/State", "value": "NY", "jive_disp…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49437741
answer count: 2
tagged with: pandas
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85865456
score: 0
has text: Waht about `df.groupby(level=0, axis=1).sum()` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49431864

http://stackoverflow.com/comment/85718754
comment on: http://stackoverflow.com/q/49358457
has text: The first paragraph seems broken.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85700283
has text: @user21359 The goal of the algorithm is to start at the beginning of the paragraph and storing the text until the end of the paragraph. Gutenburg structures the page numbers next to each paragraph. Once the text is extracted from the the page markers, which page marker is the key? The top marker or the bottom?
comment on: http://stackoverflow.com/a/49348929
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49436376
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/49436607
has comment: http://stackoverflow.com/comment/85874793
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/312443
score: 0
has answer: http://stackoverflow.com/a/49436698
answer count: 3
has comment: http://stackoverflow.com/comment/85874812
accepted answer: http://stackoverflow.com/a/49436607
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49436698
type: Question
has body: I am making a python program where I need to inspect individual four letter parts of a variable. If the variable is for example help_me_code_please it should output ease then e_pl etc , I attempted it with a=0 b=3 repetitions=5 word="10011100110000111010" for x in range (1,repetitions): print(word[a:b]) a=a+4 b=b+4 however it just outputs empty lines. Thanks so much for any help in advanced.
has title: slicing strings with variables
has answer: http://stackoverflow.com/a/49436878
has comment: http://stackoverflow.com/comment/85874765

http://stackoverflow.com/q/49321083
tagged with: python
tagged with: optimization
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49329443
tagged with: scikit-learn
favorite count: 0
type: Question
tagged with: tf-idf
has title: finding the number of clusters in a vectorized text document with sklearn tf-idf
has body: I'm trying to cluster dialogs using sklearn tf-idf and k-means. I calculated the optimal number of clusters using a silhouette score, but it increases almost linearly. So, are there other ways or maybe I'm doing something wrong? Code: tfidfV = TfidfVectorizer(max_features = 40000, ngram_range = ( 1, 3 ), sublinear_tf = True) ... X = tfidfV.fit_transform(docm2) ... for numb in nn: km = KMeans(n_clusters=numb) clabels = km.fit_predict(X) silhouette_avg = silhouette_score(X, clabels) print("For n_clusters = ", numb, "The average silhouette_score is: ", silhouette_avg)
tagged with: cluster-analysis

http://stackoverflow.com/comment/85607801
has text: Try changing `feed_dict` to `{X_1: [np.reshape(data,(1,2)) for data in x1_data], X_2: [np.reshape(data,(1,2)) for data in x2_data], Y: [np.reshape(data,(1,2)) for data in y_data]}`, the `(X_1, X_2) : (...)` looks suspicious to me
type: QuestionComment
comment on: http://stackoverflow.com/q/49302240
score: 3
type: Comment

http://stackoverflow.com/q/49432081
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/85866137
tagged with: dataframe
tagged with: python
has title: New column in Pandas dataframe based on boolean conditions
possible better answer: http://stackoverflow.com/a/49432227
accepted answer: http://stackoverflow.com/a/49432187
has body: I'd like to create a new column to a Pandas dataframe populated with True or False based on the other values in each specific row. My approach to solve this task was to apply a function checking boolean conditions across each row in the dataframe and populate the new column with either True or False. This is the dataframe: l={'DayTime':['2018-03-01','2018-03-02','2018-03-03'],'Pressure': [9,10.5,10.5], 'Feed':[9,10.5,11], 'Temp':[9,10.5,11]} df1=pd.DataFrame(l) This is the function I wrote: def ops_on(row): return row[('Feed' &gt; 10) &amp; ('Pressure' &gt; 10) &amp; ('Temp' &gt; 10) ] The function ops_on is used to create the new column ['ops_on']: df1['ops_on'] = df1.apply(ops_on, axis='columns') Unfortunately, I get this error message: TypeError: ("'>' not supported between instances of 'str' and 'int'", 'occurred at index 0') Thankful for help.
score: 12
upvote count: 12
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49432187
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49432227

http://stackoverflow.com/q/49391563
has comment: http://stackoverflow.com/comment/85787206
tagged with: matplotlib
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/85787157
possible better answer: http://stackoverflow.com/a/49393696
has body: I'm trying to create an animated plot using matplotlib. It works as expected when i'm using integers for the X values: #!/usr/bin/env python import os import random import numpy as np from datetime import datetime as dt, timedelta from collections import deque import matplotlib.pyplot as plt # $ pip install matplotlib import matplotlib.animation as animation %matplotlib notebook npoints = 30 x = deque([0], maxlen=npoints) y = deque([0], maxlen=npoints) fig, ax = plt.subplots() [line] = ax.plot(x, y) def get_data(): t = random.randint(-100, 100) return t * np.sin(t**2) def data_gen(): while True: yield get_data() def update(dy): x.append(x[-1] + 1) y.append(dy) line.set_data(x, y) ax.relim() ax.autoscale_view(True, True, True) return line, ax plt.rcParams['animation.convert_path'] = 'c:/bin/convert.exe' ani = animation.FuncAnimation(fig, update, data_gen, interval=500, blit=True) #ani.save(os.path.join('C:/','temp','test.gif'), writer='imagemagick', fps=30) plt.show() this produces the following animation: however as soon as i'm trying to use datetime values as x values - the plot is empty: npoints = 30 x = deque([dt.now()], maxlen=npoints) # NOTE: `dt.now()` y = deque([0], maxlen=npoints) fig, ax = plt.subplots() [line] = ax.plot(x, y) def get_data(): t = random.randint(-100, 100) return t * np.sin(t**2) def data_gen(): while True: yield get_data() def update(dy): x.append(dt.now()) # NOTE: `dt.now()` y.append(dy) line.set_data(x, y) ax.relim() ax.autoscale_view(True, True, True) return line, ax plt.rcParams['animation.convert_path'] = 'c:/bin/convert.exe' ani = animation.FuncAnimation(fig, update, data_gen, interval=1000, blit=True) #ani.save(os.path.join('C:/','temp','test.gif'), writer='imagemagick', fps=30) plt.show() what am I doing wrong? PS I'm using matplotlib version: 2.1.2
favorite count: 0
type: Question
score: 2
has comment: http://stackoverflow.com/comment/85784808
accepted answer: http://stackoverflow.com/a/49393361
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49393361
downvote count: 0
tagged with: animation
has title: Animation doesn't work with datetime X values, but it works properly with integers
has comment: http://stackoverflow.com/comment/85786831
has answer: http://stackoverflow.com/a/49393696
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1574088
has comment: http://stackoverflow.com/comment/85785013

http://stackoverflow.com/comment/85815239
comment on: http://stackoverflow.com/q/49397019
has text: `KeyboardInterrupt`??, do you press `Ctrl + C` between recordings?
type: Comment
type: QuestionComment
score: 0

wrapper
tag name: wrapper
tags question: http://stackoverflow.com/q/49401223
tags question: http://stackoverflow.com/q/49283215
tags question: http://stackoverflow.com/q/49318427
type: Tag

http://stackoverflow.com/comment/86949748
score: 0
has text: thank you for the feedback. I will double check the tfrecord( extract the image data from it). Another question is in your experience, any other approach to debug the bag performance( like check the weights in classification layers ) besides looking at "total loss" and "mAP"? Thank you.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49378863

http://stackoverflow.com/comment/85722604
has text: I guess you didn't understand my first comment. Here is the docstring explaining the role of the `thres` argument : _"Threshold for detecting a peak/valley. The absolute value of the intensity must be above this value"_ So obviously the data and the threshold need to be expressed in the same unit, which is not the case in your code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49358449

http://stackoverflow.com/comment/85875866
has text: thanks @drec4s .I want to only extract the data inside the image, while preserving the easy-to-read structure
comment on: http://stackoverflow.com/q/49436134
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/85681891
type: Comment
type: QuestionComment
has text: I highly recommend using [conda](https://www.anaconda.com/download/?lang=en-us) and create environments to avoid these conflicts
comment on: http://stackoverflow.com/q/49340845
score: 0

http://stackoverflow.com/comment/85759215
score: 1
type: Comment
type: QuestionComment
has text: If you can upgrade your Python version, that would be better. Python 3.3 reached end-of-life in September 2017, so doesn't even receive security fixes at this point. Is there a reason that you have to use Python 3.3?
comment on: http://stackoverflow.com/q/49379063

http://stackoverflow.com/comment/85630264
has text: Not familiar with timeit, but it looks like it accepts strings as arguments. In this scenario without the double quotes, it is recognizing your argument as one entire string, instead of a string with a variable.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49314271
type: Comment

http://stackoverflow.com/a/49308861
type: Answer
has comment: http://stackoverflow.com/comment/85643099
upvote count: 4
has comment: http://stackoverflow.com/comment/85637517
has body: import email from pkg_resources import get_distribution pkgInfo = get_distribution(package_name).get_metadata('PKG-INFO') print(email.message_from_string(pkgInfo)['Description']) package_name must be your distribution name. pkgInfo is a string that contains all metadata for the package, so I use email to parse it and return Description as a header. A little dirty trick.
accepted answer of: http://stackoverflow.com/q/49300755
has comment: http://stackoverflow.com/comment/114443775
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/49300755
has comment: http://stackoverflow.com/comment/85639927

http://stackoverflow.com/comment/85759606
type: QuestionComment
comment on: http://stackoverflow.com/q/49379505
type: Comment
has text: [TCP sockets are byte streams, not message streams](http://stupidpythonideas.blogspot.com/2013/05/sockets-are-byte-streams-not-message.html) This is probably too much to explain in a SO answer. I tried multiple times in years long past, which i why I wrote that blog post.
score: 0

http://stackoverflow.com/q/49345665
has answer: http://stackoverflow.com/a/49345688
answer count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49345947
has body: I was wondering how can I display the form errors under each field. Considering I have the log in form, if there is a problem with username, then the specific errors should be displayed under, otherwise if there is a problem with the password, the error should be displayed under the password field. I have been searching for a proper way to do it, this is what I came with: {% csrf_token %} Log In {{ form.username }} {{ form.password }} Log In {% if form.errors %} {% for field in form %} {% for error in field.errors %} {% endfor %} {% endfor %} {% for error in form.non_field_errors %} {% endfor %} {% endif %}
has answer: http://stackoverflow.com/a/49345947
type: Question
type: AnsweredQuestion
has title: How can I display the form errors under each field?
score: 0
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/49345688

http://stackoverflow.com/a/49320584
score: 0
has body: This error occurs since you're always expecting a command to have 3 inputs: command, i, e = input().split(' ') This is what happens when you use just print: &gt;&gt;&gt; "print".split(' ') ['print'] So the output of input.split() is a list with only one element. However: command, i, e = input().split(' ') is expecting 3 elements: command, i and e. Other answers already showed you how to solve modifying your code, but it can get pretty clunky as you add more commands. You can use Python's native REPL and create your own prompt. (Original post where I read about the cmd module) from cmd import Cmd class MyPrompt(Cmd): my_list = [] def do_insert(self, *args): """Inserts element in List""" self.my_list.append(*args) def do_print(self, *args): print(self.my_list) def do_quit(self, args): """Quits the program.""" raise SystemExit if __name__ == '__main__': prompt = MyPrompt() prompt.prompt = '&gt; ' prompt.cmdloop('Starting prompt...') Example: $ python main.py Starting prompt... &gt; insert 2 &gt; insert 3 &gt; insert 4 &gt; print ['2', '3', '4'] &gt; cmd also lets you document the code, since I didn't make a docstring for print this is what gets shown once I type help in the terminal: &gt; help Documented commands (type help &lt;topic&gt;): ======================================== help insert quit Undocumented commands: ====================== print I leave adding the other commands and an fun exercise to you. :)
type: Answer
answers question: http://stackoverflow.com/q/49320255

http://stackoverflow.com/q/49347070
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85693892
has comment: http://stackoverflow.com/comment/85693899
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/85693949
has title: Using %s properly (Python)
has body: import pymysql conn = pymysql.connect('localhost','root','12345','cba') myCursor = conn.cursor() tn = str(input("Enter table name : ")) myCursor.execute("""CREATE TABLE %s (rollno int primary key auto_increment,name varchar(20),age varchar(50))"""%(tn,)) name = str(input("Enter name :")) age = str(input("Enter age :")) myCursor.execute("""insert into %s (name,age) values(%s,%s) """%(tn,)),(name , age) print("Table name %s created"%(tn,)) i am getting error in line myCursor.execute("""insert into %s (name,age) values(%s,%s)"""%(tn,name,age)) i tried myCursor.execute("""insert into %s (name,age) values(%s,%s) """%(tn,)),(name,age) please help me i am stil learning
has comment: http://stackoverflow.com/comment/85693876
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85693879
has comment: http://stackoverflow.com/comment/85694017
upvote count: 0
accepted answer: http://stackoverflow.com/a/49347222
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49347222

http://stackoverflow.com/comment/85849135
type: QuestionComment
has text: Yes, but this is not the same, since on has to use the chain rule, as stated above.
comment on: http://stackoverflow.com/q/49406282
score: 0
type: Comment

http://stackoverflow.com/comment/85902571
comment on: http://stackoverflow.com/q/49430040
type: Comment
has text: Comment (originally posted as answer by @PavloMuts): Some discussions had been already on the similar problem. You could check them out [here](https://stackoverflow.com/questions/21978487/improving-python-networkx-graph-layout).
type: QuestionComment
score: 1

http://stackoverflow.com/comment/85786551
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49320362
has text: Is the answer correct? is the problem solved?
type: QuestionComment

http://stackoverflow.com/q/49419577
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Beautiful Soup: Find address og current website
upvote count: 2
duplicate of: http://stackoverflow.com/q/20475552
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/49419824
has body: I am writing a code where I am loading a lot of websites, and sometimes the link doesn't exists and instead it goes to another link (than the one I told it to). So I want to be able to identify when the current site I am scrapping from isn't actually the address I told it to go to. This is the code sample I am using. What should I add so I can find the name of the address it goes to? req = Request(l, headers={'User-Agent': 'Mozilla/5.0'}) html_page = urlopen(req).read() soup = BeautifulSoup(html_page, "lxml")
answer count: 1
linked to: http://stackoverflow.com/q/13482777
has answer: http://stackoverflow.com/a/49419824
linked to: http://stackoverflow.com/q/20475552
downvote count: 1

http://stackoverflow.com/q/49422975
type: UnansweredQuestion
tagged with: python
tagged with: cryptography
has comment: http://stackoverflow.com/comment/85890785
has comment: http://stackoverflow.com/comment/85859552
score: 0
has body: I do not understand why i don't get the same result with this python script and this bash command line: python script: from Crypto.Cipher import AES import binascii decryptor = AES.new("abcdef1234567890", AES.MODE_CBC,IV=binascii.unhexlify("a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1")) data_crypte="1234123412341234" clair = decryptor.decrypt(data_crypte) f=open("output_file_py","wb") f.write(clair) f.close() bash command line: $ echo -n 1234123412341234 | openssl enc -aes-128-cbc -K $(echo -n 'abcdef1234567890' | xxd -p) -iv a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1 -nopad -out "output_file_enc" -d Thanks
has comment: http://stackoverflow.com/comment/85880917
answer count: 0
upvote count: 2
has title: Python AES 128 CBC decrypt wrong result
has comment: http://stackoverflow.com/comment/85880972
downvote count: 2
has comment: http://stackoverflow.com/comment/85863976
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85861779

django-tables2
tags question: http://stackoverflow.com/q/49388700
tags question: http://stackoverflow.com/q/49386295
tag name: django-tables2
tags question: http://stackoverflow.com/q/49338218
tags question: http://stackoverflow.com/q/49402100
type: Tag

http://stackoverflow.com/q/49362591
answer count: 1
has comment: http://stackoverflow.com/comment/85729050
tagged with: nan
type: Question
has answer: http://stackoverflow.com/a/49365410
has title: "NaN" is not extracting in .csv
has comment: http://stackoverflow.com/comment/85728650
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85726853
tagged with: python
tagged with: python-2.7
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85728401
has body: My objective is to pass the .xlsx file and convert it into .csv, and parse to remove special character from .csv and "NaN" should display in empty cell. To do so i am using below code. If I ran below command on the console followed by #df it shows the NaN in the output. On other side If I run the code, doesn't capture the "NaN" in .csv ? df = pd.read_excel('C:\\Users\\1480587\\Documents\\Chander\\Elastic\\Data\\Dec_Inc_Data.xlsx') Using below version of Python and Pandas. INSTALLED VERSIONS ------------------ commit: None python: 2.7.11.final.0 python-bits: 64 OS: Windows OS-release: 10 pandas: 0.17.1 nose: 1.3.7 pip: 8.0.2 import pandas as pd df = pd.read_excel('C:\\Users\\1480587\\Documents\\Chander\\Elastic\\Data\\Dec_Inc_Data.xlsx') df.to_csv('C:\\Users\\1480587\\Documents\\Chander\\Elastic\\Data\\Dec_Inc_Data3.csv')

http://stackoverflow.com/a/67698886
downvote count: 0
has body: After hours of struggling with such an issue, I came to learn that Excel exports data in Multiple CSV formats. From Excel, please make sure to use 'CSV UTF-8 (Comma delimited)' option while exporting. (You often may want to use this type than the other CSV options). Once you are sure of the UTF-type, in this case, 'UTF-8', go back to your python script and change encoding to 'UTF-8', though I found skipping this parameter also works. with open('schools_dataset.csv', encoding='utf-8') as csv_file: # continue opening the file
type: Answer
answers question: http://stackoverflow.com/q/49371931
upvote count: 2
score: 2

http://stackoverflow.com/comment/85990337
type: Comment
has text: It says my 64-bit ODBC setup is working correctly.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49403624

http://stackoverflow.com/comment/85792175
comment on: http://stackoverflow.com/q/49395087
type: Comment
has text: This [question](https://stackoverflow.com/questions/31038285/python-pygame-game-lighting) has an example that might be helpful for you.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49403678
has comment: http://stackoverflow.com/comment/85820554
has comment: http://stackoverflow.com/comment/85820312
answer count: 0
has title: avoiding negative predictions in MLPRegressor in scikit
tagged with: regression
downvote count: 0
upvote count: 1
score: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85812913
has comment: http://stackoverflow.com/comment/85820415
type: UnansweredQuestion
has body: Though I have used StandardScaler or MinMaxScaler to preprocess my data while solving problem with MLPRegressor in sklearn, the predicted values have lot of negative numbers though the training set has all real positive values. Data is here: https://drive.google.com/open?id=1JF_EpyiMF5WzKZOt6d0iA2174eAheaTW. from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.neural_network import MLPRegressor x_train, x_test, y_train, y_test = train_test_split(x,y) min_max_scaler = preprocessing.MinMaxScaler() x_train = min_max_scaler.fit_transform(x_train) x_test = min_max_scaler.transform(x_test) mlp = MLPRegressor(activation='logistic' , solver='sgd' ,verbose=10, hidden_layer_sizes=(10,10), max_iter=1000) mlp.fit(x_train, y_train) print("Training set score :%f" % mlp.score(x_train, y_train)) print("Test score :%f" % mlp.score(x_test, y_test)) predictions = mlp.predict(x_test) Any suggestion where is the problem?
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/85696562
has text: I get the same error. When I start Selenium in R, Chrome opens up, but then a popup Chrome Automation Tool crashed appears.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49347949
type: AnswerComment

http://stackoverflow.com/q/49327859
type: Question
tagged with: tuples
linked to: http://stackoverflow.com/q/38189660
tagged with: python-internals
has comment: http://stackoverflow.com/comment/138514932
linked to: http://stackoverflow.com/q/14135542
tagged with: python
duplicate of: http://stackoverflow.com/q/38189660
has title: Why don't tuples get the same ID when assigned the same values?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49327911
tagged with: immutability
has body: When I executed the following steps, both tuples (a and b) haven't retained their original IDs even when I reassigned older values ((1,2)). &gt;&gt;&gt; a , b = (1,2) , (1,2) &gt;&gt;&gt; a (1, 2) &gt;&gt;&gt; b (1, 2) &gt;&gt;&gt; id(a) , id(b) (80131912, 91541064) &gt;&gt;&gt; a , b = (3,4) , (3,4) &gt;&gt;&gt; a (3, 4) &gt;&gt;&gt; b (3, 4) &gt;&gt;&gt; id(a) , id(b) (91559048, 91689032) &gt;&gt;&gt; a , b = (1,2) , (1,2) &gt;&gt;&gt; a (1, 2) &gt;&gt;&gt; b (1, 2) &gt;&gt;&gt; id(a) , id(b) (91556616, 91550408) But in the following case, both have gotten their older IDs back. &gt;&gt;&gt; a = (1,2) &gt;&gt;&gt; b = (1,2) &gt;&gt;&gt; a , b ((1, 2), (1, 2)) &gt;&gt;&gt; id(a) 88264264 &gt;&gt;&gt; id(b) 88283400 &gt;&gt;&gt; a = (3,4) &gt;&gt;&gt; b = (3,4) &gt;&gt;&gt; id(a) 88280008 &gt;&gt;&gt; id(b) 88264328 &gt;&gt;&gt; a = (1,2) &gt;&gt;&gt; b = (1,2) &gt;&gt;&gt; id(a) 88264264 &gt;&gt;&gt; id(b) 88283400 &gt;&gt;&gt; a , b ((1, 2), (1, 2)) &gt;&gt;&gt; id(a) , id(b) (88264264, 88283400) Can someone please explain this?
has answer: http://stackoverflow.com/a/49327911
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0

http://stackoverflow.com/a/49343634
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49341568
score: 1
type: Answer
has body: I wrote a wrapper to replace the Pandas Series argument with a tuple (frozen equivalent) as @abarnert and @Calvin suggested. Since tuples are immutable, the function can now be memoized. def freeze_series(f): def wrapper(series): return f(tuple(series.to_dict(OrderedDict).items())) return wrapper Here's a normal function to unfreeze the tuple back into a Pandas Series: def unfreeze_series(frozen_series): return pd.Series(OrderedDict((x, y) for x, y in frozen_series)) It can be implemented like this to solve the question example: from functools import lru_cache @freeze_series @lru_cache(maxsize=None) def fib(n): n = unfreeze_series(n) if n.iloc[0] == 1 or n.iloc[0] == 2: return 1 min1 = n.copy() min1.iloc[0] -=1 min2 = n.copy() min2.iloc[0] -= 2 return fib(min1) + fib(min2)
answers question: http://stackoverflow.com/q/49341568
downvote count: 0

http://stackoverflow.com/comment/85858014
type: QuestionComment
comment on: http://stackoverflow.com/q/49398430
has text: You need to provide more information, preferably a full minimum working example, otherwise we don't know what you did.
score: 0
type: Comment

http://stackoverflow.com/comment/85796560
comment on: http://stackoverflow.com/q/49397373
has text: FYP mean final year project if nt mistaken.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49352930
linked to: http://stackoverflow.com/q/5539736
score: 3
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85706128
has comment: http://stackoverflow.com/comment/85706090
has comment: http://stackoverflow.com/comment/85706116
has comment: http://stackoverflow.com/comment/85706150
downvote count: 1
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/120740297
tagged with: python-3.x
answer count: 0
has title: Can virtualenv be used to run Python programs on machines without Python installed?
type: UnansweredQuestion
tagged with: python
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/85706074
has body: Is it possible to run virtualenv projects on machines without Python installed? I'm developing an app on a Ubuntu machine and want to run it on a Windows machine that doesn't have Python (or any library, such as virtualenv) installed. Could I conceivably use virtualenv to develop on the Ubuntu machine, then just run the application on the Windows machine without installing Python/virtualenv?
has comment: http://stackoverflow.com/comment/85706076

http://stackoverflow.com/q/49381574
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85797935
has body: I was trying to find a whole word using regex in Python 3. The best I can come up with is: import re search_string = 'CIS 22B : Intermediate Programming Methodologies in C++' user_input = 'C++' pattern = r'\b'+re.escape(user_input) print(re.search(pattern,search_string)) Though, it has a flaw.. search would still be a success if this search string had the word C++xyz instead of C++. Which I don't want, I want it to match the word exactly. There are answers for this problem on StackOverflow.. but none of them worked for me. Probably because they were for older version of Python. Also, even for this code the method search() resulted an output.. but match() didn't. I have no idea why. Please help!
has comment: http://stackoverflow.com/comment/85763995
has comment: http://stackoverflow.com/comment/85763994
has title: Matching a single word, in python 3 regex while using re.escape() as well
tagged with: python
has comment: http://stackoverflow.com/comment/85763861
has comment: http://stackoverflow.com/comment/85764119
tagged with: regex
linked to: http://stackoverflow.com/q/45145626
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85763886
duplicate of: http://stackoverflow.com/q/45145626
linked to: http://stackoverflow.com/q/180986

http://stackoverflow.com/q/49404205
tagged with: python
upvote count: 3
tagged with: conv-neural-network
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85809685
has body: In keras fit function model.fit(X_train, y_train, nb_epoch=20, batch_size=16) How should I input the data when i have more columns? I want to input image, and detect object of class 1 on it. So the output is (x, y, width, height) The input image should be 416 x 416 x 3 and output matrix should be 13x13x4 so i want to detect up to 169 objects. Should the X_train variable be loaded set of images ( so it will be 4 dimensional array of N x 416 x 416 x 3 ) and y_train be 2D array of N x 4 , where 4 represents ( x ,y , width, height ) ? If so what do i have to pass in validation_data arguments? I am really confused.
tagged with: keras
tagged with: data-science
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85809739
has comment: http://stackoverflow.com/comment/85809545
score: 3
has title: how to input data into KERAS python?
tagged with: neural-network
has answer: http://stackoverflow.com/a/49417406

http://stackoverflow.com/comment/85848643
has text: That's true, but that doesn't mean that the class has to implement `__getitem__`. You could implement a `get_attribute` method instead or call it whatever you want. Your answer makes it look like implementing `__getitem__` is necessary for this to work.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49423605
type: Comment

http://stackoverflow.com/q/49358231
downvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85716401
has comment: http://stackoverflow.com/comment/85716453
tagged with: python
has comment: http://stackoverflow.com/comment/85716393
has comment: http://stackoverflow.com/comment/85716388
has comment: http://stackoverflow.com/comment/85716414
has comment: http://stackoverflow.com/comment/85716406
upvote count: 1
score: -4
answer count: 1
tagged with: pip
has body: This is a topic that I have not been able to find a straight answer for. Python's website (https://docs.python.org/3/installing/index.html) says that it is included from 3.4, but pip's website (https://pip.pypa.io/en/stable/installing/) says that is isn't included from python 3.4. Some youtube videos are telling me that it isn't already installed. Some questions on this page are telling me that it is. So, is it?
has comment: http://stackoverflow.com/comment/85716385
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85716419
has title: Is pip already installed on python 3.6?
has answer: http://stackoverflow.com/a/49358292

http://stackoverflow.com/comment/85677179
comment on: http://stackoverflow.com/q/49334113
has text: Okay that would be really nice of you!!
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85646338
comment on: http://stackoverflow.com/a/49303089
type: Comment
type: AnswerComment
score: 0
has text: Both questions are open and can be answered. Everyone is free to provide a different solution, although it's not too clear to me what more you are expecting.

http://stackoverflow.com/comment/103678695
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50201179
type: AnswerComment
has text: @JohnAndrews It's outside of scope of this question, but AFAIK `read_excel` will work nowadays same way as `read_csv`. According to this https://github.com/pandas-dev/pandas/issues/19454 `read_*` have been implemented.

http://stackoverflow.com/comment/85783245
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49390876
type: QuestionComment
has text: Seems to me, like this question has already been answered [here](https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo).

http://stackoverflow.com/comment/85756670
score: 0
type: Comment
type: QuestionComment
has text: What is your input list?
comment on: http://stackoverflow.com/q/49377952

http://stackoverflow.com/q/49371423
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49371574
has answer: http://stackoverflow.com/a/49371623
has comment: http://stackoverflow.com/comment/85744080
has answer: http://stackoverflow.com/a/49371574
tagged with: python
has answer: http://stackoverflow.com/a/54378349
has body: Current code: import pyodbc connection = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) if connection: print("Yes we connected\n") cur = connection.cursor() cur.execute(SELECT cost1 FROM tbl) data = cur.fetchall() for row in data: print(row) I admit I have almost no idea what I am doing in python and I got slapped with a project a little while ago that is do ASA-yesterday. I need to be able to take the results from the SQL query and sum them together. Or store them in variables to where I can call back to them in an equation. Results are: 10, 431, 543, 1268, 1207 Expected Result: 3459 I am more than happy to give any more information, and I will be spending the interim continuing to research.
accepted answer: http://stackoverflow.com/a/49371623
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/85743991
has title: Sum of Results Python SQL Query
tagged with: sql
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85743907

http://stackoverflow.com/comment/85717556
has text: Thanks! So if coloring of `R...` is a bug, is it reasonable to assume that coloring of `r"C:\Adam\Betty\Peter\Tom"` (with a yellow `P` and `T`) is another bug?
score: 0
comment on: http://stackoverflow.com/a/49358682
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49342151
has comment: http://stackoverflow.com/comment/85684843
has comment: http://stackoverflow.com/comment/85685092
has body: I have been having a lot of trouble installing PySide. I installed Qt with brew install qt as suggested in this tutorial: pyside.readthedocs.io/en/latest/installing/macosx.html. My Mac is updated to High Sierra 10.13.3. When I run pip install -U Pyside, I get the following printout: Failed building wheel for Pyside Running setup.py clean for Pyside Failed to build Pyside Installing collected packages: Pyside Running setup.py install for Pyside ... error Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-build-HTn1Jd/Pyside/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/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-nRGV6n-record/install-record.txt --single-version-externally-managed --compile: Removing /private/var/folders/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-build-HTn1Jd/Pyside/pyside_package running install running build Python architecture is 64bit error: Failed to find qmake. Please specify the path to qmake with --qmake parameter. Command "/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-build-HTn1Jd/Pyside/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/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-nRGV6n-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/4x/bkrfh91103936h2x82l9x_480000gn/T/pip-build-HTn1Jd/Pyside/ Any ideas on how to fix this? Thanks!
has comment: http://stackoverflow.com/comment/85684835
has comment: http://stackoverflow.com/comment/85684984
has comment: http://stackoverflow.com/comment/85685112
tagged with: pyside
tagged with: python
has answer: http://stackoverflow.com/a/49342569
has comment: http://stackoverflow.com/comment/85685286
type: Question
has title: Trouble installing PySide on Mac
has comment: http://stackoverflow.com/comment/85684991
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85685224
answer count: 1
has comment: http://stackoverflow.com/comment/85685085

http://stackoverflow.com/a/49389848
answers question: http://stackoverflow.com/q/49385873
type: Answer
score: 0
has body: Usually the value of an integer primary key is based on an underlying sequence in the database [1][2], which allows unique values to be allocated in a way that is safe under all the multi-transaction, multi-tenant, multi-connection racey glory that is a client-server database. Safely filling in the gaps in a sparsely-filled sequence of IDs is much more complex than "get and increment", and doesn't have any practical value for a column where the constraint is functional rather than aesthetic. From a practical standpoint, you will not run out of integer primary keys in almost all cases so there's no actual need to reuse vacant slots. If you need a sequence number that is smoothly filled from zero, maybe you can have another column for that purpose and keep it filled by another mechanism, maybe using a stored procedure to find the smallest available value to use with a new row. [1] https://www.postgresql.org/docs/10/static/sql-createsequence.html [2] https://www.postgresql.org/docs/10/static/functions-sequence.html

http://stackoverflow.com/a/49418162
answers question: http://stackoverflow.com/q/49417915
has body: why yes. yes it is: Returns A dictionary with two elements: url and fields. Url is the url to post to. Fields is a dictionary filled with the form fields and respective values to use when submitting the post. For example: {'url': 'https://mybucket.s3.amazonaws.com 'fields': {'acl': 'public-read', 'key': 'mykey', 'signature': 'mysignature', 'policy': 'mybase64 encoded policy'} }
accepted answer of: http://stackoverflow.com/q/49417915
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85817237
type: AnswerComment
has text: Make one. Read the bash documentation about these files.
type: Comment
comment on: http://stackoverflow.com/a/49406567
score: 0

http://stackoverflow.com/a/49372044
downvote count: 0
has body: This should work. There might be a nicer way to avoid the sort at the end. df_abc = df[df.value=='abc'].drop_duplicates('id', keep='last') df_not_abc = df[df.value!='abc'] df2 = pd.concat([df_abc, df_not_abc]).sort_values(by=['id', 'day'], ascending=[True, False])
answers question: http://stackoverflow.com/q/49371854
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/85734652
comment on: http://stackoverflow.com/q/49366928
type: Comment
has text: @match I think that one is mainly asking about high-order functions which the function return a new function? Not very similar to my question?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85793720
type: QuestionComment
comment on: http://stackoverflow.com/q/49395923
has text: What is the datatype of `df['date']`?
type: Comment
score: 0

http://stackoverflow.com/a/49303793
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49292221
downvote count: 0
type: Answer
has body: In case you mean html basic authentification you can also try the following workaround: (Sorry I just know Java but it should be quite similar) driver.get("http://[USERNAME]:[PASSWORD]@[rest of the Page-URL you want to enter]"); driver.get("[normal URL of the page you want to enter]"); The 2nd driver call is just reloading the page. I don´t know if you need it, but for my automation it´s needed.

http://stackoverflow.com/a/49353375
answers question: http://stackoverflow.com/q/49353288
score: 1
has body: When you use self you are trying to access members of the class, but in your case inpt it is not since it is a variable any, if you want to be a member of the class you must put forward self, in your case change: inpt = TextInput(text="Some text ",size_y=50) layout.add_widget(inpt) to: self.inpt = TextInput(text="Some text ",size_y=50) layout.add_widget(self.inpt) Note: I recommend you read OOP basics, if you are not going to have many of these problems.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49353288
upvote count: 1
has comment: http://stackoverflow.com/comment/85707115

http://stackoverflow.com/q/49387174
tagged with: urllib
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85776582
has comment: http://stackoverflow.com/comment/85775786
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85776790
has comment: http://stackoverflow.com/comment/85775614
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85776107
type: Question
has body: I am trying to download an image with python and urllib. This is my first attempt: import urllib url = "https://xxxxxxxxxxxxxxxxxxxxxxxxxx.jpg" urllib.urlretrieve(url, "myimage.jpg") The result is an empty (0 Byte) file called "myimage.jpg" The image is accessible from browser, from the same link. So I tried change the use user agent, using this script I found: from urllib import FancyURLopener url = "https://xxxxxxxxxxxxxxxxxxxxxxxxxx.jpg" class MyOpener(FancyURLopener, object): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' myopener = MyOpener() myopener.retrieve(url, 'myimage.jpg') The result is again an empty (0 Byte) file called "myimage.jpg". Additional notes: The robots.txt file is not accessible from browser: "access denied error" code 403. In the url there is the word: 'ssl' What can I do? EDIT: The image is linked from another web domain. I noticed that the image is accessible from browser only if the first time I opened the image from this specific web domain. If I clear the cookies the image become unaccessible.
has comment: http://stackoverflow.com/comment/85775926
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49387435
has comment: http://stackoverflow.com/comment/85775864
has comment: http://stackoverflow.com/comment/85775830
has comment: http://stackoverflow.com/comment/85775995
has title: Can't download image with python urllib
tagged with: python
score: -1

http://stackoverflow.com/q/49364664
has body: I have a column of sentences, which i am splitting like so df['ColTest'] = df['ColTest'].str.lower().str.split() What i am trying to do is loop through each word in each sentence and apply the autocorrect.spell() for i in df['ColTest']: for j in i: df['ColTest'][i][j].replace(at.spell(j)) This is throwing up an error AttributeError: 'float' object has no attribute 'replace' Autospell autospell DataFrame looks like ColTest This is some test string that might contain a finger but this string might contain a toe and this hass a spel error There are no numbers in my column...any ideas please?
has comment: http://stackoverflow.com/comment/85729703
tagged with: python
tagged with: string
downvote count: 1
type: AnsweredQuestion
score: 3
tagged with: pandas
tagged with: autocorrect
answer count: 1
has title: How to use autocorrect in Pandas column of sentences
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49364875
has answer: http://stackoverflow.com/a/49364875

semaphore
type: Tag
tags question: http://stackoverflow.com/q/49381195
tag name: semaphore

http://stackoverflow.com/comment/85610617
has text: You only need to round the "output", and only "when you want" to know the classes. If you want a metric, don't round it, because you will want to see the evolution of the network. You can't see the evolution from a black image to the right image while the values are between 0 and 0.5.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49301351
type: AnswerComment

http://stackoverflow.com/comment/85589594
score: 0
comment on: http://stackoverflow.com/q/49293518
type: Comment
has text: have you tried `ast.literal_eval(json.dumps(list))` ? here the list is your final result gets from json.loads
type: QuestionComment

http://stackoverflow.com/q/49355163
score: 1
upvote count: 1
tagged with: google-translator-toolkit
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49355290
tagged with: python
has body: I want to translate a tweet from Bahasa Indonesia to English, so after I can get a tweet, I run this code: from googletrans import Translator tweet = tweet.text # This saves the twitter text tw_inggris = Translator.translate(tweet, src='id', dest='en') But I got this specific error: TypeError: translate() missing 1 required positional argument: 'text' Does everyone know what's the error, and how I can fix it?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49355290
has title: translate() missing 1 required positional argument: 'text'
downvote count: 0

http://stackoverflow.com/q/49289493
tagged with: python
type: UnansweredQuestion
score: 0
has body: I would like to know a typical, efficient, "pythonic" method for converting a nested list to a typed .NET Array. Currently I am doing it in a naive way without comprehensions as I can't figure out how to do it without indices: from System import Array lstNest = [[j for j in xrange(2)] for i in xrange(10)] intArr = Array.CreateInstance(int,10,2) for i in xrange(len(lstNest)): for j in xrange(len(lstNest[i])): intArr[i,j] = lstNest[i][j]
tagged with: ironpython
has title: IronPython: Most efficient way to convert a nested python list to a .NET array
has comment: http://stackoverflow.com/comment/85582744
has comment: http://stackoverflow.com/comment/85582493
type: Question
tagged with: .net
answer count: 0

http://stackoverflow.com/comment/85737801
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49368213
has text: Minor note, `b = [aa + dd for zip(a, d)]` is not valid syntax.
score: 2

http://stackoverflow.com/comment/85688454
type: Comment
comment on: http://stackoverflow.com/q/49332244
score: 0
type: QuestionComment
has text: In this case, I want to use three separate images. one image has one channel.

http://stackoverflow.com/q/49282621
answer count: 1
type: Question
tagged with: pde
type: UnansweredQuestion
has title: How do you raise CellVariables or ImplicitSourceTerms to a power in FiPy?
tagged with: python
has answer: http://stackoverflow.com/a/49301505
tagged with: fipy
tagged with: python-2.7
has body: With FiPy (Python library) I want to solve the coupled of pdes system shown below. The code below works, but doesn't give the correct solution. p, q, r, s = 2, 1, 2, 0 Du, Dv = 0.0004, 0.04 mesh = Grid1D(nx=500, Lx=5.) U = CellVariable(name = 'U',mesh=mesh, hasOld=True, value=1.) V = CellVariable(name = 'V',mesh=mesh, hasOld=True, value=2.) eqU = TransientTerm(var=U) == DiffusionTerm(coeff=Du, var=U) - U + (U**p)/(V**q) eqV = TransientTerm(var=V) == DiffusionTerm(coeff=Dv, var=V) - V + (U**r)/(V**s) viewerV = Viewer(vars=V) viewerU = Viewer(vars=U) timeStepDuration = 0.1 steps = 1000 eqn = eqU &amp; eqV for t in range(500): U.updateOld() V.updateOld() eqn.solve(dt=1.e-3) viewerV.plot() viewerU.plot() In line with some code I saw I also tried to replace the CellVariables with ImplicitSourceTerm, but this gives an error, since taking a ImplicitSourceTerm to the power p can't be done in this way. However I can't find any documentation on how it should be done: eqU = TransientTerm(var=U) == DiffusionTerm(coeff=Du, var=U) - ImplicitSourceTerm(var=U) + ((ImplicitSourceTerm(var=U)**p)/(ImplicitSourceTerm(var=V)**q)) eqV = TransientTerm(var=V) == DiffusionTerm(coeff=Dv, var=V) - ImplicitSourceTerm(var=V) + ((ImplicitSourceTerm(var=U)**r)/(ImplicitSourceTerm(var=V)**s)) Trying to raise U.value**p also gives errors.
score: 0

http://stackoverflow.com/a/49361819
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49361673
type: Answer
has body: from collections import Counter Counter([d['first_name'] + ' ' + d['last_name'] for d in dict_nomi]) out: Counter({'Luca Rossi': 2, 'Stefano De Rosso': 1, 'Luca Bianchi': 1})

http://stackoverflow.com/comment/85840152
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49372282
score: 3
has text: This is not **auto**correlation. Autocorrelation is between a signal and a delayed copy of the same signal. You have two signals, data1 and data2.

http://stackoverflow.com/a/49400266
has body: Since you've set the scheme='quantiles', you probably want to use categorical color patches for legend. You can use the legend option and move it outside the plot like this: import geopandas as gpd import matplotlib.pyplot as plt world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax = world.plot(column='gdp_md_est', cmap='OrRd', scheme='quantiles', legend=True) ax.get_legend().set_bbox_to_anchor((1.5, 1)) ax.set_axis_off() plt.axis('equal') plt.show() If you really want a colorbar, you may need to code it yourself. The following code is adapted from geopandas: import geopandas as gpd import matplotlib.pyplot as plt world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax = world.plot(column='gdp_md_est', cmap='OrRd', scheme='quantiles') from matplotlib.colors import Normalize from matplotlib import cm norm = Normalize(vmin=world['gdp_md_est'].min(), vmax=world['gdp_md_est'].max()) n_cmap = cm.ScalarMappable(norm=norm, cmap='OrRd') n_cmap.set_array([]) ax.get_figure().colorbar(n_cmap) ax.set_axis_off() plt.axis('equal') plt.show()
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49395927
has comment: http://stackoverflow.com/comment/85803697
type: Answer

http://stackoverflow.com/comment/85872540
type: QuestionComment
comment on: http://stackoverflow.com/q/49435317
has text: `pd.isnull` also works for NaTs.
score: 8
type: Comment

http://stackoverflow.com/a/49391589
has comment: http://stackoverflow.com/comment/85784852
type: Answer
answers question: http://stackoverflow.com/q/49391213
has comment: http://stackoverflow.com/comment/85785415
has body: Here's a way to do it for a sample of the text- Python will not convert chars to ints in the way that Java/C may. Instead, you would get the ordinal value, and then convert this to a binary number def to_bin(c): bin_rep = bin(ord(c)) print bin_rep # for testing return bin_rep # can be written to a file here or not... text = "Hello there" for each_char in text: to_bin(each_char) I think this approach is worth trying with a sample of your input file, and then refactor to do it as a file r/w. To do this with the file, try this: write_str = "" with open('program.txt', 'r') as plik: # otwieramy plik do odczytu for line in plik: for each_char in line: write_str += str(to_bin(each_char)) with open('wyniki.txt', 'w') as plik1: plik1.write(write_str) plik1.close() plik.close() If you want the order of the bytes reversed, the entire file could be reversed or change write_str += str(to_bin(each_char)) to write_str = str(to_bin(each_char)) + write_str
score: 0

http://stackoverflow.com/a/49309391
answers question: http://stackoverflow.com/q/49309310
type: Answer
upvote count: 4
score: 4
has body: Piko.get('Surname') Piko.get('Surname', None) are identical and return None since "Surname" is not in your dictionary. For future reference you can quickly discover this from the Python shell (eg ipython) by typing: In[4]: help(Piku.get) Which produces: Help on built-in function get: get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49309310

http://stackoverflow.com/comment/85816166
type: AnswerComment
comment on: http://stackoverflow.com/a/49406842
score: 0
type: Comment
has text: If your questions have been answered please mark one as accepted.

http://stackoverflow.com/q/49432508
accepted answer: http://stackoverflow.com/a/49434028
has comment: http://stackoverflow.com/comment/85867008
has body: I wrote the following function to convert a value (col) with unit (ufrom) into another unit (uto): def convert(row, col , ufrom, uto): convRow = convDF[(convDF.from == row[ufrom]) &amp; (convDF.to == uto)] val = row[col] / convRow.factor return(val, uto) convDF is a dataframe containing several units and their conversion factor. I call the function like this: for idx, row in df.iterrows(): if row.Unit!= 'MM': df.at[idx, ['Width', 'Unit']] = convert(row,'Width', 'Unit', 'MM') df.at[idx, ['Length', 'Unit']] = convert(row,'Length', 'Unit', 'MM') df.at[idx, ['Hight', 'Unit']] = convert(row,'Hight', 'Unit', 'MM') The convert function gets the current row, the column containing the value that needs to be converted, the source unit column as well as the destination unit. So far it works perfectly. As you can see, I call the function three times but I was wondering if I could call it once and pass all three arguments (Width, Length, Hight) and convert them because they have the same column refering to their unit (Unit) and the same destination unit (uto). So I would like the function to handle single as well as multiple values. In the end, this df.at[idx, ['Width', 'Unit']] = convert(row,'Width', 'Unit', 'MM') should work as well as this df.at[idx, ['Width','Length','Hight', 'Unit']] = convert(row,['Width','Length','Hight'],'Unit', 'MM') Tried working with the *-syntax for passing 1:n arguments but how do I change the convert function to give multiple or single results? Thank you!
tagged with: python
has answer: http://stackoverflow.com/a/49434028
score: -1
type: AnsweredQuestion
tagged with: pandas
upvote count: 0
has title: Multiple input/output arguments for function in python
answer count: 1
downvote count: 1
tagged with: multiple-columns
favorite count: 0
type: Question
tagged with: function

http://stackoverflow.com/comment/85625956
score: 0
has text: player['health'] -= giant_rat['attack']
comment on: http://stackoverflow.com/q/49312048
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49335335
has comment: http://stackoverflow.com/comment/85672170
score: 1
upvote count: 1
downvote count: 0
has body: If all you want is to filter out the strings between two predefined strings, this code will do: def filter_output_between_strings(input: [str], separator: str): separator_indexes = [index for index, word in enumerate(input) if word == separator] for example_index, (start, end) in enumerate(zip(separator_indexes[:-1], separator_indexes[1:]), start=1): print('Example: {}: {}'.format(example_index, input[start + 1:end])) if __name__ == '__main__': input = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT', 'GONOW', 'MAKE', 'COMMENT', 'YES', 'COMMENT'] filter_output_between_strings(input, 'COMMENT') Output: Example: 1: ['YES', 'YES', 'NO', '123'] Example: 2: ['GONOW', 'MAKE'] Example: 3: ['YES']
has comment: http://stackoverflow.com/comment/85672239
answers question: http://stackoverflow.com/q/49335177
has comment: http://stackoverflow.com/comment/85672272
type: Answer

http://stackoverflow.com/a/49355272
downvote count: 0
has body: The method str.split called without arguments has a somewhat different behaviour. First it splits by any whitespace character. 'foo bar\nbaz\tmeh'.split() # ['foo', 'bar', 'baz', 'meh'] But it also remove the empty strings from the output list. ' foo bar '.split(' ') # ['', 'foo', 'bar', ''] ' foo bar '.split() # ['foo', 'bar']
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49354949
type: Answer

http://stackoverflow.com/comment/85863599
comment on: http://stackoverflow.com/a/49408701
has text: i used parenthesis abut why i type else: it showed out SyntaxErrors : invalid syntax
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49288777
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49292063
tagged with: list
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49288823
possible better answer: http://stackoverflow.com/a/49292063
has answer: http://stackoverflow.com/a/49288823
has title: How to access elements from 3 lists with index set at minimum value from one list?
type: Question
tagged with: python-3.x
has body: Say I have 3 lists of the same dimensions which contains elements of velocity, distance and time. V = [1, 2, 3, 4, -5, 4, 3, 2, 1] D = [10, 9, 8, 7, 6, 5, 4, 3, 2] T = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] If I want to find the minimum velocity in my V list I can just do np.amin(V) and I will get 5 in this case. But then how do I go about printing/getting/returning my value of D and T at that specific V? I have tried something like this def MAXVTIME(VELOCITY, DISTANCE, TIME): for i, (VELOCITY, DISTANCE, TIME) in enumerate(zip(VELOCITY, DISTANCE, TIME)): if VELOCITY == np.amin(VELOCITY): return VELOCITY.i(np.amin(VELOCITY)) but I can't get it to work. I need my function to be able to input 3 lists of velocity, distance and time, choose the smallest velocity value, and return the velocity, distance and time at that value. Think of this as a person falling down, its smallest speed will be its maximum velocity(taking downwards as negative), and the distance is decreasing while time is ticking.

http://stackoverflow.com/comment/85874391
has text: Even when memory consumption is high?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49421699
type: QuestionComment

http://stackoverflow.com/comment/85693274
score: 0
has text: To make them move upward, instead of passing a hardcoded `90` for `y`, pass a different value for each frame that moves upward. (I assume your real program has a frame loop, or, if not, an event loop? If you don't have either, you can't animate anything, and you need to read a basic tutorial first.)
comment on: http://stackoverflow.com/q/49346708
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85692424
comment on: http://stackoverflow.com/q/49319575
type: QuestionComment
has text: Alright, I’ll do that as first thing in the morning but I was about to update as well. I solved the issue but just couldnt find the exact spot on SDK repo itself, where the issue occurs. So as I mentioned I was using patch_all() but somehow when I used a simple something like patch(“boto3”,”...”) etc it stopped duplicating the nodes but yep ill update he post with screenshots and the output.
type: Comment
score: 1

http://stackoverflow.com/comment/85687850
has text: Possibly relevant: https://stackoverflow.com/questions/17675925/eoferror-eof-when-reading-a-line
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49343690

http://stackoverflow.com/comment/85660419
score: 3
type: Comment
comment on: http://stackoverflow.com/a/49328301
type: AnswerComment
has text: fit_transform is also advertised as more efficient by sklearn

http://stackoverflow.com/comment/85811657
type: AnswerComment
comment on: http://stackoverflow.com/a/49405283
has text: ndpu, why [cur.execute('use %i' % i)]? I mean what the second for actually does?
type: Comment
score: 0

http://stackoverflow.com/q/49300755
favorite count: 0
type: Question
upvote count: 5
has title: How to get access to long_description in setup after installation using pip?
tagged with: python
type: AnsweredQuestion
score: 5
has body: In the Python packaging sampleproject there is a long description for the module, given in setup.py using: # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() ... setup( ... # This is an optional longer description of your project that represents # the body of text which users will see when they visit PyPI. # # Often, this is the same as your README, so you can just read it in from # that file directly (as we have already done above) # # This field corresponds to the "Description" metadata field: # https://packaging.python.org/specifications/core-metadata/#description-optional long_description=long_description, # Optional How can the user get access to this descprtion, maybe in different format, after the module is installed with pip install sampleproject?
has answer: http://stackoverflow.com/a/49308861
accepted answer: http://stackoverflow.com/a/49308861
tagged with: setuptools
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49348831
has answer: http://stackoverflow.com/a/49348946
score: -1
has title: Shuffle a pack of cards and distribute it among four players. You need to stop the game when someone has 4 hearts and say who is the winner
type: AnsweredQuestion
tagged with: probability
answer count: 2
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/85697448
favorite count: 0
has comment: http://stackoverflow.com/comment/85697541
type: Question
possible better answer: http://stackoverflow.com/a/49349053
tagged with: python
accepted answer: http://stackoverflow.com/a/49348946
has answer: http://stackoverflow.com/a/49349053
has body: I need to write a python code for Shuffle a pack of cards and distribute it among four players. You need to stop the game when someone has 4 hearts and say who is the winner. As im a beginner in python and finished it straight forward way. can anyone give me optimized way to code this ??. here is my try.. import random colour=["Heart","Spade","Club","Diamond"] a=[2,3,4,5,6,7,8,9,10,"J","Q","K","A"] player1,player2,player3,player4=[],[],[],[] shuffle=[{x:y} for x in colour for y in a ] cnt=0 while len(shuffle)!=0: p1,p2,p3,p4=random.sample(population=shuffle,k=4) i1=shuffle.index(p1) del shuffle[i1] i2=shuffle.index(p2) del shuffle[i2] i3=shuffle.index(p3) del shuffle[i3] i4=shuffle.index(p4) del shuffle[i4] if "Heart" in p1: player1.append(p1) if len(player1)&gt;=4: print("player 1 is win ,heart cards are:",player1) break if "Heart" in p2: player2.append(p2) if len(player2)&gt;=4: print("player 2 is win,heart cards are:",player2) break if "Heart" in p3: player3.append(p3) if len(player3)&gt;=4: print("player 3 is win,heart cards are:",player3) break if "Heart" in p4: player4.append(p4) if len(player4)&gt;=4: print("player 4 is win,heart cards are:",player4) break

http://stackoverflow.com/q/49373363
has answer: http://stackoverflow.com/a/49375561
type: AnsweredQuestion
has title: Python/Pandas - df.duplicated() MemoryError: cannot allocate memory for array
tagged with: pandas
upvote count: 0
answer count: 1
has body: I am getting a MemoryError: cannot allocate memory for array when using df.duplicated() to check for duplicates in a data frame in Python 3.6.4. The df has about 150,000 rows and 208 columns and there are no issues with loading the data into a df (using chunks per below). myList = [] for chunks in pd.read_csv(filename, header=0, low_memory=False, chunksize=20000): myList.append(chunks) dfMain = pd.concat(myList, axis=0) dfMain.index.name = 'Index' print (dfMain.shape) Out: (151982, 208) Everything is fine up until this point. #Marks duplicated rows with TRUE or FALSE and put into a new df dfDup1 = pd.DataFrame(dfMain.duplicated(keep=False)) #set to False to view all duplicates This is where the error occurs: MemoryError: cannot allocate memory for array and the script stops. Unfortunately, reducing the number of columns is not an option, I need to check for duplicates across all of variables (although I did drop 150 variables to test but the problem persisted). And I do need to export the duplicated values to df/csv, so can't use drop_duplicates() at this stage. The computer has plenty of RAM (64 gigs), but Python/pandas is using only a fraction of it. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/85748651
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85748674
type: Question
has comment: http://stackoverflow.com/comment/85748693
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85748217
has comment: http://stackoverflow.com/comment/85748987
has comment: http://stackoverflow.com/comment/85749031
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49375561
tagged with: memory

http://stackoverflow.com/a/62816907
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49355010
has body: You actually can use nodemon with python, from their docs: Running non-node scripts nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of .js if there's no nodemon.json: nodemon --exec "python -v" ./app.py Now nodemon will run app.py with python in verbose mode (note that if you're not passing args to the exec program, you don't need the quotes), and look for new or modified files with the .py extension. https://github.com/remy/nodemon#running-non-node-scripts
type: Answer

http://stackoverflow.com/comment/85764150
comment on: http://stackoverflow.com/q/49379088
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python openpyxl read until emtpy cell](https://stackoverflow.com/questions/49365992/python-openpyxl-read-until-emtpy-cell)

http://stackoverflow.com/comment/85704477
has text: looks like, sometimes nothing is being returned. check the following link , https://stackoverflow.com/questions/8381193/python-handle-json-decode-error-when-nothing-returned
comment on: http://stackoverflow.com/a/49352135
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85875913
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49436834
has text: @moenad and Yilun : I thought to solve it by considering the .sql file just like a .txt file. for each line in the file, after the first single quote the name of a city starts and spans till the next quote. like: 'Tuscaloosa' . Now, i'll search for this word in the string. If match occurs, store the value in vars or go to the next line. - this is my algo. Is it possible to do this in this way? If it is, I can't write the correct code in Python.

http://stackoverflow.com/a/49287239
upvote count: 1
has body: The error I get is that sa is a unresolved reference The reason this happens is due to local scope. When executing your tr function, only variables either passed into the function, declared as a global variable, or declared in the function are seen and used. def tr(ok): s = 1 sa = sa + (ok / s) print (sa) In your code, the variables are: ok s sa The computer can't finish assigning a value to sa because it needs sa to already have a value assigned in order to calculate the value of sa. If I gave you a math problem stating X+1 and asked you what the result of that would be, you'd be unable to because I never told you what X is in the first place. So here's what you should do: Declare what sa is supposed to be inside the function: sa = *something that the computer can set sa equal to* sa + (ok / s) Pass the value into the function by modifying both the function call and the function definition: def tr(ok, sa): Or declare sa as a global variable.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49286738
downvote count: 0

twisted
tags question: http://stackoverflow.com/q/49342660
tags question: http://stackoverflow.com/q/49367026
tags question: http://stackoverflow.com/q/49410042
type: Tag
tag name: twisted
tags question: http://stackoverflow.com/q/49347506
tags question: http://stackoverflow.com/q/49334497

http://stackoverflow.com/comment/85694775
comment on: http://stackoverflow.com/a/49346089
has text: Don't feel silly, the naming of packages in the DB space is pretty confusing. :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49308712
has body: You probably have an extra opening HTML tag somewhere. You can try to search through your code using your editors CTRL+F and look for "&lt;&lt;". I would look for the problem in your HTML.
answers question: http://stackoverflow.com/q/49308534
type: Answer
score: 0

http://stackoverflow.com/q/49334438
has title: *** ConnectionError: ('Connection aborted.', error(13, 'Permission denied')) when trying to upload files to Google Cloud Storage
tagged with: ssl
tagged with: python
type: UnansweredQuestion
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/49404175
has body: I am testing my app using dev_appserver.py. My function to upload files looks something like: def upload_file(file_stream, filename): """Upload a file to Google Cloud Storage.""" client = google.cloud.storage.client.Client(project=_GOOGLE_CLOUD_PROJECT) bucket = client.get_bucket(_GOOGLE_STORAGE_BUCKET) # Here it breaks! blob = bucket.blob(filename) blob.upload_from_string(file_stream) url = blob.public_url return url At the line bucket = client.get_bucket(_GOOGLE_STORAGE_BUCKET) I receive an error saying: *** ConnectionError: ('Connection aborted.', error(13, 'Permission denied')) I authenticated by doing: gcloud auth application-default login My app.yaml: runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static application_readable: true - url: /.* script: main.app libraries: - name: ssl version: latest Any idea how to solve?
tagged with: google-cloud-platform
score: 0
tagged with: flask
answer count: 1
type: Question

http://stackoverflow.com/comment/85725286
comment on: http://stackoverflow.com/a/49361075
score: 0
has text: Do you have a file called textblob.py in your dir?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49384708
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49384794
accepted answer: http://stackoverflow.com/a/49384794
has comment: http://stackoverflow.com/comment/85770525
score: 1
has title: Call class method from function running in other process in Python
tagged with: python
has comment: http://stackoverflow.com/comment/85803862
tagged with: python-multiprocessing
type: AnsweredQuestion
downvote count: 0
tagged with: ipc
upvote count: 1
answer count: 1
has body: I have a main GUI to receive data from an amplifier and plot it. When I click a button, a new process is created and it is receiving data with a blocking method (that is why I need another process). My question is, how can I send the received data to the main GUI to plot it? Here is an scheme and what I've tried: import multiprocessing as mp # Load the .ui file gui_main_class = uic.loadUiType("gui_main.ui")[0] # Function that receive the data (RUNS IN OTHER PROCESS) def manager_process(gui_main): amp = AmpReceiver() while True data = amp.getData() **HERE IS WHERE I HAVE TO CALL draw_data(data) IN GuiMainClass TO PLOT THE DATA** # Main class that instantiates the UI class GuiMainClass(QtWidgets.QMainWindow, gui_main_class): def __init__(self, parent=None): QtGui.QWindow.__init__(self, parent) self.setupUi(self) self.pushButton.clicked.connect(self.receive_data_process) def receive_data_process(self): self.data_receiver_process = mp.Process(target=manager_process) self.data_receiver_process.start() def draw_data(self, data): CODE TO UPDATE THE PLOT (NOT INTERESTING FOR THE QUESTION) # Main function if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) application = GuiMainClass() sys.exit(app.exec_()) I think that it has to be possible, but I don't know how to adress the problem because I found that passing an object between processes actually copies the object but don't pass it in reference (so you can't call the methods on the original one) So, what do you think is the best option? Thank you very much!

http://stackoverflow.com/comment/85853072
score: 0
comment on: http://stackoverflow.com/q/49425029
has text: I've already set `USE_TZ = True`. This https://www.percona.com/blog/2015/01/07/django-with-time-zone-support-and-mysql/ does work, but it is again sort of a middleware. I am interested in knowing that from where is Model still taking UTC, when I've set IST everywhere, and I want to update that exact point, instead of using any middleware each time.
type: Comment
type: QuestionComment

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/49380657
type: Tag

http://stackoverflow.com/comment/85859511
type: Comment
comment on: http://stackoverflow.com/a/49422203
has text: yeah, there's no good reason to use a global here, since you're dealing with a method on a class.
score: 2
type: AnswerComment

http://stackoverflow.com/q/49305461
tagged with: keras
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85620359
has title: ValueError: Error when checking input: expected conv3d_1_input to have 5 dimensions, but got array with shape (7, 9, 384, 1)
has comment: http://stackoverflow.com/comment/85620063
tagged with: python
has comment: http://stackoverflow.com/comment/85618147
has body: I have the tensorflow as the backend. I'm using the 3D convolution layer in keras. My final x training data is in shape (7,9,384,1), channel equals to 1, y training data is in shape (7,1,384,1). I keep getting this error when it runs model.fit(). I checked out most of the related problems posted online, but they all kind of focus on whether it's theaon or tensorflow as the backend. Some of them suggests expand dimensions, but still doesn't work and some other problems showed up. According to the keras documents, 3D convolution should have a 5D input shape, and I am lacking the first dimension samples. I only have this one 3D data input (in shape 7,9,384), and I tried adding a 1 at the beginning of the input_shape parameter in the first layer, and it will cause another problem saying that I exceeded one dimension in the input shape. Can anyone please take a look and tell me what's wrong? Thank you so much! import numpy as np from keras.models import Sequential from keras.layers import * # Read the array from disk data = np.loadtxt('D:/8_CNN_pycharm/data.txt', delimiter=',') x = data[:,1:10] y = data[:,0] rownum = np.size(x,0) # boundIndex = 384 boundIndex = int(rownum/7/3*2) x_train = x[0:7*boundIndex,:] y_train = y[0:7*boundIndex] x_test = x[7*boundIndex:,:] y_test = y[7*boundIndex:] print(rownum) print(x_train.shape[0]) print(x_test.shape) # Going to 3D array using desired shape of the array new_x_train = x_train.reshape(7,9,boundIndex,1) # new_x_train = new_x_train.reshape(new_x_train.shape[0],7,9,boundIndex,1) # new_x_train = np.expand_dims(new_x_train,axis=0) new_y_train = y_train.reshape(7,1,boundIndex,1) # new_y_train = np.expand_dims(new_y_train,axis=0) print(new_x_train.shape[:]) # x_input = Input(shape=(7,9,boundIndex, 1)) new_x_test = x_test.reshape((7,9,int(rownum/7-boundIndex))) new_y_test = y_test.reshape((7,1,int(rownum/7-boundIndex))) model = Sequential() # model.add(Conv2D(64, (4,3), padding='same', activation='relu', input_shape=(7,9,boundIndex))) m…
has comment: http://stackoverflow.com/comment/85620094
accepted answer: http://stackoverflow.com/a/49307957
type: AnsweredQuestion
score: 0
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/49307957
has comment: http://stackoverflow.com/comment/85614634
answer count: 1

http://stackoverflow.com/a/51459077
has comment: http://stackoverflow.com/comment/89887827
score: 0
answers question: http://stackoverflow.com/q/49410722
has comment: http://stackoverflow.com/comment/89888022
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89893738
type: Answer
has body: While printing every line to log might help you to debug and troubleshoot your code, this is a very manual and not scaleable option. In addition, you would lose your mind going through endless logs. In the serverless world (and specifically in AWS, where you have Lambda, DynamoDB, SQS, SNS, API Gateway, and lots of other resources), you should use the right tools that will give you visibility into your architecture, allow you to troubleshoot issues quickly, and will identify serverless specific issues (timeouts, out of memory, ..). One thing you can try out is to stream out all your logs from CloudWatch to an external service such as ELK. It will allow you to easily explore them. Otherwise, I'm recommending to use a dedicated solution for serverless - there are several out there (our own Epsagon, IOpipe, Dashbird).

http://stackoverflow.com/comment/85776705
score: 0
type: Comment
has text: I tried executing the PHP file. The Python script got called and worked until the end. I would recommend looking at the `STDERR` output of the Python script to find out why it might have stopped. Maybe try adding `2>&1` to the python command (and temporarily remove `escapeshellcommand`) to redirect `STDERR` to `STDOUT` if you can't see `STDERR` otherwise. (Not 100% sure if this works in Windows.)
type: QuestionComment
comment on: http://stackoverflow.com/q/49384498

http://stackoverflow.com/comment/85583517
has text: OK, just post the rest of your code pls and Ill see what I can do
type: AnswerComment
comment on: http://stackoverflow.com/a/49289907
score: 0
type: Comment

http://stackoverflow.com/comment/85595510
score: 0
type: AnswerComment
has text: When I use `label=None`, I get a plot with no legend and the following printed in my terminal screen: `UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "` rather than an empty legend.
type: Comment
comment on: http://stackoverflow.com/a/49295225

http://stackoverflow.com/q/49292221
has comment: http://stackoverflow.com/comment/85595502
downvote count: 1
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/45328654
has title: How to pass authentication pop up in selenium?
type: AnsweredQuestion
answer count: 5
has answer: http://stackoverflow.com/a/74279984
has answer: http://stackoverflow.com/a/63818304
favorite count: 0
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/49303793
has answer: http://stackoverflow.com/a/49292682
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/74279984
accepted answer: http://stackoverflow.com/a/49297014
has body: I'm trying to load a web page that requires authentication using Python script with Selenium. options = webdriver.ChromeOptions() prefs = {'download.default_directory': r"download.default_directory=" + download_folder, "download.prompt_for_download": False, 'profile.default_content_setting_values.automatic_downloads': 1} options.add_experimental_option('prefs', prefs) options.add_argument("--start-maximized") options.add_argument('--disable-browser-side-navigation') driver = webdriver.Chrome(chrome_options=options, executable_path=chrome_driver) driver.get('https://user:pass@somepage.com/32324') This still gets the popup alert with user name and password. So, I figured I'll just handle the alert in code but it seems the page doesn't finish loading until the alert is closed so the script is stuck on the get function. How do I handle this situation? EDIT: This is not duplication because the accepted answer there doesn't work for me.
has comment: http://stackoverflow.com/comment/85588364
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/49297014
tagged with: python

http://stackoverflow.com/q/49301857
has body: I am using the following version of Jupyter Notebook and I have created a dashboard layout. The version of the notebook server is 5.0.0 But when I do (File -> Deploy as -> Dashboard on Jupyter Notebook Server), I get the below error message "No dashboard server configured". Please refer the screenshot below. In addition, under 'Deploy as' I do not see → 'Local Dashboard in Jupyter' option. Just wanted to understand what could be the reason for the same? I wanted to share the dashboard with non-programmers, so what is the other easy way we have to share the dashboard? I have googled this, but the solution which I have got there is almost deprecated. So thought of checking it here. Any help would be appreciated on this. Dashboard on Jupyter Notebook Server
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/49548013
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49548013
has title: How to share Jupyter Notebook Dashboard?
type: Question
tagged with: python

http://stackoverflow.com/a/49324752
type: Answer
has comment: http://stackoverflow.com/comment/85651229
has comment: http://stackoverflow.com/comment/85651577
accepted answer of: http://stackoverflow.com/q/49324347
has comment: http://stackoverflow.com/comment/85652253
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85651101
type: AcceptedAnswer
score: 3
has comment: http://stackoverflow.com/comment/85652477
answers question: http://stackoverflow.com/q/49324347
has comment: http://stackoverflow.com/comment/85652784
has comment: http://stackoverflow.com/comment/85652184
has body: This is one solution using collections.defaultdict and sets. The desired output is very similar to what you have, and can be easily manipulated to align. from collections import defaultdict results = { 'ben' : ['benj', 'benjamin', 'benyamin'], 'benj': ['ben', 'beny', 'benjamin'], 'benjamin': 'benyamin', 'benyamin': 'benjamin', 'carl': 'karl', 'karl': 'carl', } d = defaultdict(set) for i, (k, v) in enumerate(results.items()): w = {k} | (set(v) if isinstance(v, list) else {v}) for m, n in d.items(): if not n.isdisjoint(w): d[m].update(w) break else: d[i] = w result = {max(v, key=len): v for k, v in d.items()} # {'benjamin': {'ben', 'benj', 'benjamin', 'beny', 'benyamin'}, # 'carl': {'carl', 'karl'}} Credit to @IMCoins for the idea of manipulating v to w in second loop. Explanation There are 3 main steps: Convert values into a consistent set format, including keys and values from original dictionary. Cycle through this dictionary and add values to a new dictionary. If there is an intersection with some key [i.e. sets are not disjoint], then use that key. Otherwise, add to new key determined via enumeration. Create result dictionary in a final transformation by mapping max length key to values.
has comment: http://stackoverflow.com/comment/85679825

http://stackoverflow.com/comment/85706564
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49352961
type: QuestionComment
has text: Is the program going to exit when these worker threads finish?

http://stackoverflow.com/comment/85839380
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49392370
has text: Too many words KillerT. Cut down the length to one paragraph tops. Your issue is two fold: 1. Are you using he functions correctly. 2. Is your model assumption a good one. It looks like you’re using the functions fine. Maybe print out the top few max/min values of the covariance and mean? You can have really sharp curvature in high dim space. Why not iterate the entire z-vector and see if they are all 0.0?

http://stackoverflow.com/comment/85579228
type: Comment
has text: I think I understand now. So I could probably make 'otherImages' method return a string instead of writing. Then manipulate that string in the 'narrow' method and take the output and write that.
type: AnswerComment
comment on: http://stackoverflow.com/a/49287473
score: 0

http://stackoverflow.com/comment/85579137
comment on: http://stackoverflow.com/q/49287971
score: 0
has text: where is the code? Please provide a [Minimal, Complete & Verifiable example](https://stackoverflow.com/help/mcve).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85827113
has text: @disp_name Maybe make use of `string.punctuation`
comment on: http://stackoverflow.com/a/49412607
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49393453
has body: optimizer = tf.train.GradientDescentOptimizer(self._lr) will basically create a new optimizer with the modified learning rate every time it is called. But understand that learning rate is not the only parameter in an optimizer and there will be other parameters like momentum etc., which will be reinitialized on doing so. Hence correct scheduling would be to keep those other parameters unchanged and just modify the learning rate which is what is done in the tutorial by storing the learning rate as a tf.Variable and is updated by calling the function assign_lr(). Hope this answers your query.
answers question: http://stackoverflow.com/q/49392488
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49392488
has comment: http://stackoverflow.com/comment/85790302
score: 1
type: Answer

http://stackoverflow.com/a/62238924
has body: The trick is to add layout = go.Layout(annotations= [dict( 'my Annotations')]) in to the frame frames = [dict(data=[], traces=[], layout = go.Layout(annotations= [dict( 'my Annotations')]) )] Then the annotations will be related to the frame and not to the parent layout
downvote count: 0
answers question: http://stackoverflow.com/q/49405265
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/113728132
type: AnswerComment
has text: It ain't working. I got following error : RuntimeError: Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.
score: 0
comment on: http://stackoverflow.com/a/49352409
type: Comment

http://stackoverflow.com/a/49433106
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85871132
accepted answer of: http://stackoverflow.com/q/49432729
has body: Apply a groupby + np.sum operation on your data. s.groupby(pd.Grouper(freq='1D')).apply(np.sum, axis=0) 2008-07-01 [[24.0, 24.0, 24.0, 24.0], [24.0, 24.0, 24.0, ... 2008-07-02 [[24.0, 24.0, 24.0, 24.0], [24.0, 24.0, 24.0, ... 2008-07-03 [[24.0, 24.0, 24.0, 24.0], [24.0, 24.0, 24.0, ... Freq: D, dtype: object
type: Answer
answers question: http://stackoverflow.com/q/49432729

http://stackoverflow.com/q/49332154
has comment: http://stackoverflow.com/comment/85666270
has body: I'm trying to convert the code below into a function, but keep getting errors. Can anyone help with the steps I need to take in order to refactor this code into a funtion? n1 = int(input('Enter First Number')) n2 = int(input('Enter Second Number')) n3 = int(input('Enter Third Number')) average = int(n1 + n2 + n3)/3 print('') print('The Average Is:'), print(average)
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49332237
downvote count: 5
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85666279
answer count: 2
has comment: http://stackoverflow.com/comment/85666290
upvote count: 0
tagged with: function
score: -5
has answer: http://stackoverflow.com/a/49332237
accepted answer: http://stackoverflow.com/a/49332164
has title: Converting python code into a function
has answer: http://stackoverflow.com/a/49332164

http://stackoverflow.com/comment/85766097
has text: Should I worry about the contents of my post then?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49369212

http://stackoverflow.com/comment/85763039
has text: I checked out your link, but the thing is "dlink.find('a')['href'], should return a download link to a movies subtitle. And as for the fallbacks, once I get this script working properly in it's rudimentary form, I'll modify it. Thanks for the reply!
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49380186

http://stackoverflow.com/comment/85602617
score: 0
type: Comment
type: QuestionComment
has text: A small example would be very helpful.
comment on: http://stackoverflow.com/q/49300215

http://stackoverflow.com/q/49283334
tagged with: python-xarray
type: AnsweredQuestion
has title: xarray: How to add an array to specific dimension?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49290244
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49290244
type: Question
tagged with: python
tagged with: data-structures
has body: A simple example looks like: arr = xr.DataArray(np.random.rand(2,3,4), coords={'x': ['a', 'b'], 'y': ['c','d', 'e'], 'z': ['f', 'g', 'h', 'i']}, dims=('x', 'y', 'z')) to_add = np.random.rand(3,4) How do I add to_add to coord x in arr with label like a_plus? So the result would look like: &lt;xarray.DataArray (x: 3, y: 3, z: 4)&gt; array([[[0.753333, 0.585982, 0.271593, 0.017763], [0.858164, 0.628703, 0.951855, 0.097232], [0.372766, 0.006932, 0.848118, 0.06778 ]], [[0.935869, 0.517625, 0.841972, 0.116477], [0.161093, 0.449632, 0.640333, 0.578949], [0.613066, 0.315713, 0.227409, 0.853698]], [[0.405509, 0.194987, 0.662878, 0.105522], [0.565623, 0.436369, 0.153299, 0.72756 ], [0.589336, 0.957754, 0.645316, 0.319808]]]) Coordinates: * y (y) |S1 'c' 'd' 'e' * x (x) |S6 'a' 'b' 'a_plus' * z (z) |S1 'f' 'g' 'h' 'i'

http://stackoverflow.com/a/49294194
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/96896591
has body: There are lots of other parameters they are using along with form, they are hidden in the login form, you need to send them too along with your request.
answers question: http://stackoverflow.com/q/49290838
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/96896693
has comment: http://stackoverflow.com/comment/85609552
has comment: http://stackoverflow.com/comment/85609632
has comment: http://stackoverflow.com/comment/96897031

http://stackoverflow.com/comment/85567310
comment on: http://stackoverflow.com/a/49281348
type: Comment
type: AnswerComment
has text: @GokulnathKumar - there is problem `df1` is `Series`, not `DataFrame`
score: 0

http://stackoverflow.com/comment/85594668
score: 0
comment on: http://stackoverflow.com/q/49281520
type: Comment
type: QuestionComment
has text: Haha..True that..

http://stackoverflow.com/a/49432227
answers question: http://stackoverflow.com/q/49432081
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85866205
has body: In your current setup, just re-write your function like this: def ops_on(row): return (row['Feed'] &gt; 10) &amp; (row['Pressure'] &gt; 10) &amp; (row['Temp'] &gt; 10)
has comment: http://stackoverflow.com/comment/85867199
type: Answer
has comment: http://stackoverflow.com/comment/85866142

http://stackoverflow.com/q/49416636
upvote count: 1
has answer: http://stackoverflow.com/a/49416795
favorite count: 0
tagged with: networkx
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/41799844
tagged with: directed-acyclic-graphs
has body: I have a networkx DiGraph (not necessarily acyclic). All nodes have a common predecessor : the source node 0. I want to be able to edit the attributes of all edges, in a breadth first order. To do so, I would like to be able to iterate on ALL edges, starting from source, in a breadth-first manner. bfs_edges allows classic breadth-first search, which leads to the following issue: if a node has n direct predecessors, only one edge will appear in the iterator, instead of n. My edges : ([(0.0, 1), (1, 2), (1, 7), (2, 3), (2, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 7), (6, 7)]) what bfs_edges returns : for edge in nx.bfs_edges(digraph,0): print(edge[0], edge[1]) 0 1 1 2 1 7 2 3 2 4 3 5 3 6 Can anyone help? Thanks!
tagged with: digraphs
score: 1
has title: Networkx: How to iterate on ALL edges of a DiGraph, in a breadth-first manner?
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85600016
type: AnswerComment
has text: Thank You so much
comment on: http://stackoverflow.com/a/49299118
score: 0
type: Comment

http://stackoverflow.com/q/49326824
has body: I'm a student and have a question. I'm not getting the correct output in our textbook. first = 'I' second = 'love' third = 'Python' sentence = first + '' + second + '' + third + '.' Output: I love Python. When I run it, nothing happens. Can someone explain why? Thanks in advance!
has comment: http://stackoverflow.com/comment/85656017
tagged with: python
has comment: http://stackoverflow.com/comment/85655817
has answer: http://stackoverflow.com/a/49327018
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85656121
has answer: http://stackoverflow.com/a/49326907
answer count: 2
tagged with: concatenation
upvote count: 0
type: UnansweredQuestion
has title: Python value assignment does not print
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/85656058
has comment: http://stackoverflow.com/comment/85656165
has comment: http://stackoverflow.com/comment/85655617
has comment: http://stackoverflow.com/comment/85655334

http://stackoverflow.com/a/49299921
score: 64
answers question: http://stackoverflow.com/q/49295311
accepted answer of: http://stackoverflow.com/q/49295311
type: Answer
has comment: http://stackoverflow.com/comment/116971516
has body: That both seem to work doesn't mean they do the same. Flatten will take a tensor of any shape and transform it into a one dimensional tensor (plus the samples dimension) but keeping all values in the tensor. For example a tensor (samples, 10, 20, 1) will be flattened to (samples, 10 * 20 * 1). GlobalAveragePooling2D does something different. It applies average pooling on the spatial dimensions until each spatial dimension is one, and leaves other dimensions unchanged. In this case values are not kept as they are averaged. For example a tensor (samples, 10, 20, 1) would be output as (samples, 1, 1, 1), assuming the 2nd and 3rd dimensions were spatial (channels last).
upvote count: 67
has comment: http://stackoverflow.com/comment/116971597
has comment: http://stackoverflow.com/comment/116966897
type: AcceptedAnswer
downvote count: 3
has comment: http://stackoverflow.com/comment/116971314
has comment: http://stackoverflow.com/comment/116971452
has comment: http://stackoverflow.com/comment/116966912

http://stackoverflow.com/a/49418391
has comment: http://stackoverflow.com/comment/85838553
answers question: http://stackoverflow.com/q/49418346
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85838658
has body: for word in w.split(" "): first_letter = word[0] print(first_letter.upper())
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85838676

http://stackoverflow.com/comment/85642407
score: 0
has text: "it's not working very well": what does that mean? Can you give an minimal example which includes the expected behavior and the actual behavior?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49320727

http://stackoverflow.com/comment/85665300
has text: Put some print() statements for debugging so you can see the progression of the program. I noticed you didn't add any logic to to count replies and check `if done` should be true. Your formatting is still off. Some methods still need indenting. I'll edit with more explanation.
type: AnswerComment
comment on: http://stackoverflow.com/a/49330651
type: Comment
score: 1

http://stackoverflow.com/q/49419858
has comment: http://stackoverflow.com/comment/85841150
tagged with: sendkeys
answer count: 0
downvote count: 0
has body: So I am testing out selenium, and am trying to fill in a simple form online. it just asks for an email, first name, last name, and phone. I got it to input the email (the first text field), but now I cannot seem to get it to get to the next text field. I tried having it press the tab key, but that is not working. Here is the error I am getting, along with the code: def test_search_in_python_org(self): driver = self.driver driver.get(URL) #uses the URL that was generated at the start of the task content = driver.find_element_by_name('EMAIL').send_keys(userEmail) content.send_keys(Keys.TAB) content = driver.find_element_by_name('FNAME') content.send_keys(firstName) #pastes firstname content = driver.find_element_by_name('LNAME') content.send_keys(lastName) #pastes lastname content = driver.find_element_by_name('PHONE') content.send_keys(phone) #pastes phone time.sleep(1000) in terminal: File "raffleBot.py", line 34, in test_search_in_python_org content.send_keys(Keys.TAB) AttributeError: 'NoneType' object has no attribute 'send_keys' Anyone have any suggestions to get the tab key to work? or, on a different route, have selenium simply find the next available text field? Thanks so much in advance
upvote count: 1
tagged with: selenium
favorite count: 0
type: Question
has title: Clicking Tab / Finding next Text Field - Python Selenium
has comment: http://stackoverflow.com/comment/85841270
type: UnansweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/comment/85831858
comment on: http://stackoverflow.com/q/49414915
score: 0
type: Comment
type: QuestionComment
has text: @JohnnyMopp Ahh that makes sense... without updating it always refers to (0,0). Thank you!

http://stackoverflow.com/comment/85564525
has text: If you had commas separating these like in your comment, this is a very straightforward solution
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49280161
type: QuestionComment

http://stackoverflow.com/comment/85578864
has text: @StrikeX To help with the case insensitivity, it's common to convert the search query and a line in your text both to lower case to normalize the casing prior to comparison. Only do this when you're searching, not when you're actually entering the text in the dictionary. This way if you want to display the actual text entered, it's the true text and not the converted lowercase form. Replace the line in the comprehension with: `[v for k,v in my_dict.items() if usr_in.lower() in k.lower()]`
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49287082
type: AnswerComment

http://stackoverflow.com/q/49291681
has answer: http://stackoverflow.com/a/49291815
score: 2
type: AnsweredQuestion
has title: How to replace values in python numpy array in multiple dimensions using a mask?
favorite count: 0
tagged with: numpy
type: Question
upvote count: 2
tagged with: arrays
downvote count: 0
has body: I would like to replace values in a numpy array using boolean logic in dimensions &gt;= 3. All the examples I can find are for 1d or 2d arrays such that you can say something like A[A&gt;.5] = 1. That I understand. I want to do something like this: A[B==0,2 &gt; 128] = 0. Basically, I have a 2D map (B) whose dimensions are the same as the first two in A. So everywhere B == 0 and the third channel (like B of RGB in an image) is greater than 128 I want to set the 3rd channel to zero, leaving the other two channels. I can do this in a loop or doing a for value in array loop, but I was hoping someone could tell me if I could do it in a similar manner to A[A&gt;.5] = 1. I have tried A[B==0,2 &gt; 128] = 0, but I get IndexError: in the future, 0-d boolean arrays will be interpreted as a valid boolean index and I can't really think of any other ways to write this. One thing I forgot to mention - currently I can do A[B==0,2] = 0. I am just trying how to fit that extra conditional in.
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/49291815

http://stackoverflow.com/comment/85806307
type: Comment
score: 0
has text: @user8212173 thanks for suggestion
comment on: http://stackoverflow.com/q/49383376
type: QuestionComment

http://stackoverflow.com/comment/85821556
comment on: http://stackoverflow.com/q/49408994
type: Comment
score: 0
type: QuestionComment
has text: The syntax you are using: `self.fields['sip_extension'].queryset = SipExtension.objects.filter(sip_extension=1331)` looks like something you would do to create a set of related models for the user to choose from. However, you are trying to invoke the same model that is the subject of the form using what looks like an IntegerField, rather than a ForeignKey field. It isn't clear what you are trying to do.

http://stackoverflow.com/q/49290029
has comment: http://stackoverflow.com/comment/85583233
accepted answer: http://stackoverflow.com/a/49290728
answer count: 1
has answer: http://stackoverflow.com/a/49290728
tagged with: databricks
has comment: http://stackoverflow.com/comment/85583199
type: AnsweredQuestion
tagged with: pyspark
has title: How to save dataframe without Column?
tagged with: python
type: Question
score: 0
has body: I have the following DataFrame +--------------------+ | _1| +--------------------+ |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| |{"entry": {"@type...| +--------------------+ only showing top 20 rows Each row contains valid JSON. I would live to save this so that I have a file, preferably JSON, that is just a nest of objects (these rows above). I am however getting a JSON object with {"_1":"{"entry": {"@type...} I would like just {"entry": {"@type...} {"entry": {"@type...} {"entry": {"@type...}
tagged with: apache-spark

http://stackoverflow.com/a/49326907
score: 0
has body: print sentence. Will print the outut But from what you have this will output "IlovePython." not I love Python. This is because ther is no space between your '' tags. To fix this convert all those '' to ' '. Save the last one, which is . as it should be.
has comment: http://stackoverflow.com/comment/85655643
type: Answer
answers question: http://stackoverflow.com/q/49326824

http://stackoverflow.com/q/49340657
downvote count: 0
has answer: http://stackoverflow.com/a/49457568
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
tagged with: filter
answer count: 1
has title: DjangoFilters Add filter from another model
has comment: http://stackoverflow.com/comment/85681998
has body: I modified my DjangoTables class to this class Mark_Table(tables.Table): teacher = tables.Column(accessor='id_subject.id_teacher.name') group = tables.Column(accessor='id_student.id_group.name') course = tables.Column(accessor='id_student.id_group.id_course.course') curator = tables.Column(accessor='id_student.id_group.curator.name') class Meta: model = Mark fields = ['id_student', 'id_subject','mark' ,'teacher', 'group', 'course', 'curator',] attrs = {'class': 'paleblue'} I have filters for it class Mark_Filters(filters.FilterSet): class Meta: model = Mark fields = '__all__' but they work only for fields which are in model Mark. How can i add filters to another models, but in same view. I would like filters to this fields: Teacher. name, Group. name, Course. course, Curator. name, Is there any accessors for filters or something like this. didn`t find anything in DjangoFilters documentation. Thanks in advance My models
score: 1
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/49385349
upvote count: 2
has body: I guess your data looks like this If you just melt the data to each row representing single item-category in a day, you can then use it any kind of union or intersection - df1 = pd.melt(df, id_vars = 'Days', var_name = 'Category') df1 = df1.set_index(['Days', 'Category'])['value'].apply(pd.Series).stack().reset_index().drop('level_2', axis=1) df1.columns = ['Days', 'Category', 'Item'] The code above will turn the data into - Which now can be easily used for any kind of operation
score: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/85773503
accepted answer of: http://stackoverflow.com/q/49384846
type: Answer
has comment: http://stackoverflow.com/comment/85771592
answers question: http://stackoverflow.com/q/49384846

http://stackoverflow.com/comment/85828592
comment on: http://stackoverflow.com/q/49408509
type: Comment
type: QuestionComment
score: 0
has text: @FahimFerdous If you want to know how flask-login does something, read its source code. ☺

http://stackoverflow.com/q/49281822
answer count: 3
tagged with: pandas
score: 7
downvote count: 0
has answer: http://stackoverflow.com/a/49281976
upvote count: 7
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49281976
tagged with: python
has body: df A 0 503.36 1 509.80 2 612.31 3 614.29 I want to round to nearest 5 in a new B column, using numpy if possible. Output should be: A B 0 503.36 505.00 1 509.80 510.00 2 612.31 610.00 3 614.29 615.00
possible better answer: http://stackoverflow.com/a/49281893
has answer: http://stackoverflow.com/a/49281961
has answer: http://stackoverflow.com/a/49281893
type: AnsweredQuestion
has title: Round to nearest 5 with numpy

http://stackoverflow.com/comment/85792544
type: QuestionComment
score: 0
has text: hmm... checking through my old answer again, it looks like I actually covered most of that already.
comment on: http://stackoverflow.com/q/49395066
type: Comment

http://stackoverflow.com/q/49295099
has body: I'm trying to make a server programer. and the code look like this: class ALNHTTPRequestHandler(BaseHTTPRequestHandler): prefix = r'/Users/huxx/PycharmProjects/ServerDemo' # handle GET command def do_GET(self): rootdir = ALNHTTPRequestHandler.prefix # file location try: if self.path.endswith('.html'): finalPath = rootdir + self.path with open(finalPath, 'rb') as f: print('open successed') # send code 200 response self.send_response(200) # send header first self.send_header('Content-type', 'text-html') self.end_headers() # send file content to client a = f.read() self.wfile.write(a) # self.wfile.write(f.read()) return except IOError: print('well not found') self.send_error(404, 'file not foundbbbb') def run(): print('http server is starting...') server_address = ('127.0.0.1', 8011) httpd = HTTPServer(server_address,ALNHTTPRequestHandler) print('http server is running...') httpd.serve_forever() if __name__ == '__main__': run() the problem is if I use self.wfile.write(f.read()) rather than self.wfile.write(a), there's no response at all. Why is that?
answer count: 1
has title: python 3.6 BaseHTTPRequestHandler
tagged with: python
has answer: http://stackoverflow.com/a/49298636
type: AnsweredQuestion
score: 0
tagged with: basehttprequesthandler
type: Question
accepted answer: http://stackoverflow.com/a/49298636
tagged with: python-3.x

http://stackoverflow.com/a/49367908
answers question: http://stackoverflow.com/q/49358407
downvote count: 0
score: 1
upvote count: 1
has body: This tutorial from towardsdatascience is pretty good explaining the usage of the dataset API https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428 Relevant Jupyter notebook https://github.com/FrancescoSaverioZuppichini/Tensorflow-Dataset-Tutorial/blob/master/dataset_tutorial.ipynb
has comment: http://stackoverflow.com/comment/85776686
has comment: http://stackoverflow.com/comment/85775164
has comment: http://stackoverflow.com/comment/85754285
has comment: http://stackoverflow.com/comment/85776031
type: Answer
has comment: http://stackoverflow.com/comment/85775402

http://stackoverflow.com/q/49325050
upvote count: 2
tagged with: seaborn
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85682408
has comment: http://stackoverflow.com/comment/85656378
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85682475
has title: Seaborn BoxPlot and log axis
has comment: http://stackoverflow.com/comment/86610880
tagged with: pandas
has body: I'm facing a problem on ticks since hours now. I would like to plot a boxplot with log scaling but it seems there is 2 issues : Data has no positive values, and therefore cannot be log-scaled. And Attempted to set non-positive xlimits for log-scale axis; invalid limits will be ignored. Her is my code : # Import librairies import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import matplotlib.ticker as ticker # Undersampling the DataFrame through columns because too big sampling_factor = 50 all_frame_inverted_undersampled = all_frame_inverted.take([x for x in range(0,all_frame_inverted.shape[1], sampling_factor)], axis=1) # Settings the canvas fig, ax= plt.subplots(figsize=(18, 6)) ax.set_xlabel('Cycles') ax.set_ylabel('Measures') # setting log axis ax.set_xscale('log') # Plotting g = sns.boxplot(data=all_frame_inverted_undersampled , palette='rainbow', orient="v", ax=ax) # Showing plt.tight_layout() Here is the DataFrame's for the 3 first lines : And here, what I get : I've tried many things like setting : ax.xaxis.set_major_formatter(xmajor_formatter) with LogFormatter I've tried symlog, the error message disapear but the results is quite the same. I tried also : ax.set_xscale('symlog', linthreshy=1e3) EDIT I'm trying to get, on the x axis, ticks formatted as in the plot below : EDIT 2 : Here is a minimal exemple of my code : # Preprocessing and Cleaning data import numpy as np import pandas as pd # Data Visualization import matplotlib.pyplot as plt import matplotlib.ticker as ticker %matplotlib inline # Data Analysis &amp; Visualization import seaborn as sns # Data data= [[181.08, 180.23, 181.60, 178.05, 172.33, 175.50, 169.81, 167.10, 166.92, 166.10, 159.69], [144.94,140.30,140.15,146.07,143.90,143.06,139.74,139.97,144.06,145.13,146.34], [176.25,195.43,217.50,183.75,174.74,169.11,166.81,161.82,164.08,162.25,166.72], [198.31,221.16,214.19,209.06,202.08,180.08,185.79,181.73,178.95,179.53,189.08], [167.81,166.28,144.18,138.22,139.48,144.66,141.3…
tagged with: boxplot
tagged with: python
score: 2
answer count: 0

knitr
type: Tag
tag name: knitr
tags question: http://stackoverflow.com/q/49374546

http://stackoverflow.com/comment/85787844
type: Comment
score: 0
has text: Let me give that a shot
type: QuestionComment
comment on: http://stackoverflow.com/q/49392795

http://stackoverflow.com/comment/85839483
score: 2
comment on: http://stackoverflow.com/a/49418910
type: AnswerComment
type: Comment
has text: To ignore a return value.

max
tags question: http://stackoverflow.com/q/49398208
tags question: http://stackoverflow.com/q/49408230
tags question: http://stackoverflow.com/q/49327692
tags question: http://stackoverflow.com/q/49417191
tags question: http://stackoverflow.com/q/49324892
tags question: http://stackoverflow.com/q/49436598
tag name: max
type: Tag

http://stackoverflow.com/comment/131540986
has text: Well, true. It should be fixed on the PyCharm side in [PY-36444](https://youtrack.jetbrains.com/issue/PY-36444).
type: Comment
comment on: http://stackoverflow.com/a/49335777
score: 2
type: AnswerComment

http://stackoverflow.com/a/49373995
has body: You can access the command line arguments using sys.argv, which is a list of the arguments passed to the script. Here's an example: import sys print(sys.argv) Save this to test.py then execute this program with this command line: # python test.py file.txt ['test.py', 'file.txt'] The first script argument is the name of the python script itself. The second is the first argument. You can use this in your client.py script to set the output file name: import sys if len(sys.argv) &lt; 2: print('Usage: {} output_filename'.format(sys.argv[0]), file=sys.stderr) sys.exit(1) output_filename = sys.argv[1] with open(output_filename, 'wb') as arquivo: ... The length of sys.argv is used to ensure that at least 2 arguments are present; the first being the script name, the second the output filename. Any additional arguments would simply be ignored.
accepted answer of: http://stackoverflow.com/q/49373647
answers question: http://stackoverflow.com/q/49373647
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49374258
has comment: http://stackoverflow.com/comment/85749993
has comment: http://stackoverflow.com/comment/85749942
has comment: http://stackoverflow.com/comment/85749788
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49374020
has body: You can use if statements to find out if the particular integer string is found in the input function. You will use the input function to store the name, but this will automatically evaluate to a string. So, used an if statement to look for any integer (that will be stored as a string in the input function). If any are found, you will get your error message. name = input("Enter your name: ") if '1' in name: print('Wrong') if '2' in name: print('Wrong') if '3' in name: print('Wrong') if '4' in name: print('Wrong') if '5' in name: print('Wrong') if '6' in name: print('Wrong') if '7' in name: print('Wrong') if '8' in name: print('Wrong') if '9' in name: print('Wrong') if '0' in name: print('Wrong') Each time a name is entered, each if statement will check to see if an integer has been stored as a string within the error message. If it is not stored, no error message will occur. If an integer is stored as a string, and error message will occur.
has comment: http://stackoverflow.com/comment/85750447
has comment: http://stackoverflow.com/comment/85750260
has comment: http://stackoverflow.com/comment/85749761

http://stackoverflow.com/comment/85866922
score: 1
type: QuestionComment
has text: Line I said, you need your User model to inherit from AbstractBaseUser.
comment on: http://stackoverflow.com/q/49431528
type: Comment

http://stackoverflow.com/a/49405416
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85812441
has comment: http://stackoverflow.com/comment/85812282
score: 3
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49402740
has body: As long as the dependency is listed in the install_requires list, it will automatically check for that module and if not present it will install it, providing that the module can be installed from PyPi. If not (where that package cannot be found on PyPi) you get a Could not find a version that satisfies the requirement error. I could not find any packages with this name on PyPi so you need to add the dependency to be installed on PyPi to be installed via pip, if you host your package elsewhere (GitHub for example) this may provide a solution: How can I make setuptools install a package that&#39;s not on PyPI?. Running pip install commonpylib returns Could not find a version that satisfies the requirement commonlib (from versions: ) No matching distribution found for commonpylib So you do not have a setup script problem but a problem with finding the package on PyPi (which does not seem to exist), or at least Python does not know where you have hosted it. The other option is to integrate that package with what you are distributing without making it a dependency (i.e. add it to the __init__.py file ect).
accepted answer of: http://stackoverflow.com/q/49402740

http://stackoverflow.com/comment/85877088
has text: You could also create a set of last names for t1 and t2 then take the intersection of that and then compare the first names for each intersecting last name.
comment on: http://stackoverflow.com/a/49436340
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85626672
has text: The question is tagged python 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49312424
score: 0
type: Comment

http://stackoverflow.com/a/49339078
answers question: http://stackoverflow.com/q/49338432
accepted answer of: http://stackoverflow.com/q/49338432
type: Answer
has comment: http://stackoverflow.com/comment/85678651
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I am not sure what exactly you are asking for. But I would suggest, next time try to ask a question that is easily produce-able and runnable by other people here in SO. I have tried to answer your questions. Correct me if I misunderstand your question. Pass arbitrary number of DataFrame to your function and plot it: I have created three random dataframes for use: df1 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB')) df2 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB')) df3 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB')) The functions that plots them: def plot_me(*kwargs): plt.figure(figsize=(13,9)) lab_ind = 0 for i in kwargs: plt.plot(i['A'], i['B'], label = lab_ind) lab_ind += 1 plt.legend() plt.show() The result plot you get: Put the results of your model into a DataFrame Regarding your second question, I am not going to concentrate too much on your exact details - for example the name of the columns of your dataframe, etc. For this particular example I have generated two random arrays: X = np.random.randint(0,50 ,size=(50, 2)) y = np.random.randint(0,2 ,size=(50, 1)) Then fit a LinearRegression model on this data. model=LinearRegression().fit(X,y) predictions=model.predict(X) And then add it to a DataFrame: res_df = pd.DataFrame(predictions,columns = ['Value']) And if you print res_df Value 0 0.420395 1 0.459389 2 0.369648 3 0.416058 4 0.644088 5 0.362072 6 0.363157 7 0.468943 . . . .

http://stackoverflow.com/q/49344761
upvote count: 0
has comment: http://stackoverflow.com/comment/85689640
downvote count: 2
tagged with: grouping
has comment: http://stackoverflow.com/comment/85690210
has comment: http://stackoverflow.com/comment/85690046
has answer: http://stackoverflow.com/a/49344847
has comment: http://stackoverflow.com/comment/85689916
favorite count: 0
type: Question
has title: Grouping up adjacent elements together in python
has answer: http://stackoverflow.com/a/49344880
type: UnansweredQuestion
score: -2
has body: Given a list like this, where first column is the id and second is a string, [ [2, ["00_01_02"]], [1, ["00_03_04"]], [3, ["00_03_04"]], [6, ["00_03_04"]], [4, ["01_02_03"]], [5, ["01_02_03"]], ] As you can see there are adjacent elements that are the same. For example, the id 1,3 and 6 have the same string so I would like to group them up into another list. Same goes for id 5 and 4. We can also assume that the list is in sorted order by the string. I would like to solve this problem in O(NC) if possible, where N is the number of element in the list, C is the number of characters in the string. Example output would be something like, [ [[1,3,6], ["00_03_04"]], [[4,5] , ["01_02_03"]] ]
tagged with: python
has comment: http://stackoverflow.com/comment/85689686
has comment: http://stackoverflow.com/comment/132328071
has answer: http://stackoverflow.com/a/49345850
tagged with: list
answer count: 3

http://stackoverflow.com/q/49407267
has comment: http://stackoverflow.com/comment/85816333
favorite count: 0
type: Question
tagged with: python-3.x
has title: Regex to extract group of 2 numbers
upvote count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/85816484
tagged with: python
has comment: http://stackoverflow.com/comment/85815663
downvote count: 4
answer count: 1
has body: How do I write a regex to extract 0, 78, 87 digits out the string of "07887"? The output should look like this: ['0','78','87'] (The rule is 1st number will be the single digit and following 4 digits should be grouped in group of 2)
has answer: http://stackoverflow.com/a/49407709

http://stackoverflow.com/comment/85833314
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49415559
has text: how did you install pyserial?
score: 1

http://stackoverflow.com/a/49454916
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49396600
has body: I do not understand why this works, but if I add a filter_path to the query, it returns as quickly as the raw curl: es = Elasticsearch(["es-host:9200"]) results = es.search(index="some_index", doc_type="some_type", filter_path=['hits.hits._id'], body={"query": {"term": {"day": "2018_02_04"}}} ) If anyone has an explanation for this behavior, I'd appreciate that.
type: Answer
has comment: http://stackoverflow.com/comment/85940669
answers question: http://stackoverflow.com/q/49396600
score: 1

http://stackoverflow.com/a/49308938
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49300248
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49300248
has body: I chose to list channels instead of listing subscriptions, passing the same argument mySubscribers. The documentations says it's deprecated and gives them back in a weird order with duplicates but it does not have a limit.
has comment: http://stackoverflow.com/comment/119288219
has comment: http://stackoverflow.com/comment/112558669

http://stackoverflow.com/a/49355384
type: Answer
answers question: http://stackoverflow.com/q/49355335
downvote count: 0
upvote count: 1
score: 1
has body: You are very close. A couple of small changes: Code: def student_grade(filename): with open(filename, 'rU') as file: grade_dict = {} for line in file: name = line.strip().split(' ') grade_dict[name[0]] = np.array(name[1:]) return grade_dict The filename passed to open() is a variable, not a string so filename not "filename". Test Code: print(student_grade('file1')) Results: {'John': array(['23', '53', '54', '56', '58'], dtype='&lt;U2'), 'Jane': array(['89', '54', '56', '76', '93'], dtype='&lt;U2'), 'Marie-Claire': array(['56', '68', '76', '86', '92'], dtype='&lt;U2') }

http://stackoverflow.com/q/49425737
has comment: http://stackoverflow.com/comment/85852444
accepted answer: http://stackoverflow.com/a/49430460
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49430460
possible better answer: http://stackoverflow.com/a/49426312
has comment: http://stackoverflow.com/comment/85852400
has comment: http://stackoverflow.com/comment/85852562
has answer: http://stackoverflow.com/a/49426312
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85852449
answer count: 2
has body: I have a question as i write on title. I'll explain it with examples. There is a txt file which is looks like, This offense was closed with reason: Non-Issue. Notes: There is no suspicious situation. u0t9231 21 Mar 2018 10:38:46 This offense was closed with reason: Non-Issue. Notes: Expected traffic. u0t9231 21 Mar 2018 14:20:11 I want to read that txt file and I want to write to another file that will contain just part of "Notes: There is no suspicious situation." So input, This offense was closed with reason: Non-Issue. Notes: There is no suspicious situation. u0t9231 21 Mar 2018 10:38:46" Output, Notes: There is no suspicious situation
upvote count: 0
has title: How can i collect specific words in a sentences on Python?
has comment: http://stackoverflow.com/comment/85852496
tagged with: python
score: -1

http://stackoverflow.com/comment/85868989
has text: This is cleaner than what I suggested. If you don't have a way to remove on generation (e.g. if graph is in an awkward file format) then do it this way!
comment on: http://stackoverflow.com/a/49428652
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85588992
comment on: http://stackoverflow.com/a/49293214
type: Comment
type: AnswerComment
has text: Excuse me，do if and else have to be used together ？
score: 0

http://stackoverflow.com/comment/85704521
type: Comment
type: QuestionComment
has text: Hmm, this was actually good advice as it prevented me from problems later down the road -my K value was the only denominator, and had a minimum value of 0- though this did not fix my issue.
comment on: http://stackoverflow.com/q/49351985
score: 0

http://stackoverflow.com/a/49414575
downvote count: 0
answers question: http://stackoverflow.com/q/49413830
has body: Yes, you can either read it from memory: from rasterio.io import MemoryFile with MemoryFile(data) as memfile: with memfile.open() as dataset: data_array = dataset.read() Or directly from a URL: with rasterio.open('https://pathto.tif') as dataset: print(dataset.profile) I couldn't get the latter to work with your URL though so you may want to try the first.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49413830
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/a/49353557
accepted answer of: http://stackoverflow.com/q/49353463
answers question: http://stackoverflow.com/q/49353463
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: First, the missing function is a C++ mangled name. Most compilers nowadays come with tools to demangle, or you can use an online demangler like this one, which works for all not-too-ancient versions of clang++, g++, and MSVC. The result is _std::string::_Rep::_S_empty_rep_storage. This is pretty clearly part of the C++ standard library. The problem is that you've compiled some code to use C++ std::string, but haven't linked the C++ stdlib. It's not your Cython-generated code, or Python, so presumably it's that libLexActivator.a. The easy fix for this is to have Cython compile all of your code as C++ instead of C, by adding language="c++" in your cythonize call. This is a little more extreme than you need, but it's probably fine. Alternatively, you can just pick the right C++ stdlib and link to that. That's a bit confusing with clang on the Mac, because there are two of them, libc++ and libstdc++. Recent versions default to the former (libc++ is a newer implementation, built by the LLVM/Clang team, to work better with C++11 and later). But if you're building for 10.6, I'm not sure whether that's still right. So you may have to research it (or ask experts on the C++, Mac, and Clang related tags), or just try both and see. From your comments, after you fix that, you get another missing symbol, _kSCPropNetProxiesHTTPPort. That distinctive naming style almost certainly means it's a constant exported by something either inside Apple's CoreFoundation framework, or one of the other C frameworks sitting on top of it. But don't guess, just paste it in your favorite search engine, and you'll find the docs, which show that it's part of the SystemConfiguration framework. So, you need to add that to the build as well. At this point, it's pretty clear that libLexActivator.a isn't just simple C/POSIX code; it's got some platform dependencies (and it may have third-party dependencies too, for all I know) that it needs to link against. So, the best thing to do is to find its document…
type: Answer

request
tags question: http://stackoverflow.com/q/49400189
tag name: request
type: Tag
tags question: http://stackoverflow.com/q/49308917
tags question: http://stackoverflow.com/q/49415480
tags question: http://stackoverflow.com/q/49396292
tags question: http://stackoverflow.com/q/49386920

http://stackoverflow.com/q/49371776
has comment: http://stackoverflow.com/comment/85747790
score: 2
type: AnsweredQuestion
has title: Eliminate borders for automatic license plate recognition
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85748081
tagged with: image-processing
has comment: http://stackoverflow.com/comment/85748912
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85748853
has answer: http://stackoverflow.com/a/49374311
has body: Im working on a ALPR system, from the binarization part the images endup with a border that prevent the OCR to get the correct values. As in this image: How can I delete the black border an get only the characters? EDIT. This is the input: That's the quality of the images.
accepted answer: http://stackoverflow.com/a/49374311
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/comment/85858169
type: Comment
type: AnswerComment
has text: If another SO post answers this question you should close the question and not answer with a link to another question
comment on: http://stackoverflow.com/a/49428480
score: 0

http://stackoverflow.com/comment/85865973
score: 0
has text: Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49432072

http://stackoverflow.com/comment/85755926
type: Comment
has text: Thank yo very much. That was it, I forced it to UTF-8 encoding in Edit | Current File Preferences | Encoding. I apologize for posting the question in this forum. I failed at realizing the problem was caused by Komodo, I thought it was python having problems with the special characters and komodo was just signaling the problem. sorry and thank you very much.
comment on: http://stackoverflow.com/a/49366775
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85643490
comment on: http://stackoverflow.com/q/49321247
type: QuestionComment
score: 3
has text: Y u need to define the variable. Just use `COLOURS.get(key)` to access the value?
type: Comment

http://stackoverflow.com/comment/85691618
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49344575
score: 0
has text: To be more clear i am able to destroy it without having class,

http://stackoverflow.com/comment/85679935
type: QuestionComment
score: 0
has text: yes, just added to the question above
comment on: http://stackoverflow.com/q/49339600
type: Comment

http://stackoverflow.com/comment/85605006
has text: That seemed to work. If you move it below, I'll mark it as the answer. Thanks!
comment on: http://stackoverflow.com/q/49301479
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49323348
tagged with: matplotlib
tagged with: python
has title: How to specify gridspec location by numbers?
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/49323919
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/76267897
favorite count: 0
has answer: http://stackoverflow.com/a/76267897
has body: I read the instruction in Customizing Location of Subplot Using GridSpec and try out the following codes and got the plot layout: import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(3, 3) ax1 = plt.subplot(gs[0, :]) ax2 = plt.subplot(gs[1, :-1]) ax3 = plt.subplot(gs[1:, -1]) ax4 = plt.subplot(gs[-1, 0]) ax5 = plt.subplot(gs[-1, -2]) I understand that gridspec.GridSpec(3, 3) will give a 3*3 layout, but what it means for gs[0, :] gs[1, :-1] gs[1:, -1] gs[-1, 0] gs[-1, -2]? I look up online but not found a detailed expanation, and I also try to change the index but not found a regular pattern. Could anyone give me some explanation or throw me a link about this?
tagged with: matplotlib-gridspec
accepted answer: http://stackoverflow.com/a/49323919
type: Question
tagged with: subplot

http://stackoverflow.com/q/49380884
type: Question
has comment: http://stackoverflow.com/comment/85852572
has comment: http://stackoverflow.com/comment/85790940
has comment: http://stackoverflow.com/comment/85801310
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85791045
tagged with: python-2.7
tagged with: imagemagick
tagged with: wand
has comment: http://stackoverflow.com/comment/85790904
has body: I'm developing on Windows10 x64 and Python 2.7.14 I have to collect scanned JPEG images into a single compressed TIFF file. I tried Pillow image library with libtiff but it corrupted the resulting tiff file whichever compression algorithm I set. Without compression algorithm it produces a 100 MBs of non corrupted tiff file. Then I found Image Magick command line tool and it worked well with compression. It compressed a 100 MBs uncompressed tiff file into a 7 MBs jpeg compressed tiff file. magick.exe -compress jpeg *.jpg abc.tif It is really hard to get permission to run a third party exe on our servers. So I decided to use it as a library in my Python application and found Wand library. Now the problem is that Wand library does not compress the result tiff file. How can I produce a compressed tiff file with Wand library? Below is what I end up with: import os from wand.image import Image imagepaths = [] folder = "d:/scan/" for file in os.listdir(folder): if file.endswith(".jpg") or file.endswith(".jpeg"): imagepaths.append(os.path.join(folder, file)) with Image() as img: img.sequence.extend( [ Image(filename=f, resolution=300) for f in imagepaths] ) img.compression = "jpeg" img.compression_quality = 50 # these two lines have no effect, no compression is done img.save(filename="d:/scan/wand_converted.tif") # this generates a tiff file with about 100 MBs of size # When I convert jpegs to tiff with magick at command line it produces a 7 MBs file
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: windows-10
favorite count: 0
has title: convert multiple jpeg images to one compressed tiff image with wand library

http://stackoverflow.com/comment/85715223
comment on: http://stackoverflow.com/a/49317156
score: 0
type: Comment
has text: can you help me to solve this. https://stackoverflow.com/questions/49355891/how-to-calculate-quarterly-wise-churn-and-retention-rate-using-python
type: AnswerComment

http://stackoverflow.com/comment/85631547
comment on: http://stackoverflow.com/q/49315079
score: 2
type: Comment
type: QuestionComment
has text: How about `round(xxx.amount)`?

datefield
tags question: http://stackoverflow.com/q/49319153
tag name: datefield
type: Tag

http://stackoverflow.com/q/49427683
type: Question
has answer: http://stackoverflow.com/a/49429379
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49429987
has comment: http://stackoverflow.com/comment/85858506
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I am plotting the following data: myDates = ['2017-05-17', '2017-05-24', '2017-05-25', '2017-05-26', '2017-05-27', '2017-05-29', '2017-05-31', '2017-06-01', '2017-06-03', '2017-06-04', '2017-06-05', '2017-06-06', '2017-06-07', '2017-06-08', '2017-06-10', '2017-06-11', '2017-06-12', '2017-06-13', '2017-06-15', '2017-06-16', '2017-06-17', '2017-06-18', '2017-06-19', '2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23', '2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27', '2017-06-28', '2017-06-29', '2017-06-30', '2017-07-01', '2017-07-02', '2017-07-04', '2017-07-05', '2017-07-07', '2017-07-08', '2017-07-10', '2017-07-13', '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18', '2017-07-19', '2017-07-20', '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-31', '2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04', '2017-08-06', '2017-08-07', '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11', '2017-08-12', '2017-08-14', '2017-08-15', '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19', '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23', '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27', '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31', '2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04', '2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08', '2017-09-10', '2017-09-11', '2017-09-12', '2017-09-13', '2017-09-14', '2017-09-15', '2017-09-16', '2017-09-17', '2017-09-18', '2017-09-19', '2017-09-20', '2017-09-21', '2017-09-22', '2017-09-23', '2017-09-24', '2017-09-25', '2017-09-26', '2017-09-27', '2017-09-28', '2017-09-29', '2017-09-30', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08', '2017-10-09', '2017-10-10', '2017-10-12', '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16', '2017-10-18', '2017-10-19', '2017-10-20', '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28', '2017-10-30', '2017-10-…
downvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/49427920
favorite count: 0
has title: Python3: matplotlib.pyplot.plot_date() date labels overrunning
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49427920
accepted answer: http://stackoverflow.com/a/49429379

http://stackoverflow.com/comment/86709523
type: AnswerComment
comment on: http://stackoverflow.com/a/49290086
has text: (sorry for the unaccept, but the other answer provides an even better improvement)
score: 0
type: Comment

http://stackoverflow.com/comment/85841331
comment on: http://stackoverflow.com/q/49419931
score: 0
type: Comment
has text: `is it poor practice to duplicate the Singleton metaclass definition in both files, like ` Yes. Repeating yourself is never a good thing.
type: QuestionComment

http://stackoverflow.com/comment/85682904
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49341357
has text: Super interesting problem. I doubt it has anything to do with it, but can you add a Content-type header?

http://stackoverflow.com/q/49287498
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85578379
upvote count: 0
type: UnansweredQuestion
has title: Create new lines in output text - Python
tagged with: newline
tagged with: python
has answer: http://stackoverflow.com/a/49287604
score: -1
has comment: http://stackoverflow.com/comment/85578080
tagged with: syntax-error
has body: I'm writing a code in Python IDLE 3.6 that prints out a user's name in their own choice of style and colour and everything is working fine apart from this. Somehow it won't print out the three highlighted lines underneath each other and I've tried multiple methods but they all keep ending up with unexpected character after line continuation character. Please help? if style == ":": if colour == "Red" or "red": cat.write(( ":" * (len(name) + 4)), "stderr") cat.write((":", name, ":"), "stderr") cat.write((":" * (len(name) + 4)), "stderr")
answer count: 1
tagged with: console.writeline

http://stackoverflow.com/comment/85901109
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49437335
has text: @jcbridwe Are you sure you have this comment in the right place? If so I am confused by what problem you are still facing.

firefox
type: Tag
tags question: http://stackoverflow.com/q/49346601
tags question: http://stackoverflow.com/q/49407518
tag name: firefox
tags question: http://stackoverflow.com/q/49406625
tags question: http://stackoverflow.com/q/49345838
tags question: http://stackoverflow.com/q/49429403

http://stackoverflow.com/q/49359903
accepted answer: http://stackoverflow.com/a/49360177
answer count: 1
has answer: http://stackoverflow.com/a/49360177
tagged with: web-scraping
tagged with: python-requests
has title: How to select only one tag to fill date frame in a scrape?
type: Question
tagged with: pandas
has body: In Python 3, I need to scrape tables on a website: from bs4 import BeautifulSoup import requests import pandas as pd res = requests.get("http://portal.stf.jus.br/processos/listarPartes.asp?termo=paulo%20salim%20maluf") soup = BeautifulSoup(res.text, "lxml") parts = soup.find_all('table', {'class': 'table m-b-0'}) print(parts) [ Identificação Número Único Data Autuação Meio Publicidade Inq 138 0000344-45.1983.0.01.0000 29/04/1983 Físico Público Inq 170 0000243-71.1984.0.01.0000 23/03/1984 Físico Público Inq 202 0000199-18.1985.0.01.0000 26/02/1985 Físico Público Inq 228 0001497-45.1985.0.01.0000 04/11/1985 Físico Público Inq 229 0001526-95.1985.0.01.0000 11/11/1985 Físico Público AP 449 0004490-89.2007.0.01.0000 14/08/2007 Físico Público Inq 351 0001562-69.1987.0.01.0000 09/09/1987 Físico Público Inq 1430 0004092-60.1998.0.01.0000 04/12/1998 Físico Público Inq 1644 0002280-12.2000.0.01.0000 27/06/2000 Físico Público Inq 1249 0003249-66.1996.0.01.0000 18/11/1996 Físico Público Inq 1268 0003587-40.1996.0.01.0000 20/12/1996 Físico Público Inq 2518 0001854-53.2007.0.01.0000 16/04/2007 Físico Público Inq 1901 0000494-25.2003.0.01.0000 12/02/2003 Físico Público Inq 2469 0000746-86.2007.0.01.0000 21/02/2007 Físico Público Inq 1837 0002951-64.2002.0.01.0000 16/08/2002 Físico Público Rcl 2980 0004831-23.2004.0.01.0000 23/11/2004 Físico Público Rcl 2984 0004822-61.2004.0.01.0000 23/11/2004 Físico Público Pet 2188 0003954-25.2000.0.01.0000 14/11/2000 Físico Público Rcl 3338 0002065-60.2005.0.01.0000 18/05/2005 Físico Público Pet 3923 0001447-47.2007.0.01.0000 23/03/2007 Físico Público Pet 3891 0000957-25.2007.0.01.0000 05/03/2007 Físico Público Pet 3960 0002077-06.2007.0.01.0000 26/04/2007 Físico Público Pet 4466 0006782-13.2008.0.01.0000 07/11/2008 Físico Público Pet 4132 0004655-39.2007.0.01.0000 23/08/2007 Físico Público Pet 4133 0004636-33.2007.0.01.0000 23/08/2007 Físico Público Rcl 4899 0000244-50.2007.0.01.0000 18/01/2007 Físico Público MS 26863 0004617-27.2007.0.01.0000…
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85710438
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49355010
type: Comment
has text: This question may be related: https://stackoverflow.com/questions/3274334/how-can-i-watch-a-file-for-modification-change

subprocess
tags question: http://stackoverflow.com/q/49408302
tag name: subprocess
tags question: http://stackoverflow.com/q/49314298
tags question: http://stackoverflow.com/q/49320423
tags question: http://stackoverflow.com/q/49349338
type: Tag
tags question: http://stackoverflow.com/q/49394705
tags question: http://stackoverflow.com/q/49380965
tags question: http://stackoverflow.com/q/49418049
tags question: http://stackoverflow.com/q/49310057
tags question: http://stackoverflow.com/q/49428562
tags question: http://stackoverflow.com/q/49285316
tags question: http://stackoverflow.com/q/49321796
tags question: http://stackoverflow.com/q/49386696
tags question: http://stackoverflow.com/q/49351396
tags question: http://stackoverflow.com/q/49401435
tags question: http://stackoverflow.com/q/49371575
tags question: http://stackoverflow.com/q/49340955
tags question: http://stackoverflow.com/q/49381646
tags question: http://stackoverflow.com/q/49426656
tags question: http://stackoverflow.com/q/49347339
tags question: http://stackoverflow.com/q/49421699
tags question: http://stackoverflow.com/q/49390930
tags question: http://stackoverflow.com/q/49310206
tags question: http://stackoverflow.com/q/49365950

http://stackoverflow.com/comment/85597058
has text: Thank you very much,It solved the problem
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49282546
type: QuestionComment

http://stackoverflow.com/comment/85774796
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49353954
has text: It is not possible to show you how to fix your code, as what you have given does not run.

http://stackoverflow.com/comment/85582096
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49289426
has text: But even if the script is called with `./some_name.py`, calling it with `python some_name.py` (as long as you use the right Python in the shbang line—which you will, because that's what will be in `sys.executable`), it will still do the right thing. His version works for _both_ `./some_name.py` and `python some_name,py` (and also `pypy3.5 some_name.py` and so on); yours only works for the first one.
type: Comment

http://stackoverflow.com/q/49360770
accepted answer: http://stackoverflow.com/a/49384216
answer count: 1
tagged with: facebook-oauth
tagged with: django
has body: I am using inside django: social-auth-app-django and python-social-auth[django]. In settings.py I have declared the following variables: SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {'fields': 'name, email'} Everything works ok. But I want to set the SOCIAL_AUTH_FACEBOOK_KEY and the SOCIAL_AUTH_FACEBOOK_SECRET dynamic before every request for social auth, in an middleware or decorator. Why I want this is, because my django app is serving data for multiple sites, and every site has is own keys, and his own domain. I can't find a way to overwrite the variables in settings, or to send the keys to social_auth.
type: Question
type: AnsweredQuestion
tagged with: django-socialauth
has answer: http://stackoverflow.com/a/49384216
tagged with: python
tagged with: python-social-auth
has title: Set dynamic keys/secret for python-social-auth, before every request used for social auth
score: 0

http://stackoverflow.com/comment/85582705
type: QuestionComment
has text: @Tim I implemented your idea in a [CW post](https://stackoverflow.com/a/49289794/4909087). No rep will come to me for it. Nice idea.
comment on: http://stackoverflow.com/q/49289685
score: 0
type: Comment

http://stackoverflow.com/comment/85581653
type: Comment
type: QuestionComment
has text: Did you try `df.reset_index().plot(x="b",y="c")`?
comment on: http://stackoverflow.com/q/49289179
score: 0

http://stackoverflow.com/comment/85704580
type: Comment
comment on: http://stackoverflow.com/q/49352146
has text: When does knowing whether something is a dict or a list really tell you anything? If it's expecting a dict mapping user names to connection objects and you pass it a dict mapping file names to file objects, that's no better than passing it a list. You can tell that it wants a map of user names to connections by the function name, the parameter name, the docstring, the comments, the API docs, and the unit tests. Or, if you can't, you'd be just as screwed in C++ as in Python.
score: 3
type: QuestionComment

http://stackoverflow.com/comment/85626564
has text: Can you add the function definition of `csv2xml()` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49310014
type: Comment
score: 0

http://stackoverflow.com/a/49313182
accepted answer of: http://stackoverflow.com/q/49303835
type: Answer
answers question: http://stackoverflow.com/q/49303835
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Lets say you have [("key", [13,445]), ("key", [14,109]), ("key", [15,309])] When this is passed to reduceByKey, it will group all the values with same key into one executor i.e. [13,445], [14,109], [15,309] and iterates among the values In the first iterate x is [13,445] and y is [14,109] and the output is max(x[1], y[1]) i.e. max(445, 109) which is 445 In the second iterate x is 445 i.e. max of previous loop and y is [15,309] Now when the second element of x is tried to be obtained by x[1] and 445 is just an integer, the error occurs TypeError: 'int' object is not subscriptable I hope the meaning of the error is clear. You can find more details in my other answer The above explanation also explains why the solution proposed by @pault in the comments section works i.e. reduceByKey(lambda x, y: (x[0], max(x[1], y[1])))

http://stackoverflow.com/a/49310239
accepted answer of: http://stackoverflow.com/q/49310204
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: The problem is that you're using input. In Python 2, input asks for input, and then tries to evaluate it as Python code. So, when you type in 8 9 3 2 7 5, it tries to evaluate that as Python code—and of course that's not valid Python syntax. What you want to do is use raw_input, which just asks for input and returns it to your code as a string. You can then call split() on it and get a list of strings. When you move to Python 3, this problem goes away—input just returns a string. Meanwhile, just putting the result of split() in brackets doesn't do much good. You end up with a list, whose one element is another list, whose elements are the split strings. So you probably just want: A = raw_input().split() If you need to convert each string into an int, you have to call int on each one. You can do this with a list comprehension: A = [int(numeral) for numeral in raw_input().split()] … or map: A = map(int, raw_input().split()) … or an explicit loop: A = [] for numeral in raw_input().split(): A.append(int(numeral)) If you don't understand the first two, use the last one until you can figure out how they work. Concise, readable code is very important, but code that you can understand (and debug and maintain and extend) is even more important.
score: 4
answers question: http://stackoverflow.com/q/49310204

http://stackoverflow.com/q/49386423
tagged with: server
type: UnansweredQuestion
has body: I have tried to start server with Django project like this: python3.4 manage.py runserver 0.0.0.0:8000 and like this: python3.4 manage.py runserver my_domain.com:8000 and it starts fine but I can't visit my site. Any ideas what I've done wrong?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85779772
has title: Can't connect to django website started on VPS
score: 0
has comment: http://stackoverflow.com/comment/85774089
has answer: http://stackoverflow.com/a/49389390
answer count: 1
type: Question

http://stackoverflow.com/q/49343690
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85699305
tagged with: python
has comment: http://stackoverflow.com/comment/85699247
linked to: http://stackoverflow.com/q/17675925
has answer: http://stackoverflow.com/a/49350034
downvote count: 0
has comment: http://stackoverflow.com/comment/85687850
score: 1
upvote count: 1
has title: Removing EOF error from int(input()) python 3?
answer count: 1
has comment: http://stackoverflow.com/comment/85687763
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm trying to make a pattern in HackerRank and as far as I can tell, my solution works. size = int(input()) letters = 'abcdefghijklmnopqrstuvwxyz' for i in range(size): textp = "-".join(letters[size - 1: size - (1 + i): -1]) textn = "-".join(letters[size - i: size: 1]) print(textp.rjust(size + 2, '-') + '-' + letters[size - (1 + i)] + '-' + textn.ljust(size + 2, '-')) for i in range(size - 2, -1, -1): textp = "-".join(letters[size - 1: size - (1 + i): -1]) textn = "-".join(letters[size - i: size: 1]) print(textp.rjust(size + 2, '-') + '-' + letters[size - (1 + i)] + '-' + textn.ljust(size + 2, '-')) prints out: --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- But when I try to submit it I get File "solution.py", line 12, in &lt;module&gt; n = int(input()) EOFError: EOF when reading a line I'm new to python so I'm not sure how to resolve this error. The code works fine and I don't understand why the input() function is messing up.
has comment: http://stackoverflow.com/comment/85687831

http://stackoverflow.com/comment/86174985
score: 0
type: AnswerComment
has text: Yours and answer by Tomas look promising. And, I hadn’t had time to test it. I will do it tomorrow. I like the idea of reassignment. For now about `As long as you can fit .... in memory twice` - why not 3 times, 4 times? I was also thinking if there is a way to create the list as interator, generator or yield and pass it to `Pool.map()` process. Any suggestions?
comment on: http://stackoverflow.com/a/49506903
type: Comment

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/49290207
tags question: http://stackoverflow.com/q/49407797
type: Tag

http://stackoverflow.com/q/49288384
accepted answer: http://stackoverflow.com/a/49288494
has body: I am trying to loop through a list of coins using this code: coin = ["BTC", "NEO", "ETH"] for item in coin: try: term = urllib.parse.quote("'" + coin + "-BTC'") depth = client.get_order_book(term, limit=50) except (KucoinAPIException, KucoinRequestException, KucoinResolutionException) as e: print(e) pass and I receive the error: TypeError: must be str, not list What's the most efficient way to accomplish this? Do I have to split up my list? Thank you!
upvote count: 1
has comment: http://stackoverflow.com/comment/85579983
answer count: 1
has title: put variable in quotes from a list loop?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85580028
tagged with: python
tagged with: variables
downvote count: 6
has comment: http://stackoverflow.com/comment/85580179
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49288494
tagged with: list
score: -5

http://stackoverflow.com/comment/85755298
comment on: http://stackoverflow.com/q/49354201
has text: You need to use more specific selector instead of `driver.find_elements_by_tag_name('img')` to fetch only several required images
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85765469
has text: @J.Riesmeier Good points, I will mend the answer where deemed necessary. It's true that there are other issues in the file, but I chose to address the main concern of recovering the pixel data into an array.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49369212

http://stackoverflow.com/comment/85582657
has text: I'm using Spyder @cᴏʟᴅsᴘᴇᴇᴅ
comment on: http://stackoverflow.com/q/49289685
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49437238
upvote count: 1
answers question: http://stackoverflow.com/q/49436664
has body: Disclaimer I will provide you with the easiest (at least what I think is) solution to this. After you have fully understood it, you may go ahead and deploy fancier stuff. My answer is meant to be a guide and you are responsible for the code. Edit I: Sorry I missed a point. You want to grayscale your image first. The most common initial stage to this problem is cleaning out the noise. Depending on your application though, this can be an optional initial stage. There are different operations you can perform to help you get rid of the unnecessary stuff. Thereafter, you can find the edges of the less noisy image. This helps us see an outline of the image. From here, you start looking for contours inside our edges image. At this point now, we have attained contours and it is time to run this and/or this analysis on them to see if we can pinpoint our desired one. The simplest initial analysis can be removing/ignoring contours whose area is smaller than a certain threshold. Once you have observed the results, go ahead and maybe combine the area with something else like the aspect ratio and see what you get. After some trial and error, we have managed to isolate the desired contour, you can go ahead and draw a bounding rect around it. Two Cents: Just like CNN model creation, image processing is a trial and error task. For each of the different methods I have listed above, you have to try out different parameters and see which one makes sense. There are other alternatives you can use instead. Say instead of finding edges, maybe you can try thresholding the image, or maybe smooth out the image right after gray scaling it. Cheers, happy coding :)
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/49307166
has body: It's not saying there is no __repr__ method; it's saying the value used for this placeholder has no attribute named __repr__(). The format string is not an arbitrary Python expression. "{0.foo}".format(x) is roughly the same as str(x.foo), not str(x).foo.
accepted answer of: http://stackoverflow.com/q/49306985
type: Answer
answers question: http://stackoverflow.com/q/49306985
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49297254
has comment: http://stackoverflow.com/comment/85611459
downvote count: 0
answer count: 1
has body: Consider this code from abc import ABCMeta, abstractmethod class C(): @abstractmethod def my_abstract_method(self): print('foo') class D(C): pass x = C() y = D() Neither x nor y is allowed by mypy yielding me a test.py:13: error: Cannot instantiate abstract class 'C' with abstract attribute 'my_abstract_method' test.py:15: error: Cannot instantiate abstract class 'D' with abstract attribute 'my_abstract_method' I'm testing this with mypy 0.570 and python 3.6.3 However, the documentation says that I'd need to set metaclass=ABCMeta for that to work. What am I missing?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: abc
has answer: http://stackoverflow.com/a/49303838
has title: @abstractmethod works just fine without metaclass=ABCMeta when it shouldn't
has comment: http://stackoverflow.com/comment/85597955
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/85648458
has comment: http://stackoverflow.com/comment/85597595

http://stackoverflow.com/comment/85603331
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49300672
has text: @JBernardo My understanding is that there is no way to keep the arguments and have j incremented ?

http://stackoverflow.com/comment/85720764
has text: but why if we write `with open('txtfile.txt', 'w') as f:` at the tope of code the output file will be empty?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49360080
type: AnswerComment

http://stackoverflow.com/comment/85588086
score: 0
has text: thank you! super efficient and it works! a question: how does this method ensure the reading sequence is 55, 44, 33, 22, 11? (just afraid it miss-kills)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49292763

http://stackoverflow.com/comment/85729164
has text: Once again, with what you posted here, running exact `pivot` code (fixing missing single quote at end), there are some non-NA values. And be careful with `.dropna`. Per the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), it drops if **any** NAs are present. Pass in `how='all'` and no columns are dropped for me.
type: Comment
comment on: http://stackoverflow.com/q/49323159
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85865714
score: 0
type: AnswerComment
has text: Alex - thanks again for providing the code, I still can't get the script to work properly after hours and hours of editing and trying. Just to reiterate the process I'm trying to get working - I want to load firefox webdriver, go to the URL, apply all the java - load the final page - send this to scrapy and paginate through the filtered (by selenium) results - not sure if I made that clear. I'm struggling to understand - I can get as far as parsing but keep getting errors such as 'url' not defined from the selenium_response = Selector(..) Could you try running your code to debug please? thanks
comment on: http://stackoverflow.com/a/49381759
type: Comment

http://stackoverflow.com/q/49320251
upvote count: 0
answer count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85642424
has comment: http://stackoverflow.com/comment/85641342
has title: C++ error: cast from ‘int*’ to ‘int’ loses precision
tagged with: ubuntu
favorite count: 0
has comment: http://stackoverflow.com/comment/85641639
has comment: http://stackoverflow.com/comment/85641393
type: Question
tagged with: g++
has comment: http://stackoverflow.com/comment/85641358
has comment: http://stackoverflow.com/comment/85642425
has comment: http://stackoverflow.com/comment/85642584
score: -2
has comment: http://stackoverflow.com/comment/85641948
tagged with: python
has body: I started learning C++ a few days ago. I want to compile this example program in order to embed Python in C ++. The C++ program is: #include &lt;Python.h&gt; #include &lt;iostream&gt; #define pi 3.141592653589793 using namespace std; int main () { //Inicio el interprete Python e imprimo informacion relevante Py_Initialize(); PyObject *FileScript; FileScript = PyFile_FromString("script.py","r"); PyRun_SimpleFile(PyFile_AsFile(FileScript),"r"); PyObject *retorno, *modulo, *clase, *metodo, *argumentos, *objeto; int *resultado; modulo = PyImport_ImportModule("script"); clase = PyObject_GetAttrString(modulo, "Numeros"); argumentos = Py_BuildValue("ii",5,11); objeto = PyEval_CallObject(clase, argumentos); metodo = PyObject_GetAttrString(objeto, "suma"); argumentos = Py_BuildValue("()"); retorno = PyEval_CallObject(metodo,argumentos); PyArg_Parse(retorno, "i", &amp;resultado); cout&lt;&lt;"Result is: "&lt;&lt;int(resultado)&lt;&lt;endl; Py_Finalize(); char terminar; cin&gt;&gt;terminar; return 1; } and python script "script.py" is: class Numeros: def __init__(self, num1, num2): self.num1=num1 self.num2=num2 def suma(self): print self.num1, self.num2 return self.num1+self.num2 I´m using Ubuntu with G++ installed. I type this to compile: g++ -I/usr/include/python2.7 -lpython2.7 main.cpp -o main But I get this error: main.cpp:27:42: error: cast from ‘int*’ to ‘int’ loses precision [-fpermissive] cout&lt;&lt;"Result is: "&lt;&lt;int(resultado)&lt;&lt;endl; How can I solve it? Tank you very much!
has answer: http://stackoverflow.com/a/69567142
has comment: http://stackoverflow.com/comment/85642984
tagged with: c++
has answer: http://stackoverflow.com/a/49321104

http://stackoverflow.com/a/49408015
has comment: http://stackoverflow.com/comment/85820021
has comment: http://stackoverflow.com/comment/85820103
has body: Change __init__(self, *args, **kwargs) to __init__(self, _, *args, **kwargs): &gt;&gt;&gt; Foo(Something()).create() Creating &gt;&gt;&gt; Foo(Something()).do_something() Do somthing I honestly don't see the problem here. Or why you want to supply an instance of Something when creating an instance of Foo, but there you go.
score: 0
has comment: http://stackoverflow.com/comment/85818335
type: Answer
answers question: http://stackoverflow.com/q/49407788

http://stackoverflow.com/a/49413032
answers question: http://stackoverflow.com/q/49412685
type: Answer
accepted answer of: http://stackoverflow.com/q/49412685
has body: I think I can fix your problem, even though I can't reproduce it. There's a logic error: after you write, you fail to return to the start of the file for reading. In terms of analysis, you failed to do anything to diagnose the problem. At the very least, use a print statement to see what you're reading: that highlights the problem quite well. Here's the loop I used: count = 0 while count&lt;=num: file_obj.seek(0) # Read from the beginning of the file. read = file_obj.read() print(count, read) # Trace what we're reading. file_obj.seek(0, 2) file_obj.write(read) count+=1 This gives the expected output of 128 (2^(6+1)) repetitions of "hello". EXTENSIONS I recommend that you learn to use both the for loop and the with open ... as idiom. These will greatly shorten your program and improve the readability.
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85927994
type: AnswerComment
comment on: http://stackoverflow.com/a/49421808
score: 0
type: Comment
has text: although I am told not to use `eval()`, so far, this is the first solution which is satisfying my requirements.

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/49392370

http://stackoverflow.com/comment/85631609
type: Comment
score: 0
type: QuestionComment
has text: `closure` gets called with the x and y coordinates of the click, you'll need to modify the function definition so it will accept these two extra arguments. `def closure(x, y):`
comment on: http://stackoverflow.com/q/49314269

http://stackoverflow.com/comment/126394942
comment on: http://stackoverflow.com/q/49436155
type: QuestionComment
has text: A one-time workaround is to download the notebook: `File` -> `Download as` -> `Notebook (.ipnb)`, and move the file to the desired location.
score: 0
type: Comment

http://stackoverflow.com/a/49384627
has body: try replacing the method `checking_name ' ... def checking_name(self): firstname = str(self.lineEdit.text()).lower() lastname = str(self.lineEdit_2.text()).lower() b=os.listdir(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image') #for e in b: if (firstname in b) and firstname: if (lastname in b) and lastname: os.remove(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image\{}'.format(lastname)) self.showMessageBox('Warning','{} Image is deleted'.format(lastname)) self.lineEdit.setText("") self.lineEdit_2.setText("") else: self.showMessageBox('Warning','firstname != lastname') else: self.showMessageBox('Warning', 'Cannot find the `{}` image, please check if your typing is correct'\ .format(firstname)) ...
score: 0
answers question: http://stackoverflow.com/q/49379069
type: Answer

http://stackoverflow.com/q/49321065
has comment: http://stackoverflow.com/comment/85643107
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85646816
has comment: http://stackoverflow.com/comment/85643373
tagged with: pandas
has comment: http://stackoverflow.com/comment/85643822
answer count: 1
downvote count: 1
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85648250
has title: Python df error (pandas)
favorite count: 0
has body: I'm having an issue with this code: import pandas as pd import quandl quandl.ApiConfig.api_key = 'MYAPIKEY' df = quandl.get('WIKI/GOOGL') df = df'Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume' df['HL_OCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0 df['HL_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0 df = df'Adj. Close', 'HL_PCT','PCT_change','Adj. Volume' print(df.head()) The error I'm getting is: File "regression.py", line 11, in &lt;module&gt; df = df'Adj. Close', 'HL_PCT','PCT_change','Adj. Volume' File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2133, in __getitem__ return self._getitem_array(key) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2177, in _getitem_array indexer = self.loc._convert_to_indexer(key, axis=1) File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1269, in _convert_to_indexer .format(mask=objarr[mask])) KeyError: "['HL_PCT' 'PCT_change'] not in index" I'm not quite sure why it's not working. I've installed Pandas, Quandl and skLearn using pip. I'm running this on my ubuntu vm if that helps.. Any help is greatly appreciated! :) UPDATE: Running this import pandas as pd import quandl df = quandl.get('WIKI/GOOGL') df = df'Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume', print(df.head()) produces this output, so the columns are definitely there! Adj. Open Adj. High Adj. Low Adj. Close Adj. Volume Date 2004-08-19 50.159839 52.191109 48.128568 50.322842 44659000.0 2004-08-20 50.661387 54.708881 50.405597 54.322689 22834300.0 2004-08-23 55.551482 56.915693 54.693835 54.869377 18256100.0 2004-08-24 55.792225 55.972783 51.945350 52.597363 15247300.0 2004-08-25 52.542193 54.167209 52.100830 53.164113 9188600.0 &gt;&gt;&gt; EDIT: Seems like I've fixed this myself. I'm not sure how, but now when running import pandas as pd import quandl df = quandl.get('WIKI/GOOGL') df = df[['Adj. Open',…
has answer: http://stackoverflow.com/a/49323494
type: Question
tagged with: python-3.x
upvote count: 0

http://stackoverflow.com/a/49296948
downvote count: 0
has comment: http://stackoverflow.com/comment/85616326
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85628868
has body: Decorator should create new function that "replace" original function. def my_decorator(some_function): print("Something is happening before some_function() is called.") some_function() print("Something is happening after some_function() is called.") This "decorator" return None -> just_some_function = None -> TypeError: 'NoneType' object is not callable def my_decorator(some_function): def wrapper(): print("Something is happening before some_function() is called.") some_function() print("Something is happening after some_function() is called.") return wrapper This "decorator" return wrapper -> just_some_function = wrapper -> It's work. You also can check. Try print(just_some_function.__name__) -> "wrapper".
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49296780
upvote count: 2
has comment: http://stackoverflow.com/comment/85639400
answers question: http://stackoverflow.com/q/49296780

http://stackoverflow.com/a/49341775
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49341706
has body: What I will do .. df.apply(lambda x : (x-x.min())/(x.max()-x.min()))
has comment: http://stackoverflow.com/comment/85683654
has comment: http://stackoverflow.com/comment/85684095
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49341706
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85683808
has comment: http://stackoverflow.com/comment/85683966

http://stackoverflow.com/comment/85787737
has text: I don't know the API for the lib, or how you're using it, but… if you just create a file, wrap an exporter around it, keep it open until the end, close it at shutdown, and never write to that file again, it should be pretty easy—just add the `[\n` in `__init__` and `]\n` in `close`. If you need to reopen and append to the same file repeatedly, that's a bit more complicated, and you'd probably want to do it out of band instead of as part of the exporter.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49391892
score: 0

http://stackoverflow.com/q/49439850
has answer: http://stackoverflow.com/a/49439930
tagged with: os.path
type: UnansweredQuestion
has body: I'm trying to save the results of a model estimation to a file. I have tried a number of things but it doesn't work because I'm obviously not doing it correctly. I'm not even sure os.path.join is the right command from os.path: #output the vectors for winsize=5 and features=10 study1_path = os.path.join("/Users/dlhoffman/Study 1/") print(study1_path) /Users/dlhoffman/Study 1/ ifttt_model.wv.save_word2vec_format("study1_path/vectors.txt", binary=False, total_vec=None) Since I have to estimate this model a number of times and I'd like to save some brute force typing, I'd also like to label each output file with the values of the hyperparameters winsize and features. The file name I would like to get for say, winsize=5 and features=10 are: /Users/dlhoffman/Study 1/5w10fvectors.txt So in the above case, the "5" and the "10" come from the values of the variables winsize and features. I've studied the examples &amp; the os.path module documentation, but don't know enough python to get what I should do. Any ideas?
downvote count: 0
has answer: http://stackoverflow.com/a/55180682
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49439926
tagged with: filenames
score: 1
tagged with: python
answer count: 4
type: Question
has title: using os.path to write output files with variable names
has answer: http://stackoverflow.com/a/49459943

http://stackoverflow.com/q/49324282
has title: Use tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq with tensorflow 1.5 case 'TypeError: can't pickle _thread.lock objects'
linked to: http://stackoverflow.com/q/44855603
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85665499
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/54872600
tagged with: seq2seq
tagged with: python
has body: Use tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq with tensorflow 1.5 case 'TypeError: can't pickle _thread.lock objects', this issue is the same as https://github.com/suriyadeepan/practical_seq2seq/issues/31 I use the way someone post: change the code of tf in embedding_rnn_seq2seq function encoder_cell = copy.deepcopy(cell) =&gt; encoder_cell = copy.copy(cell) Is it the right way to fix this issue? Or is there any other way to fix this. the API of tf make me mess, change so frequently， tf.nn.rnn_cell, tf.contrib.seq2seq, tf.legacy_seq2seq kill me!!
has comment: http://stackoverflow.com/comment/85650066
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49331012
favorite count: 0
type: Question
has title: Unable to get new line in a .txt with python running on Ubuntu server
has comment: http://stackoverflow.com/comment/85664729
has comment: http://stackoverflow.com/comment/85664061
tagged with: newline
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/85664082
has answer: http://stackoverflow.com/a/49331110
accepted answer: http://stackoverflow.com/a/49331110
type: AnsweredQuestion
score: 0
upvote count: 1
tagged with: carriage-return
has body: I have a server running ubuntu 14.04. I transferred my code files from my local computer to the server, but I can't run my program correctly because of this part of my code: for _ in range(5): some = "some" stuff = "stuff" list_1 = open('text.txt', 'a') list_1.write("%s %s \n" %(some, stuff)) open('text.txt', 'a').close() when I run it, the output is : some stuffsome stuffsome stuffsome stuffsome stuff I can't understand why because if I run it on my local computer the output is: some stuff some stuff some stuff some stuff some stuff that's really weird, any ideas?
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85664097

http://stackoverflow.com/comment/85741342
type: QuestionComment
has text: That's what I want the answer for. How can I implement PHP(client) and Python(server) in such a way that I don't need to pass data through arguments.? One way might be to daemonize the Python script (as I read while researching) but I am not sure how to do this and pass data to this python script from PHP(client) side.
comment on: http://stackoverflow.com/q/49369356
score: 0
type: Comment

http://stackoverflow.com/comment/85745900
score: 0
type: Comment
has text: @BallpointBen Yes exactly.
type: QuestionComment
comment on: http://stackoverflow.com/q/49372237

http://stackoverflow.com/comment/85733991
type: Comment
type: AnswerComment
has text: You should consider the use of `itertools.chain` instead of `sum`, which is much slower
score: 0
comment on: http://stackoverflow.com/a/49366642

http://stackoverflow.com/comment/85741798
comment on: http://stackoverflow.com/q/49369814
has text: Removing [tag:sas] as this has nothing to do with the SAS language itself, adding [tag:enterprise-guide] instead.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/112672824
comment on: http://stackoverflow.com/q/49394941
has text: I have answered to this question here: https://stackoverflow.com/questions/49084143/opencv-live-stream-video-over-socket-in-python-3/63717263#63717263
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85823616
has text: the error becomes : ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49410882
type: Comment

http://stackoverflow.com/q/49434799
type: Question
type: UnansweredQuestion
has body: I have a module common_analysis_tools.py that I use in multiple Python projects. These projects are set up as repositories on GitHub so that I can share them with collaborators (I work in a research science environment, not a development environment). When it comes to packaging my code should the common_analysis_tools be included in each repository (e.g. as a submodule or some other way), or should I just have a separate repository for the common_analysis_tools and list this package as a dependency of my other projects? (I'm sorry if this is answered elsewhere - I have searched old posts, but haven't found an answer - if this isn't the case I'm happy for someone to point me in the right direction! Thanks!)
tagged with: python
has comment: http://stackoverflow.com/comment/85872927
answer count: 0
has comment: http://stackoverflow.com/comment/85872901
has title: Common python modules required by multiple repositories: should I package as submodules or just list as dependency?
score: 1
has comment: http://stackoverflow.com/comment/85872771
downvote count: 0
has comment: http://stackoverflow.com/comment/85872649
has comment: http://stackoverflow.com/comment/85871520
upvote count: 1
tagged with: github
favorite count: 0
tagged with: git

http://stackoverflow.com/q/49396695
type: UnansweredQuestion
has title: Convert float number into binary
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85795211
has comment: http://stackoverflow.com/comment/85795192
has body: import struct def print_binary(number_string): bin = "" if "." in number_string: number_string = float(number_string) bin += bin(struct.unpack('!i',struct.pack('!f', number_string))) else: num = int(number_string) bin += "{0:b}".format(num) print(bin) I'm having trouble with converting a number with a decimal in it to binary (my if statement) test_values = "0 1234 -1234 12.4 0.6 -12.4 -0.6 -1234567890.123456789".split() I get an error when it gets up to 12.4
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85796162
has comment: http://stackoverflow.com/comment/85797340
downvote count: 1
has comment: http://stackoverflow.com/comment/85795173
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49397544
has comment: http://stackoverflow.com/comment/85795203

http://stackoverflow.com/q/49379200
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85760266
tagged with: github
tagged with: jupyter-notebook
duplicate of: http://stackoverflow.com/q/38132862
type: Question
type: UnansweredQuestion
has body: I am working on a project where I have a Jupyter notebook file named 'Investigating_Database.ipynb'. As you open this file on GitHub you see a 'Table of Contents' section at the top followed by links which refer inside that notebook file, but as you click on those links, it doesn't work. I have tried to give links both in HTML5 and Markdown but none of it works. But the links work fine on Jupyter Notebook. I have searched and tried many different syntaxes but none work. Has anyone encountered this problem before and debugged it successfully or it's just a bug or not supported by GitHub?
has title: How to give bookmark links in Jupyter Notebook that work on GitHub?
tagged with: python
has comment: http://stackoverflow.com/comment/85759212
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/38132862

http://stackoverflow.com/comment/85783028
type: Comment
type: QuestionComment
has text: This is probably more of a CentOS admin question than a Python programming question, so you should probably ask on whichever SE site is appropriate for that. (Also, I suspect you'll need to specify which version of CentOS.)
comment on: http://stackoverflow.com/q/49390749
score: 0

http://stackoverflow.com/a/49342028
has comment: http://stackoverflow.com/comment/85684212
answers question: http://stackoverflow.com/q/49341964
has comment: http://stackoverflow.com/comment/85684559
type: Answer
has comment: http://stackoverflow.com/comment/85684517
upvote count: 3
score: 3
has body: It sounds like you need a set of categories: categories = [{'category': 'Phones'}, {'category': 'Phones'}, {'category': 'Phones'}, {'category': 'Phones'}, {'category': 'Phones'}, {'category': 'Soaps'}] # use a set to eliminate the duplicate categories c = set(d['category'] for d in categories) print(list(c)) Output: ['Soaps', 'Phones'] Update: c = {d['category'] for d in categories} # equivalent using a set comprehension
has comment: http://stackoverflow.com/comment/85684245
has comment: http://stackoverflow.com/comment/85684606
downvote count: 0

http://stackoverflow.com/comment/85789101
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49373439
has text: Allen, I might have like 10 columns with userid as unique and any one of the 9 columns value can change ( not just title). In this case how do we handle the 'changed' value field.
type: QuestionComment

http://stackoverflow.com/q/49293169
type: Question
linked to: http://stackoverflow.com/q/15839555
type: UnansweredQuestion
tagged with: python
has body: There are already a couple of question on Python's .pyc files but I have not read about 1) when (in what circumstances) are these files created and 2) whether there is a good reason to keep them. More specifically: About (1): In 200 or more PY files (new and old ones) that I have run, I have seen only a couple of .pyc files created. However, in Python's own (installation) directory there are currently 1160 .pyc files, about half of the .py files! I don't know how many of them existed already on Python's installation, but about 450 of them have been certainly created after that. So, it's a mystery to me in what circumstances these files are created. Or are they always automatically created and then they are supposed to be deleted after the PY program terminates? About (2): I have compared the execution timing .py against .pyc files and I cannot see any (significant) difference. I don't have large .py files or .py files with heave computations, etc. to test. But as far as "regular" files (small to medium size and with regular computations) are concerned, the .pyc files seem to be certainly useless. So, why should one keep them? ... Later: I just realized that a .pyc file is created only when its corresp. .py file is used as a module, i.e. it is imported. OK, there's so meaning in this! :)
has answer: http://stackoverflow.com/a/49293223
downvote count: 0
score: 7
upvote count: 7
linked to: http://stackoverflow.com/q/2998215
answer count: 1
has comment: http://stackoverflow.com/comment/85588749
has title: Python: When are .pyc files created?
favorite count: 0

http://stackoverflow.com/q/49436155
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85880201
has comment: http://stackoverflow.com/comment/126394942
answer count: 5
has comment: http://stackoverflow.com/comment/94219583
tagged with: windows
has answer: http://stackoverflow.com/a/49442035
linked to: http://stackoverflow.com/q/46272880
has comment: http://stackoverflow.com/comment/85879371
tagged with: python
has answer: http://stackoverflow.com/a/61025151
has comment: http://stackoverflow.com/comment/85881203
tagged with: jupyter-notebook
type: Question
has answer: http://stackoverflow.com/a/61513746
has comment: http://stackoverflow.com/comment/85878929
has comment: http://stackoverflow.com/comment/85881146
upvote count: 5
score: 5
has title: Jupyter notebook error Windows 10
linked to: http://stackoverflow.com/q/42648610
has answer: http://stackoverflow.com/a/54244887
possible better answer: http://stackoverflow.com/a/54244887
linked to: http://stackoverflow.com/q/43248141
accepted answer: http://stackoverflow.com/a/49442035
downvote count: 0
has comment: http://stackoverflow.com/comment/85881381
has answer: http://stackoverflow.com/a/54979909
has body: Problem: Jupyter is not able to save, create (I imagene delete) any file type. But I can load them fine An example of creating file Creating File Failed An error occurred while creating anew file. ''' Unexpected error while saving file: untitled.txt [Errno 2] No such file or directory: 'C:\Users\me\Documents\jupyter_notebooks\untitled.txt' ''' An example of saving file C:\WINDOWS\system32&gt;jupyter notebook [I 17:15:51.888 NotebookApp] JupyterLab beta preview extension loaded from c:\users\me\appdata\local\programs\python\python35\lib\site-packages\jupyterlab [I 17:15:51.888 NotebookApp] JupyterLab application directory is c:\users\me\appdata\local\programs\python\python35\share\jupyter\lab [I 17:15:52.091 NotebookApp] Serving notebooks from local directory: C:\Users\me\Documents\jupyter_notebooks [I 17:15:52.091 NotebookApp] 0 active kernels [I 17:15:52.091 NotebookApp] The Jupyter Notebook is running at: [I 17:15:52.091 NotebookApp] http://localhost:8888/?token=*******************************01d1a67a61 [I 17:15:52.091 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 17:15:52.127 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=*******************************01d1a67a61 [I 17:15:52.472 NotebookApp] Accepting one-time-token-authenticated connection from ::1 [I 17:16:01.628 NotebookApp] Kernel started: 77255bad-ad7a-4714-8221-1dd90a3a34b5 [W 17:16:11.656 NotebookApp] Timeout waiting for kernel_info reply from 77255bad-ad7a-4714-8221-1dd90a3a34b5 [I 17:16:25.646 NotebookApp] Adapting to protocol v5.0 for kernel 77255bad-ad7a-4714-8221-1dd90a3a34b5 [I 17:16:26.160 NotebookApp] Saving file at /jupyter_jupyter_lab.ipynb [E 17:16:26.543 NotebookApp] Error while saving file: jupyter_jupyter_lab.ipynb [Errno 2] No such file or directory: 'C:\\Users\\me\\Documents\\jupyter_notebooks\\.~jupyter_jupyter_lab.ipynb' Tried: Still the …
tagged with: controlled-folder-access

http://stackoverflow.com/comment/85706945
comment on: http://stackoverflow.com/q/49353337
type: Comment
type: QuestionComment
score: 1
has text: Please give a [mcve]. If nothing else, your indentation is wrong as posted.

http://stackoverflow.com/q/49302663
tagged with: bash
answer count: 2
has answer: http://stackoverflow.com/a/49302804
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49302773
has comment: http://stackoverflow.com/comment/85607504
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49302773
has comment: http://stackoverflow.com/comment/85607181
type: AnsweredQuestion
tagged with: cron
score: 1
linked to: http://stackoverflow.com/q/36885909
tagged with: python
has body: I try to set up a cron job to execute a python test program (rm a file from folder) but it doesn't work. I've tried different things : - Run programm with script sh - Run action directly with command in crontab When I launch test.sh from terminal, it works perfectly. When I launch rm file directly in crontab command it works too BUT nothing happens when the script sh is launched from crontab... This is my cron tab : */5 * * * * run_auto_resp_ads.sh 37 14 * * * test.sh 18 14 * * * rm ~/Rendu/test_cron/lol.py This is test.sh content : #!/bin/sh rm ~/Rendu/test_cron/lol2.py When I check my cron logs, task are running : Mar 15 14:21:01 AcerA17 CROND[14905]: (mjz) CMD (test.sh) Mar 15 14:18:01 AcerA17 CROND[12944]: (mjz) CMD (rm ~/Rendu/test_cron/lol.py) I've also checked files rights. Any ideas please ? Thx a lot :)
has comment: http://stackoverflow.com/comment/85607431
has title: Cron job with script sh is not executed but job is running in cron log
possible better answer: http://stackoverflow.com/a/49302804
duplicate of: http://stackoverflow.com/q/36885909

http://stackoverflow.com/a/67619181
answers question: http://stackoverflow.com/q/49320412
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: With TornadoVM [1], you can write Java code to be offloaded to GPUs via OpenCL and/or CUDA PTX. And the Java code can be invoked from any PL on top of GraalVM, including Python, Javascript, R, etc [2, 3]. [1] https://github.com/beehive-lab/TornadoVM [2] https://github.com/jjfumero/qconlondon2020-tornadovm/tree/master/nodejs [3] https://github.com/jjfumero/nyjavasig-tornadovm-2021/blob/master/python/mxmWithTornadoVM.py

web
tags question: http://stackoverflow.com/q/49392032
tags question: http://stackoverflow.com/q/49384608
tag name: web
tags question: http://stackoverflow.com/q/49392485
tags question: http://stackoverflow.com/q/49402212
type: Tag
tags question: http://stackoverflow.com/q/49352865
tags question: http://stackoverflow.com/q/49311344
tags question: http://stackoverflow.com/q/49341670

http://stackoverflow.com/q/49408762
favorite count: 0
type: Question
answer count: 2
upvote count: 0
has body: How do i find out what format the data i am trying to request is in? The data can be found in the following address: https://api.coinmarketcap.com/v1/ticker/ Thank you :)
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/49408821
has title: Python requests, how to know what format data is in?
downvote count: 1
has answer: http://stackoverflow.com/a/49408821
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49408813
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49408813

http://stackoverflow.com/q/49434727
has title: How to run function in python on background and still continue the main flow?
answer count: 0
has comment: http://stackoverflow.com/comment/85871464
has body: I currently create website with Flask. After user sign up, i want to send mail &amp; execute insert into sql, but it run slow, so i want to execute it on background and still continue the main flow and return the html without stuck on loading page. def send_email_and_insert(): # some smtplib code here # and some insert into sql too # this function make the web stuck loading 5-10 second @app.route('/sign_up/') def sign_up(): # some code here send_email_and_insert() return render_template('thanks_for_sign_up.html') I think it can be done with multiprocessing or threading, but i cant get it right. or maybe there is another solution?
has comment: http://stackoverflow.com/comment/85871312
has comment: http://stackoverflow.com/comment/85874245
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85871504
score: 0

http://stackoverflow.com/q/49323124
answer count: 1
favorite count: 0
type: Question
tagged with: command-line
linked to: http://stackoverflow.com/q/2881025
has comment: http://stackoverflow.com/comment/85647988
upvote count: 2
tagged with: timezone
has body: I can manually check whether it is daylight saving or not. But is there a way to check this using command line or a program (e.g., python)?
score: -3
accepted answer: http://stackoverflow.com/a/49323554
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49323554
type: AnsweredQuestion
has title: how to test if the time is daylight saving or not using command line?

http://stackoverflow.com/a/49376971
has comment: http://stackoverflow.com/comment/85755582
type: Answer
has comment: http://stackoverflow.com/comment/85755024
has comment: http://stackoverflow.com/comment/85754766
accepted answer of: http://stackoverflow.com/q/49376781
answers question: http://stackoverflow.com/q/49376781
has comment: http://stackoverflow.com/comment/85755726
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85755570
has body: Use pandas to easily do this thing. import pandas as pd df = pd.read_csv('your_dataset_file.csv', sep=',', header=0) # Sort it according to tenure df.sort_values(by=['tenure'], inplace=True) # Create bin edges step_size = int(df.tenure.max()/4) bin_edges = list(range(0,df.tenure.max()+step_size, step_size)) lbls = ['a','b','c','d'] df['bin'] = pd.cut(df.tenure,bin_edges, labels= lbls) # Create separate dataframes from it df1 = df[df.bin == 'a'] df2 = df[df.bin == 'b'] df3 = df[df.bin == 'c'] df4 = df[df.bin == 'd']

google-forms
type: Tag
tag name: google-forms
tags question: http://stackoverflow.com/q/49433198

http://stackoverflow.com/comment/85732670
has text: You never had a loop, encase that `Y` check in a while loop and break out when they say `N`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49365194

http://stackoverflow.com/comment/85870031
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49430954
has text: No because there isn't even a core number attached to each task to begin with. See the question and answers linked by BoarGules.
score: 0

http://stackoverflow.com/a/49350813
has body: you could do it using pandas for example, and you wouldnt need to deal with different lists 0 1 2 0 apples 1.00 11 1 grape 1.20 1 2 chocolate 0.75 15 3 bananas 1.35 27 import pandas df = pandas.read_csv(csv_file_path, header=None) df.loc[df[0] == "apples", 2] = new_stock the [0] and 2 can be changed by the name of the columns if you add column names to the file
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49350510

http://stackoverflow.com/a/49365410
type: Answer
has body: Yes you can convert np.nan to string "NaN" in the data frame. But a better and faster way is to give pandas a proper parameter when reading in the excel file, specifying what value should be mapped to nan and what should not. When you are calling read_excel function, you are using the default value of na_values parameter. According to the document, it converts values ["", "#N/A", "#N/A N/A", "#NA", "-1.#IND", "-1.#QNAN", "-NaN", "-nan", "1.#IND", "1.#QNAN", "N/A", "NA", "NULL", "NaN", "n/a", "nan", "null"] into np.nan. Therefore, you can pass in your own na_values list without string "NaN" in it, then you will see "NaN" as string in your dataframe.
answers question: http://stackoverflow.com/q/49362591
score: 0

http://stackoverflow.com/comment/85789481
type: AnswerComment
comment on: http://stackoverflow.com/a/49393055
has text: It's very bad practice to do `from numpy import *`. It's best if you import the package with an alias: `import numpy as np`, then use `np` to access the functionality of NumPy.
type: Comment
score: 0

http://stackoverflow.com/a/49346311
type: Answer
has comment: http://stackoverflow.com/comment/85818175
accepted answer of: http://stackoverflow.com/q/49346253
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: This problems is a binary segmentation problem. In a sense you learn a mapping from satellite images and predict for each pixel, iff this pixel is part of the road. A simple algorithm to do this would be to check if the pixel color is part of some range. A CNN naturally will learn you a more complicated function based on the local neighborhood of said pixel. One repo to get you started should be this one: https://github.com/jocicmarko/ultrasound-nerve-segmentation. Therein they use a similar algorithm to segment ultrasound images using CNNs. You just have to use 3 input channels instead of 1 and everything else should be quite similar.
answers question: http://stackoverflow.com/q/49346253
has comment: http://stackoverflow.com/comment/85798531
score: 1

http://stackoverflow.com/comment/85683384
type: AnswerComment
comment on: http://stackoverflow.com/a/49341505
score: 1
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ community wiki: classy. BTW if OP is using python 2 the result will be incorrect.

http://stackoverflow.com/comment/85622811
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49309522
has text: If you really want to get fancy, you can `import sys` and use [`sys._getframe().f_code.co_name`](https://stackoverflow.com/a/13514318/3579910) to programmatically pull the function name... although that's probably overkill depending on the size of the project.
type: Comment

vst
type: Tag
tag name: vst
tags question: http://stackoverflow.com/q/49435923

http://stackoverflow.com/a/49440751
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49439303
has body: It looks like the problem is in the line output = tf.matmul (11,output_layer['weights']) + output_layer['biases'] Replace it with output = tf.matmul (l1,output_layer['weights']) + output_layer['biases'] and the particular error you're seeing should go away.
type: Answer
has comment: http://stackoverflow.com/comment/86005364
accepted answer of: http://stackoverflow.com/q/49439303
type: AcceptedAnswer

http://stackoverflow.com/a/49317312
type: Answer
answers question: http://stackoverflow.com/q/49312989
has comment: http://stackoverflow.com/comment/105346768
has comment: http://stackoverflow.com/comment/105346897
has comment: http://stackoverflow.com/comment/105346741
has comment: http://stackoverflow.com/comment/105346838
has comment: http://stackoverflow.com/comment/85658842
has body: You are computing the gradients respect to X_train, which is not an input variable to the computation graph. Instead you need to get the symbolic input tensor to the model, so try something like: grads = K.gradients(model.output, model.input)
has comment: http://stackoverflow.com/comment/85658811
downvote count: 0
has comment: http://stackoverflow.com/comment/85659695
accepted answer of: http://stackoverflow.com/q/49312989
has comment: http://stackoverflow.com/comment/94627261
score: 5
has comment: http://stackoverflow.com/comment/105346867
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/49328235
tagged with: pandas
has comment: http://stackoverflow.com/comment/85658420
tagged with: python
possible better answer: http://stackoverflow.com/a/79418853
has comment: http://stackoverflow.com/comment/111821978
has answer: http://stackoverflow.com/a/59649235
has comment: http://stackoverflow.com/comment/85658366
type: Question
has title: Int too large to convert to C long while doing .astype(int)
tagged with: numpy
has body: I'm running a python script, where I have to convert a string column from a pandas df to int, using the astype(int) method. However, I get this following error: "Python int too large to convert to C long" My strings are all numbers in string format, up to 15 characters. Is there a way to convert this column to int type without this popping this error?
score: 20
has answer: http://stackoverflow.com/a/49329034
downvote count: 3
upvote count: 23
favorite count: 0
has answer: http://stackoverflow.com/a/79418853
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49329034
has comment: http://stackoverflow.com/comment/85658344
answer count: 3

http://stackoverflow.com/comment/85661218
has text: masterfloda has the right answer v to the survival question, but really this isn't an appropriate use of recursion. Just loop until you get a value entry; this will also avoid the need for nested functions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49329445
score: 1

http://stackoverflow.com/comment/85665264
type: AnswerComment
score: 0
has text: Is there a way to not make it unordered? @davedw
type: Comment
comment on: http://stackoverflow.com/a/49331535

http://stackoverflow.com/q/49380224
answer count: 1
downvote count: 1
tagged with: getattr
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49380669
accepted answer: http://stackoverflow.com/a/49380669
score: 6
linked to: http://stackoverflow.com/q/12101574
tagged with: pickle
tagged with: python
has title: how to make classes with __getattr__ pickable
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/42272335
has body: How can I modify the classes below to make them pickeable? This question: How to make a class which has __getattr__ properly pickable? is similar but refer to wrong exception in the use of getattr. This other question seems to provide meaningful insight Why does pickle.dumps call __getattr__?, however it fails to provide an example, and I honestly cannot understand what I am suppose to implement. import pickle class Foo(object): def __init__(self, dct): for key in dct: setattr(self, key, dct[key]) class Bar(object): def __init__(self, dct): for key in dct: setattr(self, key, dct[key]) def __getattr__(self, attr): """If attr is not in channel, look in timing_data """ return getattr(self.foo, attr) if __name__=='__main__': dct={'a':1,'b':2,'c':3} foo=Foo(dct) dct2={'d':1,'e':2,'f':3,'foo':foo} bar=Bar(dct2) pickle.dump(bar,open('test.pkl','w')) bar=pickle.load(open('test.pkl','r')) Results: 14 """If attr is not in channel, look in timing_data 15 """ ---&gt; 16 return getattr(self.foo, attr) 17 18 if __name__=='__main__': RuntimeError: maximum recursion depth exceeded while calling a Python object
upvote count: 7

http://stackoverflow.com/a/49354693
type: Answer
has body: This is a one-liner in Python: def findLetters(myList, myString): return set(myString) &lt;= set(''.join(myList)) You had the right idea to convert both parameters to sets, just forgot to join the list of strings before... then set inclusion operator &lt;= is very handy
score: 1
answers question: http://stackoverflow.com/q/49354618
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49377804
has body: I have the following code: X = np.array([[2,2,2,4,5,6],[1,2,3,3,3,4]]) mu = np.mean(X,axis=1) My Problem: When I try to subtract the mean from the data (X - mu), I get the following error: operands could not be broadcast together with shapes (2,6) (2,) This makes sense but still having trouble trying to subtract the mean from this data, X. I am expecting the following result: 1.5 1.5 1.5 0.5 1.5 2.5 1.67 0.67 0.33 0.33 0.33 1.33
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/85756862
type: UnansweredQuestion
has title: Using python to subtract an nx1 array (matrix) from a nxm array (matrix)
has answer: http://stackoverflow.com/a/49378202
has comment: http://stackoverflow.com/comment/85785980
has comment: http://stackoverflow.com/comment/85757215
score: 0
has comment: http://stackoverflow.com/comment/85756351
has answer: http://stackoverflow.com/a/49392217
tagged with: matrix
tagged with: python

http://stackoverflow.com/q/49391557
has body: I am attempting to create a self referential SQLAlchemy relationship with custom JOIN logic. Our database has a table of Events which contains the 'eventID', 'eventDate' and 'userID' columns. The relationship I'm implementing is 'previousEvents'. I want to join the Events table to itself using 'userID' where eventDate > eventDate for every other event with the same userID. The SQL query constructed should look like so: SELECT original.eventID, previous.eventID, ... etc FROM Events as original JOIN Events as previous ON previous.userID = original.userID AND previous.eventDate &lt; original.eventDate My table definitions look like so: from sqlalchemy import Column, ForeignKey, String, DateTime from sqlalchemy.ext.declarative import declarative_base class Event(Base): __tablename__ = 'event' # Attributes eventID = Column(String(length=256), primary_key=True) eventDate = Column(DateTime) userID = Column(String(length=256), ForeignKey('users.userID')) class Users(Base): __tablename__ = 'users' # Attributes userID = Column(String(length=256), primary_key=True) userName = Column(String) How can I define the relationship in Events to get the desired effect?
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: sql
tagged with: python
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/49393202
linked to: http://stackoverflow.com/q/37806625
upvote count: 2
has answer: http://stackoverflow.com/a/49393202
has title: Self-referential relationship with filter in SQLAlchemy
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85879899
type: AnswerComment
has text: Alright, that works! But is there a way to maybe stop or break the current course midway and reflect back? Because currently, let's say the turtle is at an edge, it goes 100units off screen then it returns. Maybe a way to stop or cut it off before the full 100units?
comment on: http://stackoverflow.com/a/49438819
type: Comment
score: 0

http://stackoverflow.com/a/49409210
has comment: http://stackoverflow.com/comment/86001315
has comment: http://stackoverflow.com/comment/86193171
has comment: http://stackoverflow.com/comment/86001337
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85876291
has comment: http://stackoverflow.com/comment/86296741
has body: Assuming: lst = ["hello i am from denmark", "that was in the united states", "nothing here"] dict_x = {"denmark" : "dk", "germany" : "ger", "norway" : "no", "united states" : "us"} You can do: res = [dict_x.get(next((k for k in dict_x if k in my_str), None), my_str) for my_str in lst] which returns: print(res) # -&gt; ['dk', 'us', 'nothing here'] The cool thing about this (apart from it being a python-ninjas favorite weapon aka list-comprehension) is the get with a default of my_str and next with a StopIteration value of None that triggers the above default.
has comment: http://stackoverflow.com/comment/85821446
answers question: http://stackoverflow.com/q/49408938
type: Answer
accepted answer of: http://stackoverflow.com/q/49408938
has comment: http://stackoverflow.com/comment/85976718

http://stackoverflow.com/comment/85587236
score: 0
comment on: http://stackoverflow.com/q/49285664
has text: @iga, tried `BATCH_SIZE=2`, interestingly now it gives `ValueError: Dimension 0 in both shapes must be equal, but are 4 and 2. Shapes are [4,2] and [2,2]. for 'softmax_cross_entropy_with_logits_sg' (op: 'SoftmaxCrossEntropyWithLogits') wit h input shapes: [4,2], [2,2].` It looks like whatever value I set it is squared
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85732693
comment on: http://stackoverflow.com/a/49365865
type: AnswerComment
score: 0
has text: I bet we can use re.sub again and replace `\n ` with `\n`
type: Comment

http://stackoverflow.com/q/49360776
downvote count: 5
tagged with: python
tagged with: parsing
has body: I'm having problem with parser on Windows(!), on Linux everything is working good. In my .CSV file I have some numbers displayed as "######", ofc only on windows. If you need to see code -> My github Screen of the following problem
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85721668
answer count: 1
has title: Numbers as ### in .CSV
has comment: http://stackoverflow.com/comment/85721725
upvote count: 1
has answer: http://stackoverflow.com/a/49360826
score: -4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49360826

http://stackoverflow.com/comment/85791990
score: 0
comment on: http://stackoverflow.com/q/49394150
type: QuestionComment
type: Comment
has text: i will try the "How to serialize SqlAlchemy result to JSON" i hope that works.

http://stackoverflow.com/comment/85794512
comment on: http://stackoverflow.com/q/49396155
type: QuestionComment
score: 0
has text: I'm not entirely sure what the specific error was, but I have just updated the post with the full error message.
type: Comment

http://stackoverflow.com/comment/103160506
has text: @Michaela Nope. If the input is a sequence of length T, then 1 will also be a sequence of length T. On the other hand, 2 and 4 will both have length 1, they're the output at a single time step.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49326310
type: Comment

http://stackoverflow.com/q/49294329
type: Question
tagged with: python
has body: I am trying the high API tf.estimator, but I find it hardly to get the session to debug some inter-result such as global step. cls = tf.estimator.Estimator( model_fn=my_model, params={ 'feature_columns': fcs, 'hidden_units': [10, 10], 'n_classes': 3, }) The example from https://www.tensorflow.org/versions/master/get_started/custom_estimators I have try sess = tf.get_default_session and with tf.Session() as sess, but can't get the defut session.
has title: How to get the default session from a tf.estimator?
score: 6
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49295627
has answer: http://stackoverflow.com/a/49295627
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/85727639
score: 0
type: AnswerComment
has text: @jezrael I'll check it out. Thanks!
comment on: http://stackoverflow.com/a/49363681
type: Comment

http://stackoverflow.com/q/49363552
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85728417
tagged with: python
tagged with: keras
has body: I am using the Keras ImageDataGenerator to process the inputs to my CNN. I want to basic preprocessing that scales the image pixels to values from -1 to 1 as it was done in the paper of the Mobilenet architecture. My datagenerator only defines the preprocessing function: train_datagen = ImageDataGenerator( preprocessing_function=preprocess_input ) My preprocess_input function: def preprocess_input(img): pix = np.asarray(img) pix = pix.astype(np.float32) pix = pix / 255.0 pix = pix * 2 return pix This is giving me the follwing error: Traceback (most recent call last): File "finetune_mobilenet.py", line 206, in &lt;module&gt; train(folder_train, folder_dev, './models/') File "finetune_mobilenet.py", line 150, in train callbacks=callbacks_list) File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 2192, in fit_generator generator_output = next(output_generator) File "/usr/local/lib/python2.7/dist-packages/keras/utils/data_utils.py", line 584, in get six.raise_from(StopIteration(e), e) File "/usr/local/lib/python2.7/dist-packages/six.py", line 737, in raise_from raise value StopIteration: 'tuple' object cannot be interpreted as an index I also tried the original preprocessing function that is available for the Mobilenet architecture in Keras but that one also fails. Can you tell what I need to change to zero-center my image data?
score: 0
answer count: 0
tagged with: image-preprocessing
has comment: http://stackoverflow.com/comment/85733968
has title: Keras image preprocessing error at return
type: Question

apache-kafka
tags question: http://stackoverflow.com/q/49327187
type: Tag
tags question: http://stackoverflow.com/q/49332239
tags question: http://stackoverflow.com/q/49322289
tag name: apache-kafka
tags question: http://stackoverflow.com/q/49433367
tags question: http://stackoverflow.com/q/49319885

flowchart
tag name: flowchart
tags question: http://stackoverflow.com/q/49409124
type: Tag

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

http://stackoverflow.com/comment/85880086
comment on: http://stackoverflow.com/q/49438954
type: Comment
type: QuestionComment
has text: @user2357112 He hasn't even gotten to any writes (that is, reads that make a new reference) at the time he's hitting the error, so how could reducing the number/frequency of writes solve that?
score: 0

http://stackoverflow.com/comment/85577813
has text: yaah ,sorry i forgot that, ok.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49286755
type: QuestionComment

similarity
tags question: http://stackoverflow.com/q/49380138
tag name: similarity
tags question: http://stackoverflow.com/q/49399439
tags question: http://stackoverflow.com/q/49432252
tags question: http://stackoverflow.com/q/49404445
tags question: http://stackoverflow.com/q/49438179
tags question: http://stackoverflow.com/q/49360773
type: Tag

http://stackoverflow.com/comment/85908266
type: Comment
comment on: http://stackoverflow.com/a/49438469
has text: Thank you again for the explanation. I'll take those factors into account in the future, and I'll remove using Pandas from doing simple text to csv manipulation like here. I think I was really not using the right/most efficient tool for the job. Cheers!
type: AnswerComment
score: 0

http://stackoverflow.com/a/49321104
type: Answer
has body: Size of pointer may be greater than size of int and depends of memory model. int iSomeValue = 0; std::cout &lt;&lt; "size of int = " &lt;&lt; sizeof(iSomeValue)&lt;&lt; " | size of pointer = " &lt;&lt; sizeof(&amp;iSomeValue); For Visual Studio 2013 Win32 output is: size of int = 4 | size of pointer = 4 For Visual Studio 2013 x64 output is: size of int = 4 | size of pointer = 8
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49320251

http://stackoverflow.com/q/49358963
possible better answer: http://stackoverflow.com/a/49359066
has comment: http://stackoverflow.com/comment/85718039
type: AnsweredQuestion
upvote count: 4
has answer: http://stackoverflow.com/a/49359066
answer count: 3
has title: How do I initialize a dictionary with a list of keys and values as empty sets in python3.6?
downvote count: 0
has body: I tried using dict.fromkeys([1,2,3],set()). This initializes creates the dictionary but when I add a value to any one of the sets all the sets get updated! &gt;&gt;&gt; d=dict.fromkeys([1,2,3],set()) &gt;&gt;&gt; d &gt;&gt;&gt; {1: set(), 2: set(), 3: set()} &gt;&gt;&gt; d[1].add('a') &gt;&gt;&gt; d &gt;&gt;&gt; {1: {'a'}, 2: {'a'}, 3: {'a'}} It seems that all the three values of the dictionary are referring to the same set. I want to initialize all the values of the dictionary to empty sets so that I can perform some operations on these sets in a loop based on the keys later.
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49359069
accepted answer: http://stackoverflow.com/a/49359019
tagged with: python
has answer: http://stackoverflow.com/a/49359019
linked to: http://stackoverflow.com/q/11509721
score: 4
has comment: http://stackoverflow.com/comment/102686898

http://stackoverflow.com/a/49335901
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85673791
has body: while(True): X= input("enter the command") """do what ever you want here"""" this will always ask for a single variable and you can check with if/else. use hold if you want to hold the asking statement.
answers question: http://stackoverflow.com/q/49335505

http://stackoverflow.com/q/49321731
has comment: http://stackoverflow.com/comment/85648414
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85646647
tagged with: python
has body: As you'll understand after reading the question, I am new to Spark. I am trying to create a new DataFrame with the list of actions per session to eventually call PySparks FP-Growth function To clarify what I want, I have: +-----------+---------+ |sessionid |event_col| +-----------+---------+ |0 | 1| |1 | 2| |1 | 3| |2 | 1| |0 | 3| +-----------+---------+ And want: +-----------+---------+ |sessionid | events| +-----------+---------+ | 0| [1, 3]| | 1| [2, 3]| | 2| [1]| +-----------+---------+ I prototyped this in plain Python with a Pandas DataFrame to get the list of events. sessions = [] for sess in df.sessionid.unique(): session = [] for action in df[df.sessionid == sess]["event_col"]: session.append(action) sessions.append(session) I've rewritten it in PySpark (2.0), but literally recreated the for loop: def sessionsbuilder(df): df = df.select(['sessionid', 'event_col']) sessions = [] for sess in df.select('sessionid').distinct().collect(): session = [] for action in df.where(df.sessionid == sess[0][0]).select('event_col').collect(): session.append(action) sessions.append(session) return sessions As expected, this is very slow (over 2 hours opposed to 11 seconds in plain python with pandas). I checked this post about nested for loops in Spark. I'm having a hard time creating this kind of lambdas for my purpose because of the list initiation in the for loop. There is possibly a way to create such a DataFrame without an explicit for loop or a way to do this more efficiently (maybe a udf), because I'm not leveraging the power of Spark this way.
linked to: http://stackoverflow.com/q/31513823
has comment: http://stackoverflow.com/comment/85646085
accepted answer: http://stackoverflow.com/a/49323952
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85646725
has answer: http://stackoverflow.com/a/49323952
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85647311
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85645347
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85644916
tagged with: python-3.x
has title: remove, or speed-up an explicit for loop in PySpark
tagged with: apache-spark-sql

http://stackoverflow.com/q/49418839
has comment: http://stackoverflow.com/comment/85839309
tagged with: python
has answer: http://stackoverflow.com/a/49418883
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49418883
has body: I'm trying to access the index number of a dictionary that is stored within a list. I'm trying to print out a statement based on this index but I'm unsure of how to go about it. Here's my current code: def getSpecies(self, animalName): for items in self.animalList: for key, value in items.items(): if self.animalName == value: type = self.animalList[itemsIndex]['Type'] print (str(self.animalName) + "' is a " + type) Where self.animalName is a user input and self.animalList contains the list of dictionaries. I want the example output to be: Shamu is a Whale An example of how the list looks like is this: self.animalList = [{'Litter': '3', 'Type': 'Whale', 'Mass': '300', 'Name': 'Shamu'}, {'Litter': '0', 'Type': 'Bird', 'Mass': '5', 'Name': 'Woody'}]
tagged with: class
tagged with: python-2.7
tagged with: list
type: AnsweredQuestion
has title: Finding index number of dictionary item in a list based on a given value
downvote count: 0
has comment: http://stackoverflow.com/comment/85839275
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85839347
favorite count: 0
type: Question

http://stackoverflow.com/comment/85744187
type: QuestionComment
comment on: http://stackoverflow.com/q/49371430
has text: Hi @hpaulj, thanks. By assigning a new array `n2` that contains only column 0 of `n1`, and using your suggestion, I built `np.where(n2[1:]-n2[:-1] < 0)` which gives me `(array([3, 5]),)`, not `array([4, 6])`
score: 0
type: Comment

http://stackoverflow.com/comment/139520689
type: AnswerComment
has text: @Xerusial I don't see an example of what OP exactly wants, but I think he wants a filename with extension and add an extra extension (for example `filte.txt` to `file.txt.backup`), otherwise the `.with_suffix` function would suffice.
comment on: http://stackoverflow.com/a/60281933
type: Comment
score: 0

http://stackoverflow.com/q/49387565
answer count: 1
tagged with: abaqus
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85781760
has answer: http://stackoverflow.com/a/49388449
has body: import section import regionToolset import displayGroupMdbToolset as dgm import part import material import assembly import step import interaction import load import mesh import optimization import job import sketch import visualization import xyPlot import displayGroupOdbToolset as dgo import connectorBehavior s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=5.0) g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=STANDALONE) s.Line(point1=(-0.2, 0.2), point2=(-0.2, 0.1)) s.VerticalConstraint(entity=g[2], addUndoState=False) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=THREE_D, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseWire(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__']
upvote count: 0
type: UnansweredQuestion
has title: how can I multiple this part using for loops?
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/85776503
score: -4

http://stackoverflow.com/a/49368570
has comment: http://stackoverflow.com/comment/85794769
type: AcceptedAnswer
has body: I would create an exclusive lock after open the file and then release the lock before closing the file: For creating an exclusive lock over the file: flock($fh, LOCK_EX); To delete it: flock($fh, LOCK_UN); Anyway you will need to check if other threads hot already the lock, so the first idea coming up is to try a few attempts to get the lock and if it's not finally possible, to inform the user, throw an exception or whatever other action to avoid an infinite loop: $fh = fopen("found.txt", "w+"); $attempts = 0; do { $attempts++; if ($attempts &gt; 5) { // throw exception or return response with http status code = 500 } if ($attempts != 1) { sleep(1); } } while (!flock($fh, LOCK_EX)); // rest of your code file_put_contents('found.txt', $users); flock($fh, LOCK_UN); // release the lock fclose($fh); Update Probably the issue still remains because the reading part, so let's create also a shared lock before start reading and also let's simplify the code: $file = "found.txt"; $fh = fopen($file,'r+'); $gotPokemon = $_GET['pokemon']; $users = ''; $wouldblock = true; // we add a shared lock for reading $locked = flock($fh, LOCK_SH, $wouldblock); // it will wait if locked ($wouldblock = true) while(!feof($fh)) { // your code inside while loop } // we add an exclusive lock for writing flock($fh, LOCK_EX, $wouldblock); file_put_contents('found.txt', $users); flock($fh, LOCK_UN); // release the locks fclose($fh); Let's see if it works
has comment: http://stackoverflow.com/comment/85871071
has comment: http://stackoverflow.com/comment/85828000
has comment: http://stackoverflow.com/comment/85879249
accepted answer of: http://stackoverflow.com/q/49368302
has comment: http://stackoverflow.com/comment/85744986
type: Answer
answers question: http://stackoverflow.com/q/49368302
has comment: http://stackoverflow.com/comment/85881603
has comment: http://stackoverflow.com/comment/85746625
score: 0

http://stackoverflow.com/q/49291726
tagged with: python
has body: I want to resize my image, but my image has lots of zeros and NaN. I want to resize by excluding zeros and NaN. The code so far I have is: # Import Libraries import numpy as np import cv2 # Generate sample data with zero and NaNs a = np.zeros(shape=(8,8)) a[0] = [1,1,3,3,5,5,7,0] a[1] = [1,0,3,0,5,0,0,7] a[2] = [1,2,3,4,5,6,7,8] a[3] = [1,2,3,0,5,6,7,8] a[4] = [1,2,3,3,5,6,7,8] a[5] = [1,2,3,4,5,6,7,8] a[6] = [2,2,3,4,5,0,7,8] a[7] = [0,2,3,4,5,6,7,8] a[1:3,5] = np.nan # Replace nan with zero (or zero with nan) # a[np.isnan(a)] = 0 a[a==0] = np.nan # Resize (8x8) array into (4x4) c = cv2.resize(a,(4,4),cv2.INTER_CUBIC) The problem is that it includes zeros and NaN when averaging. I also replaced zeros with NaNs or vice versa. I also tried with INTER_NEAREST, INTER_LINEAR, etc but the result remains the same.
accepted answer: http://stackoverflow.com/a/49298088
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49298088
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has title: Resize image by excluding zero and NaNs
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85586831

http://stackoverflow.com/q/49280700
has answer: http://stackoverflow.com/a/49280870
has comment: http://stackoverflow.com/comment/85564290
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
type: Question
has title: Calulation Formula from string to result
has body: I have a columns string column like this: A '(1+2)' '1*(1/2)' '5*2' How is it possible to solve these calculation as a float or integer? calc_df['A'] = calc_df['A'].astype('Float64') ValueError: could not convert string to float: '(1+2)'
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49280870
tagged with: calculation

http://stackoverflow.com/q/49370995
answer count: 1
accepted answer: http://stackoverflow.com/a/49386355
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49386355
tagged with: lambda
tagged with: signals-slots
has body: After alot of research including on on stackoverflow i really can't understand why the code below does not work even after i set the Default value of my variable as alot of people recomended. here is the code #initial nested array outter = [["name1",1],["name2",2],["name3",3]] for inner in outter: button = QPushButton() button.setText(inner[0]) // create a button with the text button.clicked.connect(lambda value=inner[1] : print(value)) The 3 buttons are created each with its respective name ( name1,name2,name3) but when i click them, it prints False False False If i change this part of the code, all 3 buttons print the last value "3", as shown below, button.clicked.connect(lambda : print(inner[1])) 3 3 3 I already tried doing all sorts crazy things to make this work, any advices?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/19837486
tagged with: python
has title: Python lambda pass-by-value mutable objects
has comment: http://stackoverflow.com/comment/85772765
type: Question
score: 0

http://stackoverflow.com/q/49303160
type: UnansweredQuestion
tagged with: python
has body: So I'm creating a basic (my first project using python) game with python. there is a part where I put a random.choice. I want to refer back to the same random number that it picked so I wondered if it is possible to create a variable for that output. I've tried str = randomint(1,7) but that didnt give me the result I wanted. # random module import random dice1 = ['1','2','3','4','5','6','7'] print (random.choice(dice1))
has answer: http://stackoverflow.com/a/49303249
has title: Creating variable out of random output
has comment: http://stackoverflow.com/comment/85614086
score: 0
tagged with: random
answer count: 2
has comment: http://stackoverflow.com/comment/85608335
tagged with: variables
has answer: http://stackoverflow.com/a/49303323
type: Question

http://stackoverflow.com/comment/85832554
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49414428
has text: Your question still lacks a clear problem statement. "it seems like I didn't do anything" and "it failed again" aren't clear problem statements. You should describe what you expected to happen, what happened instead, and if there's an error message you should include it in your question.

http://stackoverflow.com/a/65971744
has body: The Pyadomd package might help you with your problem: Pyadomd It is not tested on Windows 7, but I would expect it to work fine :-)
answers question: http://stackoverflow.com/q/49411277
type: Answer
score: 0

http://stackoverflow.com/comment/85743175
has text: @cᴏʟᴅsᴘᴇᴇᴅ yep , I need to keep that in mind , thank you man : -) remind me twice today :-)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49370867
score: 0

http://stackoverflow.com/comment/85723583
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49360958
has text: Well, unfortunately I can't access the above link. Good luck!
score: 0

http://stackoverflow.com/comment/85875122
comment on: http://stackoverflow.com/q/49436063
score: 0
type: Comment
has text: I do not know where to start sir. I am just 16.
type: QuestionComment

http://stackoverflow.com/comment/85876868
has text: While not ideal you could just catch the error and continue processing
type: AnswerComment
comment on: http://stackoverflow.com/a/49436340
score: 0
type: Comment

http://stackoverflow.com/a/49305814
accepted answer of: http://stackoverflow.com/q/49304932
has comment: http://stackoverflow.com/comment/85613952
answers question: http://stackoverflow.com/q/49304932
type: Answer
has comment: http://stackoverflow.com/comment/85614670
has comment: http://stackoverflow.com/comment/85615051
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
has body: Streams in Python are Python's way of abstract iteration. On the other hand they are just objects that have a __next__ method. The Csv module you mention provides a value next which behaves in exactly the same way. Furthermore the module defines some more concrete iterators like fold_left and iter. Thus it is already easy to iterate over csv lines (as string list) and to wrap an Csv.in_channel into an object with much the same signature and behaviour as a Python stream of csv lines. It remains to convert such lines into dictionaries. Which is just a matter of mapping a line-to-dictionary converter to the iterator or stream.

http://stackoverflow.com/q/49370077
type: Question
has answer: http://stackoverflow.com/a/61915306
has title: Bitbake Server does not start on Windows Subsystem for Linux
has comment: http://stackoverflow.com/comment/93241417
tagged with: python
has body: I am following the Quick Start Guide for Yocto Project on Windows Subsystem for Linux. I cloned all the necessary stuff: sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib \ build-essential chrpath socat cpio python python3 python3-pip python3-pexpect \ xz-utils debianutils iputils-ping libsdl1.2-dev xterm cloned the repository to a directory in the /mnt/c/Users/&lt;myUser&gt;/Yocto directory created a branch as mentioned in the manual cd poky/ &amp;&amp; git checkout tags/yocto_2.4.2 -b poky_2.4.2 and executed the file source oe-init-build-env Once I execute bitbake core-image-sato I get the following Error: Previous bitbake instance shutting down?, waiting to retry... Previous bitbake instance shutting down?, waiting to retry... NOTE: Retrying server connection... (Traceback (most recent call last): File "/mnt/c/Users/&lt;user&gt;/Yocto/poky/bitbake/lib/bb/main.py", line 441, in setup_bitbake server = bb.server.process.BitBakeServer(lock, sockname, configuration, featureset) File "/mnt/c/Users/&lt;user&gt;/Yocto/poky/bitbake/lib/bb/server/process.py", line 385, in __init__ self.sock.bind(os.path.basename(sockname)) PermissionError: [Errno 1] Operation not permitted ) WARNING: /mnt/c/Users/des/Development/Yocto/poky/bitbake/lib/bb/main.py:476: ResourceWarning: unclosed &lt;socket.socket fd=14, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0&gt; logger.info("Retrying server connection... (%s)" % traceback.format_exc()) NOTE: Reconnecting to bitbake server... NOTE: Retrying server connection... ERROR: Unable to connect to bitbake server, or start one I stumbled upon some GitHub Issue from the WSL Issue Tracker that this might have something to do with inotify. I can't figure out what is wrong here and which socket is the error really about?
has answer: http://stackoverflow.com/a/49370394
score: 4
tagged with: windows-subsystem-for-linux
upvote count: 4
has answer: http://stackoverflow.com/a/53326852
answer count: 3
tagged with: bitbake
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93237775
downvote count: 0
tagged with: yocto
favorite count: 0

http://stackoverflow.com/comment/85712658
score: 0
type: Comment
type: QuestionComment
has text: yes, error:"unicode' object has no attribute 'json'", i tried json.dumps too
comment on: http://stackoverflow.com/q/49356195

http://stackoverflow.com/a/49380325
has body: You miss terminate character in url(r'^movie', home) Try this: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^movie$', home), url(r'^movie/(?P&lt;title&gt;.*)$', movie_detail, name='movie_detail') ]
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49380282
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85887284
comment on: http://stackoverflow.com/a/49398948
type: AnswerComment
score: 0
has text: This is what I need finally. Can you point out what changes do I need to make in the code and where? Definitely this problem is solved then.
type: Comment

http://stackoverflow.com/a/49470953
has comment: http://stackoverflow.com/comment/135581057
type: Answer
has comment: http://stackoverflow.com/comment/135581586
score: 12
has body: I had the same issue. I needed to process a huge text corpus while keeping a few DataFrames with millions of rows loaded in memory. I think this issue is common so I will provide a generic answer: A combination of settings can solve the problem (1 &amp; 3 &amp; 5 only might do it for you): Use Pool.imap (or imap_unordered) instead of Pool.map. This will iterate over data lazily than loading all of it in memory before starting processing. Set a value to chunksize parameter. This will make imap faster. Set a value to maxtasksperchild parameter. Append\store output to disk than in memory. Instantly or every while when it reaches a certain size. Run your code in different batches. You can use itertools.islice if you have an iterator. The idea is to split your list(gen_matrix_df_list.values()) to three or more lists, then you pass the first third only to map or imap, then the second third in another run, etc. Since you have a list you can simply slice it in the same line of code.
upvote count: 12
has comment: http://stackoverflow.com/comment/85944491
has comment: http://stackoverflow.com/comment/85944589
has comment: http://stackoverflow.com/comment/135580148
has comment: http://stackoverflow.com/comment/85945094
has comment: http://stackoverflow.com/comment/85945009
answers question: http://stackoverflow.com/q/49429368
has comment: http://stackoverflow.com/comment/135567476
downvote count: 0

http://stackoverflow.com/comment/85833182
comment on: http://stackoverflow.com/q/49415590
type: Comment
has text: run a task at a specific time? I have several clients on a database in excel. Each person has a specific time that they are to be contacted to start my program, which is one of the columns in the excel file. I need to be able to translate from the excel file column to something I can compare the current either datetime.datetime.now() or datetime,datetime.now().time()
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85693219
comment on: http://stackoverflow.com/q/49346604
score: 0
has text: Can you add a small reproducible sample data set and your desired data set? Is it about financial mathematics?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85575338
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49286228
has text: I believe shutting down the notebook clears all the state from that notebook.

http://stackoverflow.com/comment/85796112
has text: Firstly please add the whole error code so at least we can know whats wrong, and it seems there are a lot of dependencies on the page you've linked, are you sure that you've successfully installed all of them?
score: 0
comment on: http://stackoverflow.com/q/49397019
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49414332
score: 1
type: Answer
has body: The "new" assumptions module is not (yet) integrated with the rest of SymPy, so making assumptions with it has no effect on your computations. Placing assumptions on symbols at the time of their creation, like Symbol(k0, positive=True), is currently the only way to have that assumption be used by SymPy.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49398913
accepted answer of: http://stackoverflow.com/q/49398913

http://stackoverflow.com/comment/85735141
type: QuestionComment
score: 0
has text: @Antry I work in Anaconda enviroment on Windows. I've checked my Python version, which was 3.5.4, so I upgraded it and that solved my problem. Thank you!
comment on: http://stackoverflow.com/q/49365979
type: Comment

http://stackoverflow.com/q/49318538
downvote count: 2
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/85638300
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85638487
has comment: http://stackoverflow.com/comment/85638155
tagged with: python
score: -1
has body: I have a string as such: teststring = 'Index: WriteVTKOutput.FOR\\r\\n======================================\\r\\n' I'd like to split it based on the '\\r' and '\\n' characters, such that I get the following result: testlist = ['Index: WriteVTKOutput.FOR', '======================================'] I tried the following commands, none of which worked: teststring.split(r'\r\n') teststring.splitlines() How does a man split that string into those delimiters while retaining his dignity and keeping it real? Thanks
answer count: 4
has answer: http://stackoverflow.com/a/49318607
has answer: http://stackoverflow.com/a/49318680
type: AnsweredQuestion
has title: split string based on special characters python
has comment: http://stackoverflow.com/comment/85638249
has answer: http://stackoverflow.com/a/49318631
possible better answer: http://stackoverflow.com/a/49318631
has answer: http://stackoverflow.com/a/49318603
accepted answer: http://stackoverflow.com/a/49318603
has comment: http://stackoverflow.com/comment/85638217

http://stackoverflow.com/comment/85831696
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49414915
has text: You need to update `turtleX, turtleY = turt.pos()` inside the `while` loop.
type: Comment

http://stackoverflow.com/comment/85656439
type: QuestionComment
comment on: http://stackoverflow.com/q/49323857
has text: What they probably mean is that sklearn cannot handle features with multiple categories. sklearn converts everything to floats, so 1s and 0s are fine, but something like a 3 label class (data ∈ {0,1,2}) will have an implicit order. I think you're fine here.
score: 0
type: Comment

http://stackoverflow.com/q/49369842
favorite count: 0
type: Question
has title: How to get the exact count of people by face detection?
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85740703
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49370205
tagged with: python
has body: I am working on using opencv to get the total number of people in a video stream. The problem is that my code only captures the number of people in frame without taking into account all of the frames in the stream. I thought about extracting all the faces detected from a video or webcam and then comparing them. My question here is how do I get the exact count of people by comparing the faces which are extracted? Or is there any other approach to get the total count? This is the function which detects faces and gives gender and count(but its only for that frame ) def start_webcam(model_gender, window_size, window_name='live', update_time=50): cv2.namedWindow(window_name, WINDOW_NORMAL) if window_size: width, height = window_size cv2.resizeWindow(window_name, width, height) video_feed = cv2.VideoCapture(0) video_feed.set(3, width) video_feed.set(4, height) read_value, webcam_image = video_feed.read() delay = 0 init = True while read_value: read_value, webcam_image = video_feed.read() webcam_image=cv2.flip(webcam_image,1,0) faces = face_cascade.detectMultiScale(webcam_image) for normalized_face, (x, y, w, h) in find_faces(webcam_image): if init or delay == 0: init = False gender_prediction = model_gender.predict(normalized_face) if (gender_prediction[0] == 0): cv2.rectangle(webcam_image, (x,y), (x+w, y+h), (0,0,255), 2) cv2.putText(webcam_image, 'female', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2) else: cv2.rectangle(webcam_image, (x,y), (x+w, y+h), (255,0,0), 2) cv2.putText(webcam_image, 'male', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255,0,0), 2) delay += 1 delay %= 20 cv2.putText(webcam_image, "Number of faces detected: " + str(len(faces)), (0,webcam_image.shape[0] -10), cv2.FONT_HERSHEY_TRIPLEX, 0.7, (255,255,255), 1) cv2.imshow(window_name, webcam_image) key = cv2.waitKey(update_time) if key == ESC: break cv2.destroyWindow(window_name)
tagged with: opencv
has answer: http://stackoverflow.com/a/49376109
score: 1

http://stackoverflow.com/q/49417145
accepted answer: http://stackoverflow.com/a/49423413
has body: I want to make a post request by using ajax. I want to use the input value as function parameter and append the function return into a html table. I don't know but a think that my code is wrong and the ajax is not working. Note: For testing, I'm taking input value and returning to html page. network.html Search {% print dado %} app.py @app.route('/network',methods=['POST','GET']) def network(): if request.method == 'POST': input = request.form['search-input'] return render_template('network.html',dado=input) else: return render_template('network.html',dado='') Edit: After this update what's returning is a JSON format { "dado": "INPUT VALUE" } app.py @app.route('/network',methods=['POST','GET']) def network(): if request.method == 'POST': input = request.form['search-input'] return jsonify(dado=input) else: return render_template('network.html',dado='') network.html
answer count: 1
linked to: http://stackoverflow.com/q/14908864
type: Question
has comment: http://stackoverflow.com/comment/85847187
has comment: http://stackoverflow.com/comment/85852117
has answer: http://stackoverflow.com/a/49423413
tagged with: python
tagged with: flask
tagged with: ajax
type: AnsweredQuestion
score: 0
has title: Flask: POST request using AJAX

http://stackoverflow.com/comment/85604878
has text: python3: can't open file 'isConnected': [Errno 2] No such file or directory I'm certain I'm in the right directory though!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49301514
type: Comment

http://stackoverflow.com/q/49347477
linked to: http://stackoverflow.com/q/42616768
tagged with: emacs
tagged with: python
has comment: http://stackoverflow.com/comment/85707375
has answer: http://stackoverflow.com/a/49354929
has title: UnknownBackend: No event loop integration for u'inline' when enable inline matplotlib in emacs python notebook
has comment: http://stackoverflow.com/comment/85847128
score: 3
upvote count: 3
downvote count: 0
has body: I am trying to enable the python notebook in emacs. I am following the instruction from this page: https://realpython.com/blog/python/emacs-the-best-python-editor/ When I tried to do "%matplotlib inline" so that I can show the plot inline, I got the following errors: "UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt, qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, OSX" My emacs is 24.4 and jupyter notebook version is 4.3 Thanks
has comment: http://stackoverflow.com/comment/85851919
has comment: http://stackoverflow.com/comment/85846805
answer count: 1
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/85709031
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21784641
type: UnansweredQuestion

http://stackoverflow.com/comment/85803862
type: QuestionComment
has text: And what is the difference between a Qthread and a Process? I use a process because I want to take advantage of a multicore processor, It can be possible with a QThread?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49384708

http://stackoverflow.com/comment/85640446
type: Comment
score: 0
has text: Do you need a loop where you generate first 1 random value, then 2, then 3, or could you generate all 6 values in a row ? Because at the end, it seems that you only need the min for the 6 values, no matter the step during which it has been generated. If that's the case, the algorithm could be implement much more efficiently.
type: QuestionComment
comment on: http://stackoverflow.com/q/49319204

http://stackoverflow.com/q/49439187
type: Question
has comment: http://stackoverflow.com/comment/85880927
tagged with: pandas
tagged with: python
has body: I'd like to apply an "aggregation" function to a groupby instance of a DataFrame by which the result is not reducing the final number of rows, but increasing it (not quite an "aggregation"). For instance, the below call should result in a duplication of cat=A, B rows depending on the result returned by the function (with cola and colb columns). Unfortunately, the added index columns are somehow added as columns in the result. &gt;&gt;&gt; df = pd.DataFrame({ 'date': pd.date_range('1/1/2018', periods=10, freq='10D'), 'val': range(10), 'cat': ['A'] * 7 + ['B'] * 3 }) &gt;&gt;&gt; def func(x): data = range(20) # 2 x 10 = 20 rows index = pd.MultiIndex.from_product([ [3, 4], pd.date_range('1/1/2018', periods=10, freq='10D') ], names=['cola', 'colb']) return pd.Series(data, index=index) &gt;&gt;&gt; df.groupby('cat').apply(func) cola 3 \ colb 2018-01-01 2018-01-11 2018-01-21 2018-01-31 2018-02-10 2018-02-20 cat A 0 1 2 3 4 5 B 0 1 2 3 4 5 cola 4 \ colb 2018-03-02 2018-03-12 2018-03-22 2018-04-01 2018-01-01 2018-01-11 cat A 6 7 8 9 10 11 B 6 7 8 9 10 11 cola \ colb 2018-01-21 2018-01-31 2018-02-10 2018-02-20 2018-03-02 2018-03-12 cat A 12 13 14 15 16 17 B 12 13 14 15 16 17 cola colb 2018-03-22 2018-04-01 cat A 18 19 B 18 19 Is there anything I can do to get this done or is .apply() just not geared to duplicate rows?
has title: Adding rows when using .apply()
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49439497
has answer: http://stackoverflow.com/a/49439497

http://stackoverflow.com/q/49300248
accepted answer: http://stackoverflow.com/a/49308938
tagged with: youtube-data-api
linked to: http://stackoverflow.com/q/8544559
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49308938
tagged with: python
tagged with: youtube-api
answer count: 1
has body: I am trying to fetch a subscription list according to the Subscriptions: list documentation. I want to get all my subscribers so I am using mySubscribers=True in the parameter list in a loop after my first request. while "nextPageToken" in my_dict: next_page_token = my_dict["nextPageToken"] my_dict = subscriptions_list_by_channel_id(client, part='snippet,contentDetails', mySubscribers=True, maxResults=50, pageToken=next_page_token ) for item in my_dict["items"]: file.write("{}\n".format(item["snippet"]["channelId"])) The problem is at page 20 my loop breaks, i.e. I don't recieve a nextPageToken key in the response capping my data to 1000 total subscribers fetched. But I have more than 1000 subs. The documentation states that myRecentSubscribers has a limit at 1000 but that mySubscribers does not. Can not really find much help with this anywhere. Any light on my situation?
has title: List subscribers limit at 1000
type: Question

http://stackoverflow.com/comment/85583107
type: AnswerComment
comment on: http://stackoverflow.com/a/49289907
score: 0
type: Comment
has text: Python version 3.6

http://stackoverflow.com/q/49290553
tagged with: bigdata
tagged with: pyspark
tagged with: python
has title: Average over 2000 values with PySpark Dataframe
answer count: 2
tagged with: apache-spark
score: 1
has answer: http://stackoverflow.com/a/49324825
downvote count: 0
upvote count: 1
has body: I have a PySpark dataframe with about a billion rows. I want to average over every 2000 values, like average of rows with indeces 0-1999, average of rows with indeces 2000-3999, and so on. How do I do this? Alternatively, I could also average 10 values for every 2000, like average of rows with indeces 0-9, average of rows with indeces 2000-2009, and so on. The purpose of this is to downsample the data. I don't currently have an index row, so if I need this, how do I do it?
has comment: http://stackoverflow.com/comment/85584478
favorite count: 0
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/49291155
type: UnansweredQuestion

http://stackoverflow.com/q/49351442
has comment: http://stackoverflow.com/comment/85711456
type: Question
has body: I wrote the below code about 6 months ago, and it seemed to work fine. Now, however, I get the following:: ~/astroconda/lib/python3.5/site-packages/astroquery/sdss/init.py:28: UserWarning: Experimental: SDSS has not yet been refactored to have its API match the rest of astroquery (but it's nearly there). warnings.warn("Experimental: SDSS has not yet been refactored to have its API " ~/astroconda/lib/python3.5/site-packages/astroquery/sdss/core.py:857: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default. AttributeError Traceback (most recent call last) ~/spectra/plot_spectra.py in &lt;module&gt;() 34 xid = SDSS.query_region(pos, spectro=True,radius=2*u.arcsec) 35 print(xid) ---&gt; 36 j_eleven = SDSS.get_spectra(matches=xid) 37 38 ~/astroconda/lib/python3.5/site-packages/astroquery/sdss/core.py in get_spectra(self, coordinates, radius, matches, plate, fiberID, mjd, timeout, cache, data_release, show_progress) 613 mjd=mjd, timeout=timeout, 614 data_release=data_release, --&gt; 615 show_progress=show_progress) 616 617 if readable_objs is not None: ~/astroconda/lib/python3.5/site-packages/astroquery/sdss/core.py in get_spectra_async(self, coordinates, radius, matches, plate, fiberID, mjd, timeout, get_query_payload, data_release, cache, show_progress) 585 link = linkstr.format( 586 base=conf.sas_baseurl, dr=data_release, --&gt; 587 instrument=row['instrument'].decode().lower(), 588 run2d=run2d, plate=row['plate'], 589 fiber=row['fiberID'], mjd=row['mjd']) AttributeError: 'str' object has no attribute 'decode' error. Not sure what I did wrong/differently... import numpy as np import scipy.interpolate as interp import matplotlib import matplotlib.pyplot as plt from astroML.plotting import setup_text_plots from astroquery.sdss import SDSS from astropy import coordinates as coords import astropy.units as u ## Find a spectrum using astroquery pos = coords.SkyCoord('165.24…
answer count: 0
has comment: http://stackoverflow.com/comment/85762424
has comment: http://stackoverflow.com/comment/85721940
type: UnansweredQuestion
tagged with: python
tagged with: astropy
has comment: http://stackoverflow.com/comment/85711451
has title: Issue with SDSS.get spectra in AstroPy
score: 0
has comment: http://stackoverflow.com/comment/85762625

http://stackoverflow.com/comment/85775097
score: 1
type: Comment
has text: Thanks for your kind words!
type: AnswerComment
comment on: http://stackoverflow.com/a/49372989

http://stackoverflow.com/a/51920899
has body: I think the primary reason is that your overhead from parallel beats the benefits. In another word, your square_int is too simple to earn any performance improvement via parallel. The square_int is so simple that passing input and output between processes may take more time than executing the function square_int. I modified your code by creating a square_int_batch function. It reduced the computation time a lot, though it is still more than the serial implementation. import time import numpy as np from joblib import Parallel, delayed def square_int(i): return i * i def square_int_batch(a,b): results=[] for i in range(a,b): results.append(square_int(i)) return results ndata = 1000000 ti = time.time() results = [] for i in range(ndata): results.append(square_int(i)) # results = [square_int(i) for i in range(ndata)] duration = np.round(time.time() - ti,4) print(f"standard computation: {duration} s" ) batch_num = 3 batch_size=int(ndata/batch_num) for njobs in [2,3,4] : ti = time.time() results = [] a = list(range(ndata)) # results = Parallel(n_jobs=njobs, )(delayed(square_int)(i) for i in range(ndata)) # results = Parallel(n_jobs=njobs, backend="multiprocessing")(delayed( results = Parallel(n_jobs=njobs)(delayed( square_int_batch)(i*batch_size,(i+1)*batch_size) for i in range(batch_num)) duration = np.round(time.time() - ti,4) print(f"{njobs} jobs computation: {duration} s" ) And the computation timings are standard computation: 0.3184 s 2 jobs computation: 0.5079 s 3 jobs computation: 0.6466 s 4 jobs computation: 0.4836 s A few other suggestions that will help reduce the time. Use list comprehension results = [square_int(i) for i in range(ndata)] to replace for loop in your specific case, it is faster. I tested. Set batch_num to a reasonable size. The larger this value is, the more overhead. It started to get significantly slower when batch_num exceed 1000 in my case. I used the default backend loky instead of multiprocessing. It is slightly faster, at least in my case…
answers question: http://stackoverflow.com/q/49381027
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90918260
accepted answer of: http://stackoverflow.com/q/49381027
upvote count: 9
type: Answer
score: 9

http://stackoverflow.com/comment/85568949
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49282797
has text: Thank you for responding I edited my code to what you have written here. It imports the module amazingly now but it does not give the user the raw_input where they can choose something other than port scanner...Could you help me?

http://stackoverflow.com/comment/85826305
has text: Sorry, just saw that you are on Windows. But you can also look through the output of `apm list --enabled` manually to check if the `language-python` package ist listed.
comment on: http://stackoverflow.com/q/49412041
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85733148
has text: Thanks All very helpful
comment on: http://stackoverflow.com/a/49365578
type: Comment
score: 0
type: AnswerComment

concatenation
tags question: http://stackoverflow.com/q/49287528
tags question: http://stackoverflow.com/q/49417146
tags question: http://stackoverflow.com/q/49439902
tags question: http://stackoverflow.com/q/49354447
tags question: http://stackoverflow.com/q/49382957
tags question: http://stackoverflow.com/q/49425238
tags question: http://stackoverflow.com/q/49395052
tags question: http://stackoverflow.com/q/49373620
type: Tag
tags question: http://stackoverflow.com/q/49326824
tag name: concatenation

http://stackoverflow.com/a/49307041
answers question: http://stackoverflow.com/q/49306922
accepted answer of: http://stackoverflow.com/q/49306922
upvote count: 2
downvote count: 0
type: Answer
score: 2
type: AcceptedAnswer
has body: Try shift the column by -6 before indexing it: ax[i].plot(data_df['col_B'].shift(-6)[101:200], color = 'red')

http://stackoverflow.com/a/49431567
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49431332
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49431332
has body: df['Filename'] = df['Filename'].apply(lambda x: x.replace(os.path.dirname(x), dst))
upvote count: 5
has comment: http://stackoverflow.com/comment/85865126
type: Answer
has comment: http://stackoverflow.com/comment/85865408

http://stackoverflow.com/comment/85685163
type: Comment
type: QuestionComment
has text: Yes, return a tuple: `return KingRow, KingColumn` then `KingRow, KingColumn = UserInput()`, but get rid of that infinite loop.
score: 2
comment on: http://stackoverflow.com/q/49342471

http://stackoverflow.com/q/49393185
has answer: http://stackoverflow.com/a/49407357
accepted answer: http://stackoverflow.com/a/56026476
answer count: 2
has answer: http://stackoverflow.com/a/56026476
tagged with: pythonnet
tagged with: .net
downvote count: 0
tagged with: python
has title: Pythonnet System.Object[,] to Pandas DataFrame or Numpy Array
type: AnsweredQuestion
tagged with: python.net
tagged with: pandas
score: 3
upvote count: 3
has body: I am using Pythonnet to call a C# function which returns a clr Object ( an n x m matrix). In python the type is System.Object[,]. How can I convert this variable to a Pandas DataFrame or something more manageable? Thank you.
possible better answer: http://stackoverflow.com/a/49407357
favorite count: 0
type: Question

http://stackoverflow.com/q/49310407
has comment: http://stackoverflow.com/comment/85623208
type: AnsweredQuestion
has title: Generate random audio or playing a file at different offset
tagged with: python
score: 2
tagged with: audio
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49483212
upvote count: 2
has answer: http://stackoverflow.com/a/49483212
has body: On Python 2.7 is there a way to generate an audio file or an audio data as a string, more especifically white noise. I'm using winsound.PlaySound(sound, flags) However with this function I can't control when the audio starts playing and I need Python to play a random white noise signal (even if it comes from the same file but starts playing at a different time). In other words, can someone help me generate a random white noise audio and then play it asynchronously in the background? Or can someone recommend me an audio module
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/85877434
comment on: http://stackoverflow.com/q/49437742
type: Comment
type: QuestionComment
has text: @roganjosh Seriously don't know why I didn't got that in any search result or in the SO "similar posts" when posting. I've gone through hundreds of pages. My bad obviously, but that's a bit strange.
score: 0

http://stackoverflow.com/comment/85665457
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49331376
type: AnswerComment
has text: After looking back at the way I was generating the boolean expression, I found an error that was dropping parenthesis. For some reason, I was not making the connection that Sympy would reduce the expression to False. Thanks for the help!

http://stackoverflow.com/comment/85872350
has text: Underscore works in the shell for this purpose.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49435233

http://stackoverflow.com/a/49381525
has body: You should never set the ticklabels without setting the ticks as well. What this essentially does is keeping an AutoLocator for the axes but using a FixedFormatter for the labels. So when using a FixedFormatter as is done with set_xticklabels always make sure to also use a FixedLocator, e.g. using set_xticks. ax.set_xticks(list(range(len(labels)))) ax.set_xticklabels(labels) Of course after setting the formatter and locator this way, you should not set them to something different later. So the following two lines need to be deleted from the code. ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49381274
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85764536
accepted answer of: http://stackoverflow.com/q/49381274
has comment: http://stackoverflow.com/comment/85764684
has comment: http://stackoverflow.com/comment/85764073
has comment: http://stackoverflow.com/comment/85763819
type: Answer
has comment: http://stackoverflow.com/comment/85764794

http://stackoverflow.com/a/49406287
answers question: http://stackoverflow.com/q/49325168
has body: Thanks to @Erwin Kalvelagen for pointing out GLPK's serial nature, after doing some experiments I migrated to Gurobi and now all my 10 CPU cores are being used by the Pyomo model.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49325168
type: AcceptedAnswer

http://stackoverflow.com/q/49408509
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/85818504
tagged with: flask-login
answer count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85818959
has title: Signout after user disconnects on Flask
has comment: http://stackoverflow.com/comment/85828592
type: Question
has answer: http://stackoverflow.com/a/49416610
has body: For those of you who have used flask-login will know the decorator fresh_login_required. I am trying to implement something similar by myself. It doesn't have to be a decorator. I just want to be able to do some works after the user has been totally disconnected (example: closed the browser). And is it a good idea to have a global integer variable to count the total active/online users? Thanks in advance :)
has answer: http://stackoverflow.com/a/49414926
has comment: http://stackoverflow.com/comment/85846771
has answer: http://stackoverflow.com/a/78508780
tagged with: python

http://stackoverflow.com/comment/85590177
score: 0
type: Comment
has text: I tried this and worked very well. Thanks for the prompt response. However, I get the below warning when I run the code C:\Users\R15445\AppData\Local\Continuum\anaconda3\lib\site-packages\ipykernel_launcher.py:3: 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
comment on: http://stackoverflow.com/a/49292608
type: AnswerComment

http://stackoverflow.com/comment/85612483
has text: Hmm i tried but it didn't work. I've edited post with more clear example where it shows that when called from inside task body, the task is routed incorrectly, but from outside of task body it's all ok...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49303053
score: 0

http://stackoverflow.com/comment/85688190
has text: oh really? I didn't know you needed to have some rep for inline images, sorry!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49339890

http://stackoverflow.com/q/49331227
tagged with: python
has comment: http://stackoverflow.com/comment/85665182
has comment: http://stackoverflow.com/comment/85665384
has body: I have a list containing: lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']] and I'm using radix sort to sort the string elements in the lst above. The output I'm trying to achieve is: lst = [[1,'FANTASTIC FOUR'],[20,'FANTASTIC FOUR'],[18,'PADDINGTON']] since the first list and the last list both shares the same string, they should be grouped together. I've tried writing a radix sort function to cater for this, but I'm getting the output: lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']] instead of: lst = [[1,'FANTASTIC FOUR'],[20,'FANTASTIC FOUR'],[18,'PADDINGTON']] Here's the code: def radix_sort(lst, length): for i in range (length-1, -1, -1): #for every letter "column" buckets = [[], [], [], [], [], [], [], [], [], [], [], [], [], [],[], [], [], [], [], [], [], [], [], [], [], []] j = 0 for word in lst: index = ord(word[j])-ord('A') buckets[index].append(word) #add to bucket lst[:] = [] #rebuild list for containedList in buckets: lst.extend(containedList) return lst lst = [[1, 'FANTASTIC FOUR'],[18, 'PADDINGTON'],[20, 'FANTASTIC FOUR']] n = len(lst) radix = [radix_sort(i, n) for i in lst] print(radix)
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85665535
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85664458
has comment: http://stackoverflow.com/comment/85664486
has comment: http://stackoverflow.com/comment/85665336
upvote count: 1
downvote count: 1
has title: Using radix sort to sort single lists within a list of list
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85677579
tagged with: radix-sort
has comment: http://stackoverflow.com/comment/85665463

http://stackoverflow.com/a/49417937
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49417286
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85843088
has comment: http://stackoverflow.com/comment/85855072
has body: I don't see your problem... This looks like answersing your question: from flask import Flask from multiprocessing import Process, Queue import time globalvar=0 app = Flask(__name__) @app.route('/') def index(): return "globvar in index=" + str(q.get()) # Now, it will return a value other than 0! def multiprocess(q): # global globalvar tried but same result i = 0 while 1: # for keep fresh value of i i += 1 variable = i % 10 print "i in multiprocess=" + str(i) q.put(variable) time.sleep(0.1) def flaskserver(): app.run(debug=True, host='127.0.0.1', port=7654, use_reloader=False) if (__name__ == '__main__'): q = Queue() p1 = Process(target=flaskserver) p2 = Process(target=multiprocess, args=(q,)) p1.start() p2.start() while 1: globalvar = q.get() print "globalvar in main=" + str(globalvar) time.sleep(0.1)
type: Answer
answers question: http://stackoverflow.com/q/49417286

http://stackoverflow.com/comment/85744802
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49371691
has text: I think `argparse` is confusing this `-1,2` with a optionals flag. `-1` can be a short optional, and the code to distinguish that from real numeric negatives is not robust. `--cb_ticks=1,2' should work.
score: 3

http://stackoverflow.com/comment/85725061
type: Comment
has text: Thank you Zipa, that was spot on. Made below change and the code worked like a charm. changed X = tf.get_collection('input:0') to X = graph.get_tensor_by_name('input:0') to fix the error
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49359909

http://stackoverflow.com/comment/85709030
has text: Yes, you have re-edited. Your original answer didn't have the indents.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49354207

http://stackoverflow.com/a/49288494
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49288384
accepted answer of: http://stackoverflow.com/q/49288384
type: Answer
has body: It is probably easier (and efficient/Pythonic) to use a for loop to achieve this: coin = ["BTC", "NEO", "ETH"] for i in coin: term = urllib.parse.quote("'" + i + "-BTC'") depth = client.get_order_book(term, limit=50)

http://stackoverflow.com/comment/97930554
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/55605151
has text: Would it be possible to add a start menu entry that launches Jupyter into a specific notebook?

http://stackoverflow.com/comment/85680543
comment on: http://stackoverflow.com/q/49340174
type: Comment
type: QuestionComment
score: 0
has text: Define 'not working' clearly. Do you get an error? Then include the full traceback. Do you get output you didn't expect? Then tell us what output you did get, and what it should have been.

http://stackoverflow.com/comment/85607925
type: Comment
comment on: http://stackoverflow.com/q/49302796
score: 0
type: QuestionComment
has text: @piRSquared updated question

http://stackoverflow.com/comment/85750447
type: Comment
comment on: http://stackoverflow.com/a/49374258
type: AnswerComment
has text: Okay. Then the question is who cares? Based on what the OP wanted, it shouldn't matter. If a user enters a real first name or last name, it's irrelevant because there will not be a number in the name. Maybe if they have a username program, which they didn't specify.
score: 0

http://stackoverflow.com/q/49408302
has comment: http://stackoverflow.com/comment/85818087
has body: I have a subprocess that either quits with a returncode, or asks something and waits for user input. I would like to detect when the process asks the question and quit immediately. The fact that the process asks the question or not is enough for me to decide the state of the system. The problem is that I cannot read the question because the child process probably does not flush standard output. So I cannot rely on parsing subprocess.Popen().stdout: when trying to read it, well, it blocks because input is being read first. A bit like this # ask.py, just asks something without printing anything if a condition is met # here, we'll say that the condition is always met input() Of course, the actual subprocess is a third party binary, and I cannot modify it easily to add the necessary flush calls, which would solve it. I could also try the Windows equivalent of unbuffer (What is the equivalent of unbuffer program on Windows?) which is called winpty, which would (maybe) allow me to detect output and solve my current issue, but I'd like to keep it simple and I'd like to solve the standard input issue first... I tried... well, lots of things that don't work, including trying to pass a fake file as stdin argument, which doesn't work because subprocess takes the fileno of the file, and we cannot feed it rubbish... p = subprocess.Popen(["python","ask.py"],...) Using communicate with a string doesn't work either, because you cannot control when the string is read to be fed to the subprocess (probably through a system pipe). Those questions were promising but either relied on standard output, or only apply to Linux Detecting when a child process is waiting for input How can I know whether my subprocess is waiting for my input ?(in python3) What I'm currently doing is running the process with a timeout, and if the timeout is reached, I then decide that the program is blocked. But it costs the timeout waiting time. If I could decide as soon as stdin is read by the subprocess, that …
tagged with: windows
has comment: http://stackoverflow.com/comment/86233792
has comment: http://stackoverflow.com/comment/86266631
linked to: http://stackoverflow.com/q/18107541
has comment: http://stackoverflow.com/comment/86266748
linked to: http://stackoverflow.com/q/11516258
tagged with: python
has comment: http://stackoverflow.com/comment/86234014
tagged with: io-redirection
has comment: http://stackoverflow.com/comment/85818141
has answer: http://stackoverflow.com/a/49631900
score: 11
type: AnsweredQuestion
tagged with: subprocess
linked to: http://stackoverflow.com/q/12180073
has comment: http://stackoverflow.com/comment/85846593
possible better answer: http://stackoverflow.com/a/49603436
accepted answer: http://stackoverflow.com/a/49631900
has answer: http://stackoverflow.com/a/49603436
has title: How to detect when subprocess asks for input in Windows
downvote count: 1
has comment: http://stackoverflow.com/comment/85848700
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85837737
has comment: http://stackoverflow.com/comment/86266692
has comment: http://stackoverflow.com/comment/85845162
answer count: 2
upvote count: 12

http://stackoverflow.com/q/49344301
linked to: http://stackoverflow.com/q/29529641
has comment: http://stackoverflow.com/comment/85688803
tagged with: python
accepted answer: http://stackoverflow.com/a/49344598
type: Question
has answer: http://stackoverflow.com/a/49344598
possible better answer: http://stackoverflow.com/a/49344579
answer count: 2
has title: How can I get the next string, in alphabetical DESCENDING order, in Python?
has answer: http://stackoverflow.com/a/49344579
has body: I need a simple python program that looks for a string in a list and if it doesn't find it generates the next one in alphabetical DESCENDING ORDER .By that, I meant if it does not find 'abz' it will generate ac deleting the last char when it reaches 'z'. Another example: I have a list like: list = ['allena', 'allend','alphosis','alpinist', 'alternative'] Assuming I don't know what is in the list. After the function find allend in the list it will check for allene to allenz, and after alleo to allez and after alle to allz ... Thereby by removing the last char in the string everytime it is 'z'.... the function will reach alp and alt... until it reaches a The function will change the last character of a string and remove it when it becomes 'z' until it remains the first char only. Thank you guys!
tagged with: string
tagged with: sorting
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49439265
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49439182
type: Answer
has body: This is one way. price = df[df['property_name'] == 'price'].set_index(['date', 'store'])['property_value'] quantity = df[df['property_name'] == 'quantity'].set_index(['date', 'store'])['property_value'] rev = (price * quantity).reset_index().assign(property_name='revenue') df = pd.concat([df, rev], ignore_index=True) Explanation Derive price and quantity dataframes via slicing, index by date and store. Calculate rev via price * quantity on index; add property_name columns. Concatenate along axis=0 by default (index). Result date property_name property_value store 0 2013-06-20 price 101 1 1 2013-06-20 price 201 2 2 2013-06-21 price 301 1 3 2013-06-21 price 401 2 4 2013-06-20 quantity 1000 1 5 2013-06-20 quantity 2000 2 6 2013-06-21 quantity 3000 1 7 2013-06-21 quantity 4000 2 8 2013-06-20 revenue 101000 1 9 2013-06-20 revenue 402000 2 10 2013-06-21 revenue 903000 1 11 2013-06-21 revenue 1604000 2
accepted answer of: http://stackoverflow.com/q/49439182

http://stackoverflow.com/comment/85706076
score: 1
type: Comment
has text: No; `virtualenv` just manages *which* Python installation is used to run code. In the extreme, it installs a version of Python in your virtual environment directory. In no way is it capable of running Python code itself.
comment on: http://stackoverflow.com/q/49352930
type: QuestionComment

http://stackoverflow.com/a/49358655
score: 0
answers question: http://stackoverflow.com/q/49284908
type: Answer
has body: @ShadowRanger (I forgot to thank you for your answer). In fact in my case the reloads() are necessary during the development for the following reason. The Python interpreter is embedded in a software written in C++. The "embedded interpreter" allows to access some of the C++ data; in addition to that, it allows to run some Python "apps" (small applications with a GUI) in the context of the C++ software (i.e. able to access and modify some C++ data). When developing such an "app", of course it is needed to run it again and again after every few modifications. This makes reloads() necessary since the embedded interpreter stays alive between each run. Another possibility would be to restart the embedded Python interpreter before restarting the App, but at this time it is not possible. A problem appears with reloads() since it is possible to execute two or more identical "apps" mentioned above in the embedded interpreter. If reloads are present in the imported modules, objects created in the first started "apps" do not recognize their mother/child (errors similar to the one of my original post appear). This is why in this framework it is now clear that I should (i) use reload() only during development (debug flag), (ii) run only one "app" at a time during development --- the scenario where multiple "apps" run at the same time should be tested only in release code (no debug flag --- so no reload()).

http://stackoverflow.com/q/49314573
has title: Pyhdbcli SAP HANA Connection DLL Load Fail
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85639923
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/85636178
type: UnansweredQuestion
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/49659524
has body: Long time lurker hoping to get some assistance with connecting Python to SAP HANA. I previously had it working perfectly however I recently wiped my Anaconda install to get a clean slate (start up performance issues with Jupyter) and now I can't get it to work at all! When I try and run the connection via sqlalchemy I get the following traceback: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\hdbcli\dbapi.py in &lt;module&gt;() 10 import sys 11 ---&gt; 12 import pyhdbcli 13 from .resultrow import ResultRow 14 ImportError: DLL load failed: The specified module could not be found. I have tried to follow the tutorial below (copy the 5 files into the python Lib folder)... http://www.saphanacentral.com/p/power-of-python-integrated-with-sap-hana.html However I don't seem to even have a Python folder under C:\Program Files\sap\hdbclient as they have suggested in the tutorial. Therefore I assumed that I should put it in with the rest of my Python packages under C:\Users\myname\AppData\Local\Continuum\anaconda3\Lib So far without any success. I would really appreciate any suggestions! Thanks!
upvote count: 1
favorite count: 0
tagged with: hana

http://stackoverflow.com/comment/85752467
comment on: http://stackoverflow.com/q/49375222
score: 0
has text: there's [implicit and explicit](https://www.guru99.com/implicit-explicit-waits-selenium.html) waits you can use.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49425147
has comment: http://stackoverflow.com/comment/85851351
type: UnansweredQuestion
has body: I created a simple Multi-Layer-Perceptron to test TensorFlow Serving. It simply takes two numbers and should predict the sum of those two numbers. Here is the code that I wrote: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import logging import numpy as np import tensorflow as tf tf.app.flags.DEFINE_integer("model_version", 1, "version number of the model.") tf.app.flags.DEFINE_string("work_dir", "/tmp", "Working directory.") FLAGS = tf.app.flags.FLAGS def main(): # DATA PREPARATION # ================================================ data_train = np.array( [[1, 3], [2, 5], [3, 1], [3, 3], [4, 2], [7, 1], [8, 1], [2, 2], [5, 1], [1, 7], [0, 1], [0, 5], [0, 7], [0, 8], [1, 1], [1, 2], [0, 0], [1, 8]] ) labels_train = np.array( [4, 7, 4, 6, 6, 8, 9, 4, 6, 8, 1, 5, 7, 8, 2, 3, 0, 9] ) # specify that all features have real-value data feature_columns = [tf.feature_column.numeric_column("x", shape=[2])] # CREATE CLASSIFIER # ================================================ # build 3 layer dnn with 10, 20, 10 units respectively. classifier = tf.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=10, model_dir="/tmp/addition_model" ) # TRAINING PHASE # ================================================ # define the training inputs train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": data_train}, y=labels_train, num_epochs=None, shuffle=True ) # train model classifier.train(input_fn=train_input_fn, steps=10000) # PREDICT NEW SAMPLES (LOCAL) # ================================================ # new_samples = np.array( # [[0, 6]], # dtype=np.float32 # ) # # predict_input_fn = tf.estimator.inputs.numpy_input_fn( # x={"x": new_samples}, # num_epochs=1, # shuffle=False # ) # # predictions = list(classifier.predict(input_fn=predict_input_fn)) # predicted_classes = [p["classes"] for p in predictions] # # print("Predictions: {}".format(predicted_classes)…
tagged with: tensorflow-serving
tagged with: python
has title: TensorFlow Serving: How to get prediction, ModelSpec missing
downvote count: 0
has answer: http://stackoverflow.com/a/49425290
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/91845851
score: 0
comment on: http://stackoverflow.com/q/49371500
type: QuestionComment
has text: Repl.it doesn't currently support tkinter but it supports a GUI library called REMI. You can see an example here: https://repl.it/@amasad/tictactoe
type: Comment

http://stackoverflow.com/q/49376887
has body: Say I have a pyspark dataframe: df.show() +-----+---+ | x | y| +-----+---+ |alpha| 1| |beta | 2| |gamma| 1| |alpha| 2| +-----+---+ I want to count how many occurrence alpha, beta and gamma there are in column x. How do I do this in pyspark?
score: 7
answer count: 1
has title: How to count frequency of each categorical variable in a column in pyspark dataframe?
downvote count: 1
favorite count: 0
type: Question
tagged with: apache-spark-sql
upvote count: 8
type: UnansweredQuestion
tagged with: pyspark
has comment: http://stackoverflow.com/comment/103772154
tagged with: python
has comment: http://stackoverflow.com/comment/85777228
has answer: http://stackoverflow.com/a/49376888

http://stackoverflow.com/q/49377595
tagged with: django-views
has title: Django template - use 2 models to filter results
has body: Apologies if my question is not that clear. I'm new to Django and it's my first time to ask questions here as I can't seem to find solutions to my problem. I've done research on how to use multiple models in Django template and succeeded to do so, however, one of my requirement is that each trucker in the list should show corresponding number of registered truck units but I can't seem to do this. The output should be like this: Truckers List Registered Trucker Number of units Trucker #1 10 Trucker #2 5 ... Trucker #n 3 Should you have suggestions I highly appreciate it. Im using Django version 2.0.1 and Python 3.6 on Windows if that's relevant. Here is my code: models.py class Trucker(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class TruckUnit(models.Model): plate_number = models.CharField(max_length=7) trucker = models.ForeignKey(Trucker, related_name='truckunits', on_delete=models.CASCADE) def __str__(self): return self.plate_number views.py class TruckerList(generic.ListView): model = Trucker context_object_name = 'trucker_list' queryset = Trucker.objects.all().order_by('name') template_name = 'trip_monitor/trucker_list.html' def get_context_data(self. **kwargs): context = super(TruckerList, self).get_context_data(**kwargs) context['units'] = TruckUnit.objects.all() context['truckers'] = self.queryset return context urls.py from django.urls import path from . import views urlpatterns = [ path('truckers/', views.TruckerList.as_view(), name='trucker_list'), ] trucker_list.html {% extends 'base.html' %} {% block content %} Trucker List {% if trucker_list %} Registered Truckers Number of units {% for trucker in trucker_list %} {{ trucker.name }} {{ units.count }} {% endfor %} {% else %} No registered truckers yet {% endif %} {% endblock %}
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
answer count: 2
accepted answer: http://stackoverflow.com/a/49378923
downvote count: 0
has answer: http://stackoverflow.com/a/49378923
tagged with: django
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/49378804
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49378804

http://stackoverflow.com/a/49344032
has body: Strings are iterable so you can pass them into sorted like so: def largest_number(num): num = str(num) ordered = ''.join(sorted(num, reverse=True)) return int(ordered) largest_number(87491) &gt;&gt; 98741 sorted returns a list, so sorted('87491', reverse=True) will return: ['9', '8', '7', '4', '1'] Passing the list into join(link to explanation of the join method) will return: '98741'
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49343931
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49343931

http://stackoverflow.com/comment/85644866
has text: I think this whole thing is out of scope of this question... If I were you I'd open/search a question about how to inspect the imports of a python file
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49321689
score: 0

http://stackoverflow.com/q/49388276
has comment: http://stackoverflow.com/comment/85778381
tagged with: default-value
tagged with: python
has comment: http://stackoverflow.com/comment/85778511
tagged with: module
has comment: http://stackoverflow.com/comment/85778100
score: 0
has body: Is there a golden standard to implement default values in python modules if there are lots of defaults? I tend to use classes with the defaults stored as static values. """ __init__.py """ class Default(object): class Address(object): server = "https://stackoverflow.com" class SomeValues(object): bar = 3 default_Server = Default.Address.server This way I can group them and easily access them. However, I am not sure whether this is good style or if there is a better or more common way to implement this.
answer count: 0
has comment: http://stackoverflow.com/comment/85780580
has comment: http://stackoverflow.com/comment/85809116
has comment: http://stackoverflow.com/comment/85778092
upvote count: 1
has comment: http://stackoverflow.com/comment/85778445
tagged with: default
downvote count: 1
favorite count: 0
type: Question
has title: Module default implementation standard?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85778693

http://stackoverflow.com/q/49402888
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85814401
accepted answer: http://stackoverflow.com/a/49407539
has title: How to get text which has no HTML tag | Add multiple delimiters in split
tagged with: python
type: AnsweredQuestion
tagged with: xpath
has answer: http://stackoverflow.com/a/49407539
has body: Following XPath select div element with class ajaxcourseindentfix and split it from Prerequisite and gives me all the content after prerequisite. div = soup.select("div.ajaxcourseindentfix")[0] " ".join([word for word in div.stripped_strings]).split("Prerequisite: ")[-1] My div can have not only prerequisite but also the following splitting points: Prerequisites Corerequisite Corerequisites Now, whenever I have Prerequisite, above XPath works fine but whenever anything from above three comes, the XPath fails and gives me the whole text. Is there a way to put multiple delimiters in XPath? Or how do I solve it? Sample pages: Corequisite URL: http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&amp;coid=96106&amp;show Prerequisite URL: http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&amp;coid=96564&amp;show Both: http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&amp;coid=98590&amp;show [Old Thread] - How to get text which has no HTML tag
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/49333626
answer count: 1
tagged with: ixmldomelement
favorite count: 0
has comment: http://stackoverflow.com/comment/85829272
type: Question

http://stackoverflow.com/a/49390959
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49390553
score: 1
type: Answer
has body: Looks like you are trying to pass a JSON string to proc_call, so do just that. Create a suitable Python construct, encode as JSON, and pass it as the argument: import json start_date = datetime.date(2018, 3, 10) end_date = datetime.date(2018, 3, 16) arg0 = {"start_date": start_date, "end_date": end_date, "foo": "1", "foo2": 2} proc_call = text('call schema.proc_call(:arg0)') results = pd.read_sql_query(proc_call, con=connection, params={"arg0": json.dumps(arg0)}) The error is the result of trying to use placeholders inside a string literal. The end result is something along the lines of '{"start_date":"'2018-03-10'", ...}' which is the string literal '{"start_date":"' followed by 2018-03-10 and so on, which is not valid syntax. You could also take using bound parameters a step further and specify their type explicitly: from sqlalchemy import bindparam, JSON start_date = datetime.date(2018, 3, 10) end_date = datetime.date(2018, 3, 16) arg0 = {"start_date": start_date, "end_date": end_date, "foo": "1", "foo2": 2} proc_call = text('call schema.proc_call(:arg0)') proc_call = proc_call.bindparams(bindparam('arg0', type_=JSON)) results = pd.read_sql_query(proc_call, con=connection, params={"arg0": arg0})
accepted answer of: http://stackoverflow.com/q/49390553
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85730981
has text: I am almost certain OP's data does not even remotely resemble this perfect MCVE. They have an array of ragged lists, but for some reason they seem to be dodging... ah :|
comment on: http://stackoverflow.com/a/49364704
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/110851780
score: 0
type: Comment
comment on: http://stackoverflow.com/a/54318365
type: AnswerComment
has text: This does sometime cause issues where it fails to kill the subprocess and spawns a new one. Any suggestions?

http://stackoverflow.com/comment/85719921
type: AnswerComment
has text: update-2 works incorrectly I want to find all the products with just one complex query in the database, without calculating something in python, since now I'm looking for the right products in python and the response takes 0.6 seconds. I expect that the response time will grow in future..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49351380

http://stackoverflow.com/q/49380186
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85764141
has body: I'm trying to create a script to download subtitles from one specific website. Please read the comments in the code. Here's the code: import requests from bs4 import BeautifulSoup count = 0 usearch = input("Movie Name? : ") search_url = "https://www.yifysubtitles.com/search?q="+usearch base_url = "https://www.yifysubtitles.com" print(search_url) resp = requests.get(search_url) soup = BeautifulSoup(resp.content, 'lxml') for link in soup.find_all("div",{"class": "media-body"}): #Get the exact class:'media-body' imdb = link.find('a')['href'] #Find the link in that class, which is the exact link we want movie_url = base_url+imdb #Merge the result with base string to navigate to the movie page print("Movie URL : {}".format(movie_url)) #Print the URL just to check.. :p next_page = requests.get(movie_url) #Soup number 2 begins here, after navigating to the movie page soup2 = BeautifulSoup(next_page.content,'lxml') #print(soup2.prettify()) for links in soup2.find_all("tr",{"class": "high-rating"}): #Navigate to subtitle options with class as high-rating for flags in links.find("td", {"class": "flag-cell"}): #Look for all the flags of subtitles with high-ratings if flags.text == "English": #If flag is set to English then get the download link print("After if : {}".format(links)) for dlink in links.find("td",{"class": "download-cell"}): #Once English check is done, navigate to the download class "download-cell" where the download href exists half_dlink = dlink.find('a')['href'] #STUCK HERE!!!HERE'S THE PROBLEM!!! SOS!!! HELP!!! download = base_url + half_dlink print(download) I'm getting the following error : File "C:/Users/PycharmProjects/WhatsApp_API/SubtitleDownloader.py", line 24, in &lt;module&gt; for x in dlink.find("a"): TypeError: 'NoneType' object is not iterable
has comment: http://stackoverflow.com/comment/85763668
downvote count: 0
tagged with: python
has title: BeautifulSoup : Why is the "dlink_find('a')['href']" not working?
has comment: http://stackoverflow.com/comment/85763874
has comment: http://stackoverflow.com/comment/85762794
has comment: http://stackoverflow.com/comment/85764236
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49382148
linked to: http://stackoverflow.com/q/3887381
accepted answer: http://stackoverflow.com/a/49381812
has answer: http://stackoverflow.com/a/49382148
has comment: http://stackoverflow.com/comment/85763039
has answer: http://stackoverflow.com/a/49381812
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/a/49344128
has comment: http://stackoverflow.com/comment/85786791
has comment: http://stackoverflow.com/comment/85840504
answers question: http://stackoverflow.com/q/49344116
type: Answer
has comment: http://stackoverflow.com/comment/86214840
has comment: http://stackoverflow.com/comment/86061395
has comment: http://stackoverflow.com/comment/86174968
has comment: http://stackoverflow.com/comment/86188034
has comment: http://stackoverflow.com/comment/85778320
score: 0
has comment: http://stackoverflow.com/comment/85726585
has body: from matplotlib.finance import quotes_historical_yahoo should be on the same line like so: from matplotlib.finance import quotes_historical_yahoo Alternatively, you can break lines: from matplotlib.finance \ import quotes_historical_yahoo
has comment: http://stackoverflow.com/comment/85712798
has comment: http://stackoverflow.com/comment/85840608

http://stackoverflow.com/comment/85646114
comment on: http://stackoverflow.com/q/49321748
type: QuestionComment
score: 0
has text: @CBroe Just out of curiosity, I checked Facebook's ToS here: https://www.facebook.com/terms.php Are you sure this type of automation is actually violating their ToS? Maybe I missed it, but I haven't found anything that would explicitly forbid this.
type: Comment

http://stackoverflow.com/comment/85850370
type: QuestionComment
comment on: http://stackoverflow.com/q/49406100
score: 0
has text: @MichaelMacAskill I have tryed and everything is fine now with openpyxl. I just uninstalled it and reinstalled it. Thank you for your advise.
type: Comment

http://stackoverflow.com/a/49289415
has comment: http://stackoverflow.com/comment/85607292
has comment: http://stackoverflow.com/comment/85606915
answers question: http://stackoverflow.com/q/49287395
has comment: http://stackoverflow.com/comment/85606656
has comment: http://stackoverflow.com/comment/85607373
has comment: http://stackoverflow.com/comment/85607231
has body: This is one solution via collections.defaultdict. The triple-merge method (as detailed by @scomes) is the conventional algorithm, but you might find this one easier to maintain. In the solution below, df1 is CodeA dataset and df2 is CodeB dataset. from collections import defaultdict from itertools import chain d = defaultdict(list) # create full set from df2 and test set from df1 full_set = list(zip(df2['CodeB'].astype(str), df2['Field2'])) test_set = set(df1['CodeA'].astype(str).str.rstrip('0')) # create dictionary of mapping (loopy) for k in test_set: d[k].extend([i for i in full_set if i[0].startswith(k)]) # map dictionary df1['Mapped'] = df1['CodeA'].astype(str).str.rstrip('0').map(d) # expand column of list of tuples lens = list(map(len, df1['Mapped'])) res = pd.DataFrame({'Example': np.repeat(df1['Example'], lens), 'CodeA': np.repeat(df1['CodeA'], lens), 'Field1': np.repeat(df1['Field1'], lens), 'Mapped': list(chain.from_iterable(df1['Mapped']))}) # split column of tuples res'CodeB', 'Field2' = res['Mapped'].apply(pd.Series) # drop helper column res = res.drop('Mapped', 1) Result CodeA Example Field1 CodeB Field2 0 2500 1 w 2525 b 0 2500 1 w 2522 f 1 4110 2 x 4113 c 2 2525 3 y 2525 b 3 5345 4 z 5345 h
type: Answer
score: 0

http://stackoverflow.com/comment/85658811
has text: Thanks for the answer. A question first, should K.gradient(model.input, model.output) be K.gradient(model.output, model.input) in your answer? Then, I have tried to use model.input as a parameter. Now it works as it returns [<tf.Tensor 'gradients/dense_1/MatMul_grad/MatMul:0' shape=(?, 784) dtype=float32>].
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49317312

http://stackoverflow.com/q/49368189
accepted answer: http://stackoverflow.com/a/49368229
tagged with: python
has answer: http://stackoverflow.com/a/49368229
score: 0
answer count: 1
has title: Remove all rows of a Dataframe in which at least one contains a specific id
type: Question
type: AnsweredQuestion
has body: I have the following dataframe with user statuses: id name email status_id 23 Alex a@a.com 1 23 Alex a@a.com 2 23 Alex a@a.com 3 25 Bill b@b.com 2 25 Bill b@b.com 3 28 Claire c@c.com 3 29 David d@d.com 1 29 David d@d.com 2 I want to remove from the dataframe all users that has at least one row in which the status_id is equal to 1, in this case, the expected dataframe is: id name email status_id 25 Bill b@b.com 2 25 Bill b@b.com 3 28 Claire c@c.com 3 It would also be even better if I could get only the users without repetition, so the final dataframe would be: id name email 25 Bill b@b.com 28 Claire c@c.com
tagged with: pandas

http://stackoverflow.com/comment/85855205
type: Comment
comment on: http://stackoverflow.com/a/49426852
score: 0
type: AnswerComment
has text: I know... it could be really practical

http://stackoverflow.com/q/49347446
has answer: http://stackoverflow.com/a/49357656
possible better answer: http://stackoverflow.com/a/49357656
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49414420
accepted answer: http://stackoverflow.com/a/49414420
has body: I have been using the python client API of ML engine to create training jobs of some canned estimators. What I'm not able to do is get the path of the saved_model.pb on GCS because the path it is stored in has a timestamp as a dir name. Is there anyway I can get this using a regular expression or something on python client, so that I'll be able to deploy the model with correct path. The path seems to be in this format right now - gs://bucket_name/outputs/export/serv/timestamp/saved_model.pb UPDATE Thanks shahin for the answer. So I wrote this, which gives me the exact path that I can pass to the deploy_uri for ml engine. from google.cloud import storage def getGCSPath(prefix): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) mlist = bucket.list_blobs(prefix=prefix) for line in mlist: if 'saved_model.pb' in line.name: return line.name[:-14] # print getGCSPath('output/export/serv/')
tagged with: google-cloud-ml
tagged with: python
tagged with: google-cloud-storage
type: AnsweredQuestion
score: 0
answer count: 2
has title: Get the path of saved_model.pb after training on ML engine

http://stackoverflow.com/a/49319347
score: 0
answers question: http://stackoverflow.com/q/49318170
has comment: http://stackoverflow.com/comment/85639949
has body: You may want to select only the integer rows: import pandas as pd d = {'A': ["Location1", "Location2", 1, 2], 'B': [1, 2, 3, 4]} df = pd.DataFrame(data=d) df_numeric = df[pd.to_numeric(df.A, errors='coerce').notnull()] print(df_numeric) A B 2 1 3 3 2 4 Grouped by A: df_numeric_grouped_by_A = df_numeric.groupby("A").mean() print(df_numeric_grouped_by_A) B A 1 3 2 4
type: Answer

http://stackoverflow.com/comment/85795433
comment on: http://stackoverflow.com/q/49389873
score: 0
type: Comment
type: QuestionComment
has text: killed on the bash output screen.

http://stackoverflow.com/q/49395923
has title: How to check if column of datetime values is in a list of dates?
type: UnansweredQuestion
has body: So I have a column with a list of dates in it. I have a list/array with a set of specific dates in it. I want to assign a new column in my dataframe with true/false as to whether or not the specific date was in the list. I have the following, but it doesn't work and I'm not sure why. __DATELIST = [date(2017, 7, 4), date(2016, 7, 4), ...] def isholiday(x): return x in __DATELIST df['isholiday'] = df['date'].apply(isholiday) Any thoughts? The above is always false.
has comment: http://stackoverflow.com/comment/85793720
tagged with: python
has comment: http://stackoverflow.com/comment/85793736
has answer: http://stackoverflow.com/a/49395992
has comment: http://stackoverflow.com/comment/85793758
has answer: http://stackoverflow.com/a/49396205
score: 0
tagged with: pandas
tagged with: datetime
tagged with: dataframe
type: Question
answer count: 2

http://stackoverflow.com/comment/112047438
has text: Sequences are `Iterable` as a consequence of needing the `__getitem__` method, not simply being `Iterable`.
comment on: http://stackoverflow.com/a/56769160
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49344325
has comment: http://stackoverflow.com/comment/85693127
answers question: http://stackoverflow.com/q/49339739
type: AcceptedAnswer
score: 0
type: Answer
has body: The cmd shell doesn't understand Python's Unicode escape sequences, so you are receiving literal ASCII characters for the escape codes. If you want to support translating them, you could change you main call to: main(args.data.encode(sys.stdin.encoding).decode('unicode-escape')) And then your output will be: i'm deciding between Firestik Firefly, 4' 200w, &amp; Firestik FS-3BK, 3' 650w. Is one better? It's for recreational use on and off road. thank you!
accepted answer of: http://stackoverflow.com/q/49339739

http://stackoverflow.com/q/49413824
tagged with: pandas.excelwriter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85874903
has comment: http://stackoverflow.com/comment/85877526
tagged with: python
has comment: http://stackoverflow.com/comment/85875889
has comment: http://stackoverflow.com/comment/85878816
score: 0
has comment: http://stackoverflow.com/comment/86052538
has title: Modifying an existing excel workbook's multiple worksheets based on pandas dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/85879467
tagged with: openpyxl
linked to: http://stackoverflow.com/q/36447758
answer count: 1
has answer: http://stackoverflow.com/a/49416906
upvote count: 1
downvote count: 1
has body: I currently have an excel file with, for minimally viable example, say 3 sheets. I want to change 2 of those sheets to be based on new values coming from 2 pandas dataframes (1 dataframe for each sheet). This is the code I currently have: from openpyxl.writer.excel import ExcelWriter from openpyxl import load_workbook path = r"Libraries\Documents\Current_Standings.xlsx" book = load_workbook('Current_Standings.xlsx') writer = pd.ExcelWriter(path, 'Current_Standings.xlsx', engine='openpyxl') writer.book = writer Blank_Propensity_Scores.to_excel(writer, sheet_name = 'Blank_Propensity.xlsx') Leads_by_Rep.to_excel(writer,sheet_name = 'Leads_by_Rep.xlsx') writer.save() when I run this I get the following error message, not sure why, because every stack overflow answer I have looked at has only 1 item for openpyxl: TypeError: __new__() got multiple values for argument 'engine' I also tried playing around with getting rid of the engine='openpyxl' argument but when I do that I get the following error message instead: ValueError: No Excel writer 'Current_Standings.xlsx'
has comment: http://stackoverflow.com/comment/85861110
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49418627
score: 0
has comment: http://stackoverflow.com/comment/85839271
tagged with: list
has answer: http://stackoverflow.com/a/49418739
answer count: 3
upvote count: 2
downvote count: 2
tagged with: string
has answer: http://stackoverflow.com/a/49418659
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49418644
has comment: http://stackoverflow.com/comment/85839069
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85838918
tagged with: python
has title: Turn a list of variable length into multiple lists
has body: I am writing a script that takes user input of however many characters and I want to put each one of the characters into its own list to be then manipulated. input = AVI Output: A = ['A'] V = ['V'] I = ['I'] I was able to get it into a single list like this: ['A','V','I'] but that becomes too confusing for what I want to do later.

http://stackoverflow.com/comment/85636142
has text: @Ev.Kounis sometimes I find `chain` far more readable as to what it's doing. The elements it's going to add can be shown on the left (thus (to me at least) a bit more obvious) rather than in a nested for-loop comp - which can for some still take a bit of deciphering...
comment on: http://stackoverflow.com/a/49317362
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49342925
downvote count: 0
has body: Im trying ti replicate a sentence classification model from this github https://github.com/bgmartins/sentence-classification/blob/master/sentence-classification.py Here is my code: data = [ ( row["sentence"] , row["label"] ) for row in csv.DictReader(open("./test-data.txt"), delimiter='\t', quoting=csv.QUOTE_NONE) ] random.shuffle( data ) train_size = int(len(data) * percent) train_texts = [ txt.lower() for ( txt, label ) in data[0:train_size] ] test_texts = [ txt.lower() for ( txt, label ) in data[train_size:-1] ] train_labels = [ label for ( txt , label ) in data[0:train_size] ] test_labels = [ label for ( txt , label ) in data[train_size:-1] ] num_classes = len( set( train_labels + test_labels ) ) tokenizer = Tokenizer(nb_words=max_features, lower=True, split=" ") tokenizer.fit_on_texts(train_texts) train_sequences = sequence.pad_sequences( tokenizer.texts_to_sequences( train_texts ) , maxlen=max_sent_len ) test_sequences = sequence.pad_sequences( tokenizer.texts_to_sequences( test_texts ) , maxlen=max_sent_len ) train_matrix = tokenizer.texts_to_matrix( train_texts ) test_matrix = tokenizer.texts_to_matrix( test_texts ) embedding_weights = np.zeros( ( max_features , embeddings_dim ) ) for word,index in tokenizer.word_index.items(): if index &lt; max_features: try: embedding_weights[index,:] = embeddings[word] except: embedding_weights[index,:] = np.random.rand( 1 , embeddings_dim ) le = preprocessing.LabelEncoder( ) le.fit( train_labels + test_labels ) train_labels = le.transform( train_labels ) test_labels = le.transform( test_labels ) But when I try to fit the LSTM: model = Sequential() model.add(Embedding(max_features, embeddings_dim, input_length=max_sent_len, mask_zero=True, weights=[embedding_weights] )) model.add(Dropout(0.25)) model.add(LSTM(output_dim=embeddings_dim , activation='sigmoid', inner_activation='hard_sigmoid', return_sequences=True)) model.add(Dropout(0.25)) model.add(LSTM(output_dim=embeddings_dim , activation='sigmoid', inner_activation='h…
score: 1
has answer: http://stackoverflow.com/a/49347968
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52047243
tagged with: python
tagged with: lstm
answer count: 2
has title: Keras: got an unexpected keyword argument 'class_mode'

http://stackoverflow.com/comment/85752500
comment on: http://stackoverflow.com/q/49374091
score: 0
type: QuestionComment
has text: I highly doubt that a pandas dataframe will provide any sort of performance advantage over plain Python data structures (or your own custom classes). Pandas works well for numeric, panel data. You've left the realm of subtle and efficient pandas when you decided to force a Json blob into an object dtyped dataframe.
type: Comment

http://stackoverflow.com/q/49404275
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85896563
tagged with: python
has title: Getting started with Pyspark
has comment: http://stackoverflow.com/comment/85814902
has comment: http://stackoverflow.com/comment/85846509
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/85812866
has body: I am trying out pyspark on windows by following this article. The article asks to run pyspark from command prompt. When I run pyspark in command prompt, it starts jupyter notebook. But in example, it seems that running pyspark in command line starts interactive command line python shell. Why is this so? The article next asks to read readme file: &gt;&gt;&gt;textFile = spark.read.text("README.md") I tried running that in jupyter notebook. But I got following error: --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) D:\Sanjeev\Programs\spark\spark-2.3.0-bin-hadoop2.7\python\pyspark\sql\utils.py in deco(*a, **kw) 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: D:\Sanjeev\Programs\spark\spark-2.3.0-bin-hadoop2.7\python\lib\py4j-0.10.6-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name) 319 "An error occurred while calling {0}{1}{2}.\n". --&gt; 320 format(target_id, ".", name), value) 321 else: Py4JJavaError: An error occurred while calling o30.text. : org.apache.spark.sql.AnalysisException: java.lang.RuntimeException: ExitCodeException exitCode=-1073741515: ; at org.apache.spark.sql.hive.HiveExternalCatalog.withClient(HiveExternalCatalog.scala:106) at org.apache.spark.sql.hive.HiveExternalCatalog.databaseExists(HiveExternalCatalog.scala:194) at org.apache.spark.sql.internal.SharedState.externalCatalog$lzycompute(SharedState.scala:114) at org.apache.spark.sql.internal.SharedState.externalCatalog(SharedState.scala:102) at org.apache.spark.sql.hive.HiveSessionStateBuilder.externalCatalog(HiveSessionStateBuilder.scala:39) at org.apache.spark.sql.hive.HiveSessionStateBuilder.catalog$lzycompute(HiveSessionStateBuilder.scala:54) at org.apache.spark.sql.hive.HiveSessionStateBuilder.catalog(HiveSessionStateBuilder.scala:52) at org.apache.spark.sql.hive.HiveSessionStateBuilder$$anon$1.&lt;init&gt;(HiveSessionStateBuilder.scala:69) at org.apa…
score: 1
has comment: http://stackoverflow.com/comment/85811844
linked to: http://stackoverflow.com/q/45947375
downvote count: 1
has comment: http://stackoverflow.com/comment/85846660
has comment: http://stackoverflow.com/comment/85846389
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49406977
has comment: http://stackoverflow.com/comment/85811437

http://stackoverflow.com/a/49337845
has body: Connect to Gdrive using below snippet. You will have to authenticate twice using the link from cell output. !apt-get install -y -qq software-properties-common python-software-properties module-init-tools !add-apt-repository -y ppa:alessandro-strada/ppa 2&gt;&amp;1 &gt; /dev/null !apt-get update -qq 2&gt;&amp;1 &gt; /dev/null !apt-get -y install -qq google-drive-ocamlfuse fuse from google.colab import auth auth.authenticate_user() from oauth2client.client import GoogleCredentials creds = GoogleCredentials.get_application_default() import getpass !google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} &lt; /dev/null 2&gt;&amp;1 | grep URL vcode = getpass.getpass() !echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} !mkdir -p drive !google-drive-ocamlfuse drive Read CSV using pandas df = pd.read_csv('drive/path/file.csv') Save CSV Use index = False if you don't need index as first col in csv. df.to_csv('drive/path/file.csv',index = False)
answers question: http://stackoverflow.com/q/49332876
type: Answer
score: 0

http://stackoverflow.com/comment/85743977
has text: This particular example would easily take days to converge to an answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49371307
type: Comment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49374730
tags question: http://stackoverflow.com/q/49392032
tags question: http://stackoverflow.com/q/49294941
tags question: http://stackoverflow.com/q/49343677
tags question: http://stackoverflow.com/q/49433890
tags question: http://stackoverflow.com/q/49405251
tags question: http://stackoverflow.com/q/49338793
tags question: http://stackoverflow.com/q/49337956
tags question: http://stackoverflow.com/q/49301335
tags question: http://stackoverflow.com/q/49283522
tags question: http://stackoverflow.com/q/49340821
tags question: http://stackoverflow.com/q/49314730
tags question: http://stackoverflow.com/q/49396249
tags question: http://stackoverflow.com/q/49340713
tags question: http://stackoverflow.com/q/49436134
tags question: http://stackoverflow.com/q/49412229
tags question: http://stackoverflow.com/q/49288932
tags question: http://stackoverflow.com/q/49294809
tags question: http://stackoverflow.com/q/49282133
tags question: http://stackoverflow.com/q/49416063
tags question: http://stackoverflow.com/q/49379200
tags question: http://stackoverflow.com/q/49374323
tags question: http://stackoverflow.com/q/49439177
tags question: http://stackoverflow.com/q/49340026
tags question: http://stackoverflow.com/q/49364202
tags question: http://stackoverflow.com/q/49374778
tags question: http://stackoverflow.com/q/49327416
tags question: http://stackoverflow.com/q/49407797
tags question: http://stackoverflow.com/q/49390075
tags question: http://stackoverflow.com/q/49366473
type: Tag
tags question: http://stackoverflow.com/q/49429940
tags question: http://stackoverflow.com/q/49348234
tag name: html
tags question: http://stackoverflow.com/q/49434230
tags question: http://stackoverflow.com/q/49328148
tags question: http://stackoverflow.com/q/49372959
tags question: http://stackoverflow.com/q/49290704
tags question: http://stackoverflow.com/q/49301542
tags question: http://stackoverflow.com/q/49323292
tags question: http://stackoverflow.com/q/49349118
tags question: http://stackoverflow.com/q/49435630
tags question: http://stackoverflow.com/q/49307040
tags question: http://stackoverflow.com/q/49308534
tags question: http://stackoverflow.com/q/49362988
tags question: http://stackoverflow.com/q/49428951
tags question: http://stackoverflow.com/q/49317893
tags question: http://stackoverflow.com/q/49288541
tags question: http://stackoverflow.com/q/49350586
tags question: http://stackoverflow.com/q/49292217
tags question: http://stackoverflow.com/q/49389812
tags question: http://stackoverflow.com/q/49345665

http://stackoverflow.com/q/49362300
score: 1
tagged with: python
tagged with: wordcloud2
has comment: http://stackoverflow.com/comment/85765266
answer count: 4
has comment: http://stackoverflow.com/comment/85758864
favorite count: 0
type: Question
tagged with: python-3.x
has title: Word Cloud Arabic
linked to: http://stackoverflow.com/q/60656343
has answer: http://stackoverflow.com/a/75429611
type: UnansweredQuestion
has body: I had some problem with WordCloud code in python when try to run Arabic huge data this my code: from os import path import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display d = path.dirname(__file__) f = codecs.open(path.join(d, 'C:/example.txt'), 'r', 'utf-8') text = arabic_reshaper.reshape(f.read()) text = get_display(text) wordcloud = WordCloud(font_path='arial',background_color='white', mode='RGB',width=1500,height=800).generate(text) wordcloud.to_file("arabic_example.png") And this is the error I get: Traceback (most recent call last): File "", line 1, in runfile('C:/Users/aam20/Desktop/python/codes/WordClouds/wordcloud_True.py', wdir='C:/Users/aam20/Desktop/python/codes/WordClouds') File "C:\Users\aam20\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\aam20\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/aam20/Desktop/python/codes/WordClouds/wordcloud_True.py", line 28, in text = get_display(text) File "C:\Users\aam20\Anaconda3\lib\site-packages\bidi\algorithm.py", line 648, in get_display resolve_implicit_levels(storage, debug) File "C:\Users\aam20\Anaconda3\lib\site-packages\bidi\algorithm.py", line 466, in resolve_implicit_levels '%s not allowed here' % _ch['type'] AssertionError: RLI not allowed here Can someone help resolve this issue?
downvote count: 0
upvote count: 1
tagged with: word-cloud
has comment: http://stackoverflow.com/comment/85763790
has comment: http://stackoverflow.com/comment/85765155
has answer: http://stackoverflow.com/a/62262198
has answer: http://stackoverflow.com/a/61589815
has answer: http://stackoverflow.com/a/57506785

http://stackoverflow.com/q/49284864
has answer: http://stackoverflow.com/a/49284899
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
has body: Is there a way to join two Pandas dataframes that have common, duplicated indices without doing the Cartesian product? E.g.: df1 = pd.DataFrame(data={'event':['A','C','D']}, index=[1.,3.,3.]) df2 = pd.DataFrame(data={'event':['B','C']}, index=[2.,3.]) Note event C is recorded in both frames, and C and D both have the same index value (a timestamp). df1.join(df2,how='outer',lsuffix='1',rsuffix='2') gives: event1 event2 1.0 A NaN 2.0 NaN B 3.0 C C 3.0 D C The (C,C) and (D,C) rows are the Cartesian product of C and D in df1 and C in df2. I want row 4 to be just (D, NaN), since D only appears in df1 and not in df2, i.e.: event1 event2 1.0 A NaN 2.0 NaN B 3.0 C C 3.0 D NaN
score: 2
type: AnsweredQuestion
tagged with: pandas
has title: Join two Pandas dataframes that have common, duplicated indices without doing the Cartesian product
accepted answer: http://stackoverflow.com/a/49284899
favorite count: 0
type: Question

pyqt5
tags question: http://stackoverflow.com/q/49358862
tags question: http://stackoverflow.com/q/49335486
tags question: http://stackoverflow.com/q/49338758
type: Tag
tags question: http://stackoverflow.com/q/49328148
tags question: http://stackoverflow.com/q/49386039
tags question: http://stackoverflow.com/q/49404977
tags question: http://stackoverflow.com/q/49340886
tags question: http://stackoverflow.com/q/49289835
tags question: http://stackoverflow.com/q/49334963
tags question: http://stackoverflow.com/q/49349520
tags question: http://stackoverflow.com/q/49420732
tags question: http://stackoverflow.com/q/49363360
tags question: http://stackoverflow.com/q/49321272
tags question: http://stackoverflow.com/q/49431089
tags question: http://stackoverflow.com/q/49323961
tags question: http://stackoverflow.com/q/49435804
tags question: http://stackoverflow.com/q/49423350
tags question: http://stackoverflow.com/q/49370995
tags question: http://stackoverflow.com/q/49421560
tags question: http://stackoverflow.com/q/49329640
tags question: http://stackoverflow.com/q/49403638
tags question: http://stackoverflow.com/q/49309034
tags question: http://stackoverflow.com/q/49431548
tag name: pyqt5
tags question: http://stackoverflow.com/q/49418905
tags question: http://stackoverflow.com/q/49417693
tags question: http://stackoverflow.com/q/49348545
tags question: http://stackoverflow.com/q/49343560
tags question: http://stackoverflow.com/q/49401730
tags question: http://stackoverflow.com/q/49413607
tags question: http://stackoverflow.com/q/49342385
tags question: http://stackoverflow.com/q/49306741
tags question: http://stackoverflow.com/q/49344445
tags question: http://stackoverflow.com/q/49319494
tags question: http://stackoverflow.com/q/49299107
tags question: http://stackoverflow.com/q/49327154
tags question: http://stackoverflow.com/q/49307970
tags question: http://stackoverflow.com/q/49306865
tags question: http://stackoverflow.com/q/49416790
tags question: http://stackoverflow.com/q/49383369
tags question: http://stackoverflow.com/q/49304411
tags question: http://stackoverflow.com/q/49379069
tags question: http://stackoverflow.com/q/49284591

http://stackoverflow.com/q/49385664
has body: A device is connected to my PC and I need to write a command via COM Port and get the output. Here is my code from time import sleep import serial ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM20' ser.open() ser.write("system\r") result = ser.read(100) print result ser.close() This is working perfectly. However, different commands return different strings. so I need to read it without mentioning no of bytes in ser.read(100). How can I achieve that? Appreciate any help. Thank you
has answer: http://stackoverflow.com/a/49386628
accepted answer: http://stackoverflow.com/a/49386628
answer count: 1
type: Question
has title: How to read serial port output in Python using pySerial?
tagged with: pyserial
tagged with: serial-port
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85811462
type: Comment
has text: What does `which -a python` say?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49405236

http://stackoverflow.com/comment/85723399
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49356711
type: Comment
has text: I was already upgrade scrapy. I use python 3.6.2. Is there any problem with this version?

http://stackoverflow.com/q/49393805
has comment: http://stackoverflow.com/comment/85790587
favorite count: 0
has answer: http://stackoverflow.com/a/49393930
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/49393866
has title: Get random items from range of list
downvote count: 2
has body: Let's say I have a unsorted set of items: input = set([45, 235, 3, 77, 55, 80, 154]) I need to get random values from this input but in a specific range. E.g. when I have ran = [50, 100] I want it to return either 77 or 55 or 80. What's the fastest way to get this for large sets in python?
has comment: http://stackoverflow.com/comment/85790426
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49394130
has answer: http://stackoverflow.com/a/49394114
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85789365
score: 0
tagged with: random
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/49394130
has answer: http://stackoverflow.com/a/49393866

http://stackoverflow.com/a/49398990
has comment: http://stackoverflow.com/comment/85799302
downvote count: 1
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49398493
has body: It seems that your are confused on what do you want. Based on your comment, the answer is in python datetime documentation: There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc: timestamp = dt.replace(tzinfo=timezone.utc).timestamp() or by calculating the timestamp directly: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

http://stackoverflow.com/a/49338857
score: 0
has body: The j in the first loop will not increase until 'i' traverse through every element, so j will print 1.20 both times. For traversing through both lists at the same time you can use one for loop. for j in range(len(userlst)): print("Movies: " + str(movielst[j])) print("Users: " + str(userlst[j])) The output will be : Movies: A WALK,DRAGONBALL Users: [1, 20] Movies: JAMES BOND,MISSION Users: [6, 7]
answers question: http://stackoverflow.com/q/49338726
type: Answer

http://stackoverflow.com/q/49362774
has title: How to clean the terminal screen in Python 3?
tagged with: terminal
type: UnansweredQuestion
has body: How can I clear/clean entire terminal screen/window of Python 3? My aim is to: Print 5 lines in terminal/output screen window in Python3 Clean the entire output screen Print 3 lines in the screen
tagged with: python
linked to: http://stackoverflow.com/q/2084508
score: 0
has answer: http://stackoverflow.com/a/49362839
duplicate of: http://stackoverflow.com/q/2084508
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85725704
tagged with: python-3.x

http://stackoverflow.com/q/49389440
tagged with: django
score: 4
favorite count: 0
tagged with: docker
has title: cookiecutter-django local development with docker
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49396669
tagged with: python
tagged with: cookiecutter-django
tagged with: cookiecutter
accepted answer: http://stackoverflow.com/a/49396669
type: Question
upvote count: 4
downvote count: 0
has body: I've never use docker for development on local machine so I have few questions that I didn't find in documentation. After setup I can't figure out how do I can install my packages via pip. I tried: docker-compose -f local.yml run --rm django pip install some-package. It installed package somewhere, but not in project. Do I need to build every time when I add new package? How to run django managment commands in another thread docker-compose -f local.yml run --rm django python manage.py mycommand stop runserver command that is not convenient Where do I see celery tasks log ? How to run: celery -A apps.taskapp worker -l info celery -A apps.taskapp beat -l INFO to see debug messages of my tasks
answer count: 1

http://stackoverflow.com/comment/85636357
type: QuestionComment
has text: compile into a .pyc file
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49317551

http://stackoverflow.com/comment/85740073
score: 0
comment on: http://stackoverflow.com/q/49369241
has text: Briefly scanning your code, it looks odd that you are calling the super of RenderView with every request that your app receives. Consider initializing the super in __init__ and then using ```self.get_context_date(**kwargs)```.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49421199
answers question: http://stackoverflow.com/q/49421144
has comment: http://stackoverflow.com/comment/85843412
has comment: http://stackoverflow.com/comment/85843619
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/85843509
upvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85844493
has comment: http://stackoverflow.com/comment/85843474
accepted answer of: http://stackoverflow.com/q/49421144
downvote count: 1
has comment: http://stackoverflow.com/comment/85843915
has body: try this: cursor.executemany('INSERT into test VALUES(%s, %s, %s,%s)',data) Or cursor.execute("INSERT INTO test VALUES %s;" %(str(tuple(data)).replace('((','(').replace('))',')')))

http://stackoverflow.com/comment/85812245
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49405477
has text: this is what I needed!Thanks a lot!
score: 0

http://stackoverflow.com/q/49353234
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has body: I have a 2d list (array) in python that I am trying to print to the console with different characters. Array: maze_a = [[1,1,1,1,1,1,1,0,1,1,1,1,1,1,1], [1,0,0,0,0,0,1,0,1,0,0,0,0,0,1], [1,0,1,1,1,0,1,0,1,1,1,1,1,0,1], [1,0,1,0,1,0,1,0,0,0,0,0,1,0,1], [1,0,1,0,1,0,1,1,1,1,1,0,1,0,1], [1,0,1,0,0,0,0,0,0,0,0,0,1,0,1], [1,1,1,0,1,1,1,1,1,1,1,1,1,0,1], [1,0,0,0,0,0,1,0,0,0,0,0,0,0,1], [1,0,1,1,1,0,1,0,1,1,1,1,1,1,1], [1,0,1,0,1,0,1,0,0,0,0,0,0,0,1], [1,0,1,0,1,0,1,1,1,1,1,1,1,0,1], [1,0,0,0,1,0,0,0,1,0,0,0,1,0,1], [1,1,1,1,1,0,1,0,1,0,1,0,1,0,1], [1,0,0,0,1,0,1,0,1,0,1,0,1,0,1], [1,0,1,1,1,0,1,1,1,0,1,0,1,0,1], [1,0,0,0,0,0,0,0,0,0,1,0,0,0,1], [1,1,1,1,1,1,1,1,1,0,1,1,1,1,1]] Code: for row in maze_a: print(*row) Current Output: 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 1 0 1 1 1 1 1 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 1 0 1 1 1 0 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 I am trying to add to my code to change the characters. I would like the 0's as whitespace and the 1's as *s. I tried .replace(0, ' ') but I couldn't seem to get it work. I know this seems easy but I cannot find an answer for the life of me. Maybe I cannot use the print(*row) or I need to convert to string first (which I tried and failed)?
has title: Replace and print characters from 2d list python
favorite count: 0
score: 1
has answer: http://stackoverflow.com/a/49353307
type: Question

http://stackoverflow.com/comment/85583161
score: 0
comment on: http://stackoverflow.com/a/49290002
type: Comment
has text: @mike, I suggest you ask as a separate question.. Not exactly the same method as `groupby`.
type: AnswerComment

http://stackoverflow.com/a/49326664
accepted answer of: http://stackoverflow.com/q/49313291
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85659621
score: -1
answers question: http://stackoverflow.com/q/49313291
has comment: http://stackoverflow.com/comment/85709694
has body: a VNC server accesses the frame buffer, in droidVNCserver that is open source this is done in native C ( JNI - Java Native Interface ) and i think it is only possible in low level C. the source code is in https://github.com/oNaiPs/droidVncServer/tree/master/ , see https://github.com/oNaiPs/droidVncServer/tree/master/jni/vnc and see https://github.com/oNaiPs/droidVncServer/tree/master/jni/vnc/screenMethods for the jni code How Droid VNC works? so with this you can access the frame buffer on the android device however then you have to grab the image over USB using python what is not trivial. you can i.e. mount the android as mass storage or PTP ( picture transfer protocol ) or MTP ( media transfer protocol ) device or use adb however this is not easy if you want an easy solution install droidVNCserver on your android and write a python program using libraries like https://pypi.python.org/pypi/vncdotool to access it...
has comment: http://stackoverflow.com/comment/85659339
has comment: http://stackoverflow.com/comment/85659298
type: Answer
has comment: http://stackoverflow.com/comment/85725178
downvote count: 1
has comment: http://stackoverflow.com/comment/85670456
upvote count: 0

http://stackoverflow.com/q/49341323
linked to: http://stackoverflow.com/q/24723547
tagged with: python
has body: I've cloned some private python3 (can not share it). I build it like this: cd project python3 setup.py install I can use the project using: /Library/Frameworks/Python.framework/Versions/3.6/bin/tool --help This shows the right output. But I want to use this like this: python3 tool --help Here I get: /usr/local/bin/python3.6: can't find '__main__' module in 'tool' I see there is a __main__ in the project. What is wrong?
has title: How to build python3 package
type: Question
tagged with: python-3.x
score: 0
duplicate of: http://stackoverflow.com/q/24723547
has comment: http://stackoverflow.com/comment/85684377
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85682996
has comment: http://stackoverflow.com/comment/85682817

http://stackoverflow.com/a/49876847
answers question: http://stackoverflow.com/q/49359159
type: Answer
score: 0
has body: You can use the library "dask" e.g: # Dataframes implement the Pandas API import dask.dataframe as dd`&lt;br&gt; df = dd.read_csv('s3://.../2018-*-*.csv')

http://stackoverflow.com/q/49395278
linked to: http://stackoverflow.com/q/47717277
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49396001
linked to: http://stackoverflow.com/q/11941817
has title: Function to delete data frames from namespace if they start with a specific prefix
type: Question
has comment: http://stackoverflow.com/comment/85792677
has comment: http://stackoverflow.com/comment/85792585
has comment: http://stackoverflow.com/comment/85792344
tagged with: python
has comment: http://stackoverflow.com/comment/85792455
has comment: http://stackoverflow.com/comment/85792710
has body: Purpose: write a function to delete all data frames that start with a specific prefix from the name space. def del_dfs(prefix): df_list = [] # I know this list building stage may not be necessary but I need a list of included dfs for other purposes df_list.append([df for name, df in globals().items() if name.startswith(prefix) and isinstance(df, (pd.Series, pd.DataFrame))]) for df in df_list: del df Issue: This simply does not delete the dfs from the namespace. I guess it is related to the deletion happening inside the function but I can not figure out a solution. update My overall purpose is to find all dfs in the namespace that start with a prefix, concatenate them (I already have a function for this), and then delete the individual dfs from the namespace to free up RAM as I now have them all in a concatenated df.
has comment: http://stackoverflow.com/comment/85792552
score: 0
tagged with: pandas

http://stackoverflow.com/comment/85796354
score: 0
comment on: http://stackoverflow.com/q/49396973
has text: @cricket_007: I understand, but what I care now is what I see and not what is stored.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85686827
type: QuestionComment
type: Comment
has text: [This](https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html) might help
score: 0
comment on: http://stackoverflow.com/q/49343231

http://stackoverflow.com/q/49324347
has comment: http://stackoverflow.com/comment/85650511
favorite count: 0
has comment: http://stackoverflow.com/comment/85650742
type: Question
accepted answer: http://stackoverflow.com/a/49324752
score: 3
has answer: http://stackoverflow.com/a/49324752
has comment: http://stackoverflow.com/comment/85650786
has answer: http://stackoverflow.com/a/49324869
has comment: http://stackoverflow.com/comment/85650208
tagged with: python
has body: I am doing some entity matching based on string edit distance and my results are a dictionary with keys (query string) and values [list of similar strings] based on some scoring criteria. for example: results = { 'ben' : ['benj', 'benjamin', 'benyamin'], 'benj': ['ben', 'beny', 'benjamin'], 'benjamin': ['benyamin'], 'benyamin': ['benjamin'], 'carl': ['karl'], 'karl': ['carl'], } Each value also has a corresponding dictionary item, for which it is the key (e.g. 'carl' and 'karl'). I need to combine the elements that have shared values. Choosing one value as the new key (lets say the longest string). In the above example I would hope to get: results = { 'benjamin': ['ben', 'benj', 'benyamin', 'beny', 'benjamin', 'benyamin'], 'carl': ['carl','karl'] } I have tried iterating through the dictionary using the keys, but I can't wrap my head around how to iterate and compare through each dictionary item and its list of values (or single value).
tagged with: dictionary
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49324869
has title: Combine python dictionaries that share values and keys
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85650292
has comment: http://stackoverflow.com/comment/85650575

http://stackoverflow.com/comment/85725935
comment on: http://stackoverflow.com/q/49362328
score: 0
type: Comment
type: QuestionComment
has text: Please include the Python code you have tried. Where does it not work? What exact error do you get?

http://stackoverflow.com/q/49438414
has body: I know this question is asked more than one time, but I couldn't understand codes or the logic behind. In my data set, first I created a layer, sigmoid layer, then I connected this layer to the output layer and I've used softmax function in the output layer. fl = tf.layers.dense(x, 10,activation=tf.sigmoid) output = tf.layers.dense(fl, 2,activation=tf.nn.softmax) I've created loss and accuracy, initialized variables, set optimizer and train variables, then I start running on my data: loss = tf.losses.softmax_cross_entropy(onehot_labels=y,logits=output) accuracy = tf.metrics.accuracy(tf.argmax(y_train,1),tf.argmax(output,1)) # inits init_local = tf.local_variables_initializer() init_global = tf.global_variables_initializer() sess.run(init_global) sess.run(init_local) optimizer = tf.train.GradientDescentOptimizer(rate) train = optimizer.minimize(loss) for i in range(1000): _, lv = sess.run((train, loss)) if i%5 == 0: print("L: " + str(lv)) print("Accuracy: "+str(sess.run(accuracy))) I can see that my loss value decreases every time I run on the training set. And my accuracy is ~0.93. The problem is, from now on, I don't know how to test this model with real data. Also, how can I draw a histogram of my real data? I have correct labels for my real data as well.
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49523803
type: UnansweredQuestion
tagged with: python
has title: How to used trained model to test data and plot graph?
score: 0

http://stackoverflow.com/comment/86086764
score: 0
type: Comment
has text: Unfortunately, as confirmed in the [link](https://issuetracker.google.com/issues/70605915#comment2), the design is to clutter up every background processes. However, you can manage manually what exactly you want to log by using the [Logging](https://cloud.google.com/logging/docs/how-to) API. Likewise, you can [programmatically](https://cloud.google.com/appengine/docs/standard/python/logs/#writing_application_logs) write application logs from your application.
comment on: http://stackoverflow.com/a/49438689
type: AnswerComment

http://stackoverflow.com/a/49282815
score: 0
accepted answer of: http://stackoverflow.com/q/49281917
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85568680
answers question: http://stackoverflow.com/q/49281917
has body: I guess I've understood what you wish to achieve. The reason why you're not getting the values in the order of the tokens is because of the way you've defined the loop structure. Lets say the dictionary_list contains the values [a, b, c, d, e]. The tokens array contains the value [e, i, y, a, b]. When the outer loop executes, the value of i is a. The second loop checks through the tokens (which are in the order of sentence) and encounters a at index = 3, and hence, prints a. But you wish to print e first since it occurs first in the token. Solution: Swap the loop definitions for a in tokens: for i in definitions: if a.encode('utf-8') == i.encode('utf-8'): print(i) OR for a in tokens: if a.encode('utf-8') in dictionary_list: print(a) This way, the programs holds e from tokens first, if e exists in dictionary (which does exist), it prints e, and so on. Hope this solves your issue.
type: Answer

firebase-realtime-database
tags question: http://stackoverflow.com/q/49348460
tag name: firebase-realtime-database
tags question: http://stackoverflow.com/q/49343473
tags question: http://stackoverflow.com/q/49280929
type: Tag

http://stackoverflow.com/q/49360480
has answer: http://stackoverflow.com/a/59177557
has answer: http://stackoverflow.com/a/51729798
type: AnsweredQuestion
has title: Python type hinting for async function as function argument
tagged with: python-asyncio
accepted answer: http://stackoverflow.com/a/51729798
upvote count: 58
tagged with: python-typing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/92817917
answer count: 2
tagged with: pycharm
score: 58
downvote count: 0
possible better answer: http://stackoverflow.com/a/59177557
tagged with: python
has body: I am trying to make sure a function parameter is an async function. So I am playing around with the following code: async def test(*args, **kwargs): pass def consumer(function_: Optional[Coroutine[Any, Any, Any]]=None): func = function_ consumer(test) But it doesn't work. I am presented with the following error during type checking in PyCharm: Expected type 'Optional[Coroutine]', got '(args: Tuple[Any, ...], kwargs: Dict[str, Any]) -&gt; Coroutine[Any, Any, None]' instead Can anyone give me some hints how to solve this?

http://stackoverflow.com/a/49365130
has body: Tkinter has no attribute conifig but rather config do well to check the tkinter documentation to check other attribute of tkinter. from Tkinter import * def donothing(): print "Ok ok i wont.." root = Tk() menu = Menu(root) root.config(menu=menu) submenu = Menu(menu) menu.add_cascade(label="File", menu=submenu) submenu.add_command(label="New project...", command=donothing) submenu.add_command(label="save", command=donothing) submenu.add_separator() submenu.add_command(label="Exit", command=donothing) editmenu = Menu(menu) menu.add_cascade(label="Edit", menu=editmenu) editmenu.add_command(label="Redo", command=donothing) root.mainloop()
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49364713
accepted answer of: http://stackoverflow.com/q/49364713

http://stackoverflow.com/comment/85688355
comment on: http://stackoverflow.com/a/49343988
type: Comment
has text: Great @sharjeel, that means we are getting closer to the solution. Can you update the question to include how exactly you add parent in?
score: 0
type: AnswerComment

http://stackoverflow.com/q/49332694
type: Question
has answer: http://stackoverflow.com/a/49332761
tagged with: attributeerror
tagged with: python
has title: AttributeError: 'GramMatrix' object has no attribute 'gradInput'
tagged with: python-3.x
score: 0
has body: Here's a simplified version of my code (The full version is a bunch of class functions for a neural network using PyTorch): # Define an nn Module to compute content loss in-place class ContentLoss(object): def __init__(self, strength): super(ContentLoss, self).__init__() self.strength = strength self.target = 0 self.loss = 0 self.mode = None def forward(self, input): print("ContentLoss - Forward") if self.mode == 'loss': print("ContentLoss - Forward - Loss") self.loss = (input * self.target) * self.strength #Forward elif self.mode == 'capture': print("ContentLoss - Forward - Capture") self.target = input self.output = input return self.output def backward(self, input, gradOutput): print("ContentLoss - Backward") if self.mode == 'loss': print("ContentLoss - Backward - Loss") self.gradInput = input * self.target # Backward self.gradInput = self.gradInput * self.strength self.gradInput = self.gradInput + gradOutput else: print("ContentLoss - Backward - Capture") self.target = gradOutput return self.gradInput class GramMatrix(object): def __init__(self): super(GramMatrix, self).__init__() def forward(self, input): self.output = input return self.output def backward(self, input, gradOutput): self.gradInput = self.gradInput + gradOutput + input return self.gradInput class StyleLoss(object): def __init__(self, strength): super(StyleLoss, self).__init__() self.strength = strength self.target = 0 self.mode = None self.loss = 0 self.gram = GramMatrix() self.blend_weight = None self.G = None def forward(self, input): print("StyleLoss - Forward") self.G = self.gram.forward(input) if self.mode == 'capture': print("StyleLoss - Forward - Capture") if self.blend_weight == None: self.target = self.G else: self.target = self.target + (self.blend_weight * self.G) elif self.mode == 'loss': print("StyleLoss - Forward - Loss") self.loss = self.strength * (self.G * self.target) #Forward self.output = input return self.output def backward(self, input, gradOutput): print("StyleLoss - Backwa…
tagged with: function
type: UnansweredQuestion
answer count: 1
tagged with: methods

http://stackoverflow.com/comment/110631290
has text: @hwjp yea, of course. `Coroutine` is just the return type of an async function. So if your function has no return type declared, it could secretly behave like an async one.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/59177557
type: Comment

mouse-cursor
tag name: mouse-cursor
type: Tag
tags question: http://stackoverflow.com/q/49338888

http://stackoverflow.com/q/49348539
has comment: http://stackoverflow.com/comment/85696818
tagged with: python-3.x
score: 0
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49348567
favorite count: 0
type: Question
has title: print star pattern with interval range output in python
has body: So far I have the solution to print star patterns lower = int(input("what is the minimum nmber of stars: ")) upper = int(input("what is the maximum number of stars: ")) interval=int(input("enter the interval:")) for i in range (lower,upper+1,interval): print((lower) * ' ' + i * '*') which only prints out the the stars for example: *** what I'm looking for is ***(3 stars) ********(7 stars) ***********(11 stars) How do I print the literal part(x stars)?
tagged with: python

http://stackoverflow.com/a/49361730
has body: This is a generalized solution via numpy.where. It will work for matching first instance of any specified value. df = df.iloc[:np.where(df['streak']==0)[0][0]] # streak # 0 1.0 # 1 2.0
score: 0
answers question: http://stackoverflow.com/q/49352824
type: Answer

http://stackoverflow.com/comment/86210713
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49525170
score: 0
has text: I have yet to test out the part of the program that actually does the lookup of values in the Redis database, but from the looks of it, it will be plenty fast enough. I'll have a definite answer on whether Redis solved the entire problem by the end of the day.

http://stackoverflow.com/comment/85653484
type: AnswerComment
has text: Thank you, i will try it later
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49307125

http://stackoverflow.com/comment/85752994
has text: Thanks for the headsup. But I'm still stuck with installing the beautifulsoup package so I would love to look at the script and see if I can change it or understand it but I'm not even there yet. @abarnert I have no idea how I ended up with that.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49375881

http://stackoverflow.com/a/49382652
has body: Generator expression yields or generates one element at a time. Since c has arrays a and b as its elements, it will apply sum to individual arrays during np.sum(x for x in c). np.sum() sums up all the elements of c after flattening them.
score: 0
answers question: http://stackoverflow.com/q/49382504
type: Answer

http://stackoverflow.com/q/49413062
has answer: http://stackoverflow.com/a/49413361
score: 1
has body: My Document model has a text_location column, a file path that I need to read from after querying. I am using paginate when querying. That is created through this code: class Document(db.Model): id = db.Column(db.Integer, primary_key=True) text_location = db.Column(db.String) page_views = Document.query.paginate(page, 1, False) I can display {{ page_views }} correctly in the template. However, if I try to open text_location, I get "Pagination" object has no attribute "text_location". with open(page_views.text_location) as f: document_text = f.read() How can I read the text_location for the Documents I queried?
downvote count: 0
answer count: 1
has title: Access a column from a Flask-SQLAlchemy paginate result
upvote count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
tagged with: python
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/49413361
type: AnsweredQuestion

http://stackoverflow.com/a/49317155
type: Answer
downvote count: 0
has body: First of all, your search is not case sensitive because you used the option nocase=1. Secondly, if you want to do a up or down search, there are the backwards and forwards options (I found the documentation here). When you do a backward search, you also need to change the way you move the insert cursor too and the stopindex. Here is an example in which the text in the entry is searched in the text starting from the current insert position and moving upward / downward depending on the selected radiobutton: from tkinter import * from tkinter import messagebox as MessageBox def search(): pattern = e.get() if search_dir.get() == 'forwards': res = txt.search(pattern, 'insert', forwards=True, stopindex='end') else: res = txt.search(pattern, 'insert', backwards=True, stopindex='1.0') txt.tag_remove('sel', '1.0', 'end') try: txt.tag_add('sel', res, '%s+%ic' % (res, len(pattern))) if search_dir.get() == 'forwards': txt.mark_set('insert', '%s+%ic' % (res, len(pattern))) else: txt.mark_set('insert', '%s-1c' % (res)) except: MessageBox.showinfo("Search complete","No further matches") root = Tk() txt = Text(root) txt.pack(fill='both',expand=True) e = Entry(root) e.pack(fill='x') search_dir = StringVar(root, 'forwards') Radiobutton(root, text='▲', value='backwards', variable=search_dir).pack() Radiobutton(root, text='▼', value='forwards', variable=search_dir).pack() Button(root, text='Search', command=search).pack() root.mainloop()
accepted answer of: http://stackoverflow.com/q/49314702
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49314702

http://stackoverflow.com/a/49318098
score: 0
has comment: http://stackoverflow.com/comment/85640455
has comment: http://stackoverflow.com/comment/85639944
has body: You defined your request handler mylemmatize(token) to take a variable called token but you route is not aware of that and so does not pass your data to the request handler. Change your route from : @app.route("/glcoding", methods=['POST']) to this instead: @app.route("/glcoding/&lt;token&gt;", methods=['POST']) See the doc on variable rule for more info. Also if you do not need to pass the token as a variable, then you need to remove it from your mylemmatize function definition.
answers question: http://stackoverflow.com/q/49316810
type: Answer

http://stackoverflow.com/q/49320188
tagged with: tensorflow
type: Question
upvote count: 4
has body: I'm trying to build a tensorflow neural network using a sigmoid activation hidden layer and a softmax output layer with 3 classes. The outputs are mostly very bad and I believe it is because I am making a mistake in my model construction because I've built a similar model with Matlab and the results have been good. The data is normalized. These results look like this: [9.2164397e-01 1.6932052e-03 7.6662831e-02] [3.4100169e-01 2.2419590e-01 4.3480241e-01] [2.3466848e-06 1.3276369e-04 9.9986482e-01] [6.5199631e-01 3.4800139e-01 2.3596617e-06] [9.9879754e-01 9.0103465e-05 1.1123115e-03] [6.5749985e-01 2.8860433e-02 3.1363973e-01] My nn looks like this: def multilayer_perceptron(x, weights, biases, keep_prob): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.sigmoid(layer_1) layer_1 = tf.nn.dropout(layer_1, keep_prob) out_layer = tf.nn.softmax(tf.add(tf.matmul(layer_1,weights['out']),biases['out'])) return out_layer With the following cost function: cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predictions, labels=y)) I'm growing convinced that my implementation is incorrect and I am doing something very silly. Hours on google and looking at other examples hasn't helped. UPDATE: When I changed the cost function (shown below), I get decent results. This feels wrong though. cost = tf.losses.mean_squared_error(predictions=predictions, labels=y)
type: UnansweredQuestion
has title: Neural Network using Softmax with strange outputs
answer count: 1
tagged with: neural-network
tagged with: softmax
tagged with: machine-learning
tagged with: python
downvote count: 1
favorite count: 0
score: 3
has answer: http://stackoverflow.com/a/49320401

http://stackoverflow.com/q/49290207
answer count: 1
has answer: http://stackoverflow.com/a/49310222
tagged with: web-scraping
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85590018
tagged with: python
has title: Mechanicalsoup Not Logging Me In
tagged with: mechanicalsoup
score: 0
has comment: http://stackoverflow.com/comment/85604786
has body: I am trying to login to a site with mechanicalsoup, but when I submit the form, it keeps me on the same page. I have done a lot of researching for this and could not find an answer. br.open(domain + action) form = br.select_form() user_info = getUserInfo() br["ff_login_id"] = user_info["eid"] br["ff_password"] = user_info["password"] br["empl-login_submit"] = "SUBMITTED" br.get_current_form().print_summary() res = br.submit(form, domain) print(res) #This is getting a response 200
has comment: http://stackoverflow.com/comment/85659278

http://stackoverflow.com/q/49315139
type: UnansweredQuestion
has title: How to achieve DOM manipulation in languages other than javascript ex:python
has answer: http://stackoverflow.com/a/49315260
tagged with: javascript
tagged with: python
answer count: 2
has body: InputTags = document.getElementsByTagName("input") for (inputTag in InputTags) { if (inputTag.name == 'username') inputTag.value = "abc" else if (inputTag.name == 'password') { inputTag.value = "abc@123" } } In the above segment, DOM elements are manipulated by Javascript method "getElementsByTagName".Similarly how do I acheive this in languages like python?
score: 0
has answer: http://stackoverflow.com/a/49315349
has comment: http://stackoverflow.com/comment/85633654
upvote count: 1
tagged with: dom
has comment: http://stackoverflow.com/comment/85631678
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49405842
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85812648
answer count: 1
has comment: http://stackoverflow.com/comment/85817178
tagged with: while-loop
type: Question
has comment: http://stackoverflow.com/comment/85816181
score: 0
has comment: http://stackoverflow.com/comment/85813996
has title: Python while sampling
has answer: http://stackoverflow.com/a/49408303
tagged with: sample
has body: I'm searching to make a loop to go throw samples till I reach the result. Example: i=(list(np.random.randint(2, size=5)),list(np.random.randint(2, size=2)),list(np.random.randint(2, size=7)),list(np.random.randint(2, size=7)),list(np.random.randint(2, size=9)),list(np.random.randint(2, size=8)),list(np.random.randint(2, size=7))) tot=0 for j in range(0,len(anytable)): if resp(i,(anytable.iloc[j,0:7].tolist())): #this function "resp" gives me True and False and add 1 to variable "tot" tot=tot+1 Now I want to stop till I have to tot&gt;=100 . So I have to generate many "i" samples lists till I get to tot&gt;=100. How can I do this? Thank you very much

http://stackoverflow.com/q/49410425
tagged with: pandas
score: 1
upvote count: 3
has answer: http://stackoverflow.com/a/49410747
tagged with: http://stackoverflow.com/tag/json
has body: I'm trying to get an API call and save it as a dataframe. problem is that I need the data from the 'result' column. Didn't succeed to do that. I'm basically just trying to save the API call as a csv file in order to work with it. P.S when I do this with a "JSON to CSV converter" from the web it does it as I wish. (example: https://konklone.io/json/) import requests import pandas as pd import json res = requests.get("http://api.etherscan.io/api?module=account&amp;action=txlist&amp; address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a&amp;startblock=0&amp; endblock=99999999&amp;sort=asc&amp;apikey=YourApiKeyToken") j = res.json() j df = pd.DataFrame(j) df.head() output example picture
has title: JSON from API call to pandas dataframe
has comment: http://stackoverflow.com/comment/86203217
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49410979
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49410979
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49410747
answer count: 2

http://stackoverflow.com/comment/85724587
score: 0
type: Comment
has text: Thanks for the help@jezrael. I'm quite new to Python
type: AnswerComment
comment on: http://stackoverflow.com/a/49361824

http://stackoverflow.com/a/49396609
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49396311
type: Answer
has body: Trying to do what you want with map will require adding some kind of "memory" to the function—it has to know what it's done so far, so it knows what to do next. You can do this, either by using a closure, or by using a class with a __call__ method. But there's an easier way. What you're looking for is almost exactly the accumulate function. The only difference is that you want to supply a starting value. (And, of course, that accumulate isn't actually in the stdlib in 2.7; you need to get it off a backport on PyPI.) You could handle that in three obvious ways: accumulate, then add your starting value to each element. chain a starting value before the input, then accumulate, then next (or islice) to skip over the extra value in the output. Take the "roughly equivalent" sample code in the accumulate docs and modify it to take a start value. Let's do the last one—it's probably the heaviest-weight option, but the one you can learn the most from, plus it'll work even in 2.7 without any backports: def accumulate(iterable, func=operator.add, start=0): 'Return running totals' it = iter(iterable) total = start try: total += next(it) except StopIteration: return total yield total for element in it: total = func(total, element) yield total Compare to the original code in the docs—all I did was add a new parameter, set total = start, and change the special handling for the first element or for empty iterables. You can obviously simplify things (if we have a start value, we don't even need special handling for empty input), or make things fancier (default to no start value instead of 0, so accumulate works for types that aren't interoperable with int just like the one in itertools does), etc., but this is a simple starting point. And now: &gt;&gt;&gt; new_list = accumulate([0,0,0,1,0,2], start=18) &gt;&gt;&gt; new_list [18, 18, 18, 19, 18, 20]

nearest-neighbor
tags question: http://stackoverflow.com/q/49420191
type: Tag
tag name: nearest-neighbor

http://stackoverflow.com/a/49314782
answers question: http://stackoverflow.com/q/49308534
score: 0
type: AcceptedAnswer
has body: I think you should use &amp;lt; or &amp;gt; for display symbols &lt; or >
accepted answer of: http://stackoverflow.com/q/49308534
type: Answer

http://stackoverflow.com/q/49287116
tagged with: rest
has comment: http://stackoverflow.com/comment/85577338
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85577354
score: 0
has answer: http://stackoverflow.com/a/49287851
tagged with: api
answer count: 1
has body: I am new to Python and am trying to use it to connect to Americommerce API. They have an example on git. It doesn't seem to work though. I add the url to STORE_DOMAIN, key to ACCESS_TOKEN, and app id to STORE_ID. The only one that seems to matter is the web url. If I mispell it I get coonection errors, however the key and id I can enter whatever I want there and get the same results. here is the script #!/usr/bin/env python3 # The 'requests' module is available via pip: "pip install requests" # You can find more documentation about requests at http://docs.python-requests.org/en/latest/ import requests import json import locale import sys STORE_DOMAIN = "http://www.example.com" ACCESS_TOKEN = "key" STORE_ID = "app_id" # This should reflect your store's ID locale.setlocale(locale.LC_ALL, '') # Searches for and returns the customer that matches the info passed in, # if no customer is found a new one is created and returned def get_customer(firstName, lastName, email): # setup headers headers = { 'X-AC-Auth-Token': ACCESS_TOKEN, 'Content-Type': 'application/json' } # build API call to check if customer already exists (using email) uri = '{}/api/v1/customers?email={}'.format(STORE_DOMAIN, email) # include verify=False if using dev certificate # r = requests.get(uri, headers = headers, verify=False) r = requests.get(uri, headers = headers) # see if a customer was found customer = r.json() if (customer['total_count'] &gt; 0): return customer['customers'][0] # no customer found, so lets create a new one data = { 'last_name': doe, 'first_name': john, 'email': johndoe@email.com, 'store_id': 4 } # build API call to post a new customer uri = '{}/api/v1/customers'.format(STORE_DOMAIN) # include verify=False if using dev certificate # r = requests.post(uri, headers=headers, data = json.dumps(data), verify=False) r = requests.post(uri, headers=headers, data = json.dumps(data)) # return newly created customer return r.json() if __name__ == '__main__': customer = get_customer('John'…
has title: Connecting to API issues
type: Question

http://stackoverflow.com/comment/85604571
comment on: http://stackoverflow.com/a/49300949
score: 0
type: AnswerComment
has text: Thank you very much. Idk exactly what helped of these 3 tips, but Im glad that this problem is resolved.
type: Comment

http://stackoverflow.com/q/49313193
accepted answer: http://stackoverflow.com/a/49313328
upvote count: 1
has body: I have 3 dataframes like below, ` df1=[ 1q2 123 1q3 212 1d4 234...] df2=[ 1q1 223 1q2 126 1q3 42 1d4 314...] df3=[ 1q2 923 1q4 121 1d3 423...] ` How can I get result like dfans=[1q1 0 223 0 1q2 123 126 923 1q3 212 42 423 1d4 234 314 121....] column1 contains the id column 2 get the correct value for id's after matching ids,from df1; similarly values matched from df2 in column 3 and value matching from df3. if no values for that id is available place a 0 in that location. is there any way?
has title: matching the ids from different data frame and arranging the column values in to a single data frame in python
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49313328
has comment: http://stackoverflow.com/comment/85627996
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas

http://stackoverflow.com/a/49419348
accepted answer of: http://stackoverflow.com/q/49419009
answers question: http://stackoverflow.com/q/49419009
upvote count: 2
type: Answer
score: 2
has body: You'll need to save a reference to your photo because it is being garbage collected after my_mainloop runs. You can add it to your canvas object for instance: canvas.dial_1_photo_new = ImageTk.PhotoImage(img2) dial_2 = canvas.create_image((dial_1_center), image=canvas.dial_1_photo_new, anchor=tk.E)
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/53147354
answers question: http://stackoverflow.com/q/49285746
upvote count: 1
has body: The problem asks you to evaluate weight1, weight2, and bias when your inputs are [(0,0), (0,1), (1,0), (1,1)] in order to produce [False, False, False, True]. 'False' in this context would be a result that is a negative number. In contrast, 'True' would be a result that is a positive number. So, you evaluate the following: x1*weight1 + x2*weight2 + bias' is positive or negative For example, setting weight1=1, weight2=1, and bias=-1.1 (possible solution) you get for the first input: 0*1 + 0*1 + (-1.1) = -1.1 which is negative, meaning it evaluates to False for the next input: 0*1 + 1*1 + (-1.1) = -0.1 which is negative, meaning it evaluates to False for the next input: 1*1 + 0*1 + (-1.1) = -0.1 which is negative, meaning it evaluates to False and for the last input: 1*1 + 1*1 + (-1.1) = +0.9 which is positive, meaning it evaluates to True
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/49361612
has body: I want to get all the percentage from above string with decimal or without decimal points. I also want to get % sign. string = """Bachelor of Engineering in Electronics from in 2013 with 60%. Diploma (Electronics &amp; Video Engineering) from in 2009 with 79.39%. SSC from in 2006 with 61.71%.""" I have tried as below re.findall(r'\d+%|([0-9]\d?)\.\d+%', string) getting output as ['', '79', '61'] But I want output as below ['60%', '79.39%', '61.71%'] Anybody can tell where I am going wrong and regex to get expected output.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85723274
score: 3
tagged with: python
linked to: http://stackoverflow.com/q/30072184
tagged with: regex
tagged with: percentage
upvote count: 6
accepted answer: http://stackoverflow.com/a/49361644
has comment: http://stackoverflow.com/comment/85725545
duplicate of: http://stackoverflow.com/q/30072184
has comment: http://stackoverflow.com/comment/85723208
has comment: http://stackoverflow.com/comment/85723352
has answer: http://stackoverflow.com/a/49361644
answer count: 1
downvote count: 3
has title: Regex to parse percentage from the string
favorite count: 0
type: Question

http://stackoverflow.com/comment/85789200
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49393181
score: 0
has text: Why would it always be 1? Most likely, the db is assigning the next id based on whatever has been created before.

http://stackoverflow.com/comment/85759802
has text: Maybe you can precise what kind of operation you want to do in your `#Do something` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49379301
type: Comment
score: 0

http://stackoverflow.com/q/49341965
tagged with: python
has answer: http://stackoverflow.com/a/54172285
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/85686073
favorite count: 0
has title: statsmodels 2 dimensional kernel regression
type: Question
tagged with: statsmodels
has body: I have a dataframe with 3 columns ['X', 'Y', 'Z'] and I would like to study how the X and Y influence the distribution of Z. For that, I wanted to use the nonparametric regressor of nadaraya watson. In statsmodels there is a class called KernelReg that implement it. While I am able to successfully run the code for a 1-dimensional regression (Z on X and Z on Y), I struggle to run it for the 2-dimensional regression. My code is as follows: XYZ is my dataframe xv = XYZ['X'].values; yv = XYZ['Y'].values; zv = XYZ['Z'].values from statsmodels.nonparametric.kernel_regression import KernelReg ksrmv = KernelReg(endog=zv, exog= [xv, yv], var_type='c') The error I get is cannot reshape array of size 3171442 into shape (2,1) xv.shape = yv.shape = zv.shape =(1585721,) I already tried different alternative of specifying the exog like XYZ.loc[:, ['X', 'Y']] or XYZ.loc[:, ['X', 'Y']].values or np.concatenate([xv[:, None], yv[:, None]]) always the same error. In the description of exog in statsmodels. It should be a list of independent variable(s). Each element in the list is a separate variable, I am not sure how to interpret it.
upvote count: 6

http://stackoverflow.com/q/49326487
has title: Count function counting ' '
tagged with: python
accepted answer: http://stackoverflow.com/a/49326695
has body: I used a="string" to initialize a string in Python. I then used a.count(''); I did not write anything inside the quotes (not even a space). The count function returned 7 in this case. I also tried with a=str() and then repeated the countand got 1. Can anyone please explain it to me?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49326695
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/41079054
type: Question
has comment: http://stackoverflow.com/comment/85654651

http://stackoverflow.com/q/49324013
type: Question
has comment: http://stackoverflow.com/comment/85655090
has comment: http://stackoverflow.com/comment/85654980
tagged with: django
has answer: http://stackoverflow.com/a/49326939
tagged with: python
tagged with: jquery
has title: Django; error on printing JSON response in Firefox console
has comment: http://stackoverflow.com/comment/85655252
tagged with: ajax
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85653257
tagged with: http://stackoverflow.com/tag/json
answer count: 1
accepted answer: http://stackoverflow.com/a/49326939
has body: Urls.py: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http import JsonResponse def get_data(request): dictionary = {'Name':'John'} return JsonResponse(dictionary) def index(request): return render(request, 'javascript/index.html') Index.html: &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $.ajax({ method: "GET", url: "/api/data/", success: function(dictionary){ console.log(dictionary) }, error: function(error_data){ console.log("errorrr") console.log(error_data) } }) &lt;/script&gt; Using AJAX, I want to print dictionary contents upon index.html load. However, the Ajax call fails for some reason. Console.log output is: errorrr 127.0.0.1:8000:30:3 Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … } Is there any mistake in how my jQuery is written?

http://stackoverflow.com/q/49385159
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
has body: I have a numpy array of numpy array of 3 grayscale images with just 0 and 255 values (shape: (3, 512, 512)). I turned them to one-hot encodings into 2 classes using tf.one_hot (shape: (3, 512, 512, 2)). Now, I am trying to get them back to original form through np.argmax. But when I read the images, they are all black. labels = [] labels.append(label_1) labels.append(label_2) labels.append(label_3) labels = np.asarray(labels) print(labels.shape) # (3, 512, 512) sess = tf.InteractiveSession() labels = tf.one_hot(labels, 2) # (3, 512, 52, 2) print(labels.shape) #print(labels) labels = labels.eval() # to convert to numpy array from tensor imgs = np.argmax(labels, axis=3) # also tried tf.argmax print(imgs.shape) # (3, 512, 512) for i in range(imgs.shape[0]): image = imgs[i] print(img.shape) # (512, 512) indices = np.where(image &gt; 0) print(indices) # array([], dtype=int64), array([], dtype=int64) print(indices) image = Image.fromarray(image, 'L') image.show() # black images, values all zero I am sure I am missing something pretty simple but can't figure it out. Any help will be appreciated. Thanks. Edit: I checked for indices where the array has non-zero values. But all values seem to be zeros. So, not an issue of displaying the image. I think the problem is with argmax but I do not know what.
tagged with: one-hot-encoding
type: UnansweredQuestion
tagged with: python
has title: Converting images to one-hot array and back returns black images
has answer: http://stackoverflow.com/a/49385217
score: 1
upvote count: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49318607
has body: teststring = 'Index: WriteVTKOutput.FOR\\r\\n======================================\\r\\n' print(teststring.split("\\r\\n")[:-1]) print(teststring.strip("\\r\\n").split("\\r\\n")) Output ['Index: WriteVTKOutput.FOR', '======================================'] ['Index: WriteVTKOutput.FOR', '======================================']
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49318538

factorial
type: Tag
tag name: factorial
tags question: http://stackoverflow.com/q/49372279
tags question: http://stackoverflow.com/q/49407764

superclass
type: Tag
tag name: superclass
tags question: http://stackoverflow.com/q/49353201
tags question: http://stackoverflow.com/q/49386412

http://stackoverflow.com/a/49283625
has body: If method=='POST' and your form is invalid, nothing is returned.
has comment: http://stackoverflow.com/comment/85570092
downvote count: 0
answers question: http://stackoverflow.com/q/49283522
type: Answer
has comment: http://stackoverflow.com/comment/85570754
score: 4
upvote count: 4

http://stackoverflow.com/a/49438960
has comment: http://stackoverflow.com/comment/85912036
has comment: http://stackoverflow.com/comment/85912509
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49438907
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85913138
answers question: http://stackoverflow.com/q/49438907
has comment: http://stackoverflow.com/comment/85913415
has comment: http://stackoverflow.com/comment/85913991
has comment: http://stackoverflow.com/comment/85914913
has body: if your dataframe looks like this, with a column called json_col: import pandas as pd &gt;&gt;&gt; df json_col 0 {'a': 'x', 'b': 'y', 'c': 'z'} 1 {'a': 'x1', 'b': 'y2', 'c': 'z3'} You can do this: df'a','b','c' = df.json_col.apply(pd.Series) resulting in this final df: &gt;&gt;&gt; df json_col a b c 0 {'a': 'x', 'b': 'y', 'c': 'z'} x y z 1 {'a': 'x1', 'b': 'y2', 'c': 'z3'} x1 y2 z3
has comment: http://stackoverflow.com/comment/85910900
type: Answer

http://stackoverflow.com/a/49321265
score: 0
answers question: http://stackoverflow.com/q/49304002
has body: I had figure it out, I have to create a function that store all the lists during the loops: def funcThatStoreList(args, result =[]): result.append(args)
type: Answer

http://stackoverflow.com/comment/85789945
comment on: http://stackoverflow.com/q/49368211
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/40208051/selenium-using-python-geckodriver-executable-needs-to-be-in-path
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49387819
tagged with: python
has comment: http://stackoverflow.com/comment/85777128
tagged with: distance
score: 0
has answer: http://stackoverflow.com/a/49396240
has title: Assigning cluster based on minimum distance from a set of lat-long points with assigned clusters
tagged with: loops
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49401103
type: UnansweredQuestion
tagged with: cluster-analysis
has body: I have a dataframe(df1) as below: clust longitude latitude 1 77.62279999 12.95248389 1 77.62517676 12.95027966 2 77.62753442 12.93745478 2 77.62753442 12.93745478 3 77.62217671 12.93353553 3 77.62217671 12.93353553 I have a another dataframe with set of longitude/latitude(df2). I want to loop over all these points and for each point iterate over all points of df1 and assign the cluster value based on minimum distance. I can do a for looping and compute distance and but how to assign the cluster with minimum distance. Is looping the best method for such problem or there can be better method like knn or Kd-tree?

http://stackoverflow.com/comment/97870888
has text: You really help me a lot. I have no such issue on win10 Pro. However, such problem occurs when I work on win10 Enterprise distribution.
type: AnswerComment
comment on: http://stackoverflow.com/a/49442035
type: Comment
score: 0

http://stackoverflow.com/a/49293311
score: 0
answers question: http://stackoverflow.com/q/49284253
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49284253
has body: i found the solution, if i code this way it works as i wanted. keyboard = [] for i, events in enumerate(Events): if (events.gid == gid): keyboard = keyboard + InlineKeyboardButton(events.etkinlik + u" ", callback_data=i), InlineKeyboardButton(events.etkinlik + u" ", callback_data=i + 100) return InlineKeyboardMarkup(keyboard)

http://stackoverflow.com/comment/85778379
has text: The saving of each x value was a mistake on my part and has been fixed since it was pointed out. I have ran this code and the mass needs to be reduced as the effect is only for very small masses. thank you for your time
comment on: http://stackoverflow.com/a/49369331
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49352971
has comment: http://stackoverflow.com/comment/124581990
type: UnansweredQuestion
downvote count: 0
tagged with: django
has body: UPDATE: here is my progress in the last week, view.py: class PersoListView(ListView): template_name = 'sconsult/search.html' context_object_name = 'search_list' def get_context_data(self, **kwargs): get_image = self.request.GET.get('q') context = super(PersoListView, self).get_context_data(**kwargs) perkz = File.objects.select_related().filter( citid__persoid=get_image, filedoc__page='1', filedoc__docid='2').values( 'filedoc__docimage', 'filedoc__docid', 'filedesc') for perko in perkz: porkz = perko['filedoc__docimage'] tmp = 'sconsult/static/sconsult/media/images/' + perko['filedesc'] + '.jpg' img = Image.open(io.BytesIO(porkz)) img.save(tmp, 'JPEG') img64 = base64.b64encode(open(tmp, 'rb').read()).decode('utf-8').replace('\n', '') img_tag = '{0}'.format(img64) print(img_tag) context['img_list'] = img_tag return context def get_queryset(self): get_search = self.request.GET.get('q') if get_search is not None: perso = File.objects.select_related().filter( citid__persoid=get_search,filedoc__page='1',filedoc__docid='1').values( 'citid__name', 'citid__lastname', 'fileid', 'officeid__officedesc', 'citizenid') return perso and this is my relevant search.html template: {% for person in search_list %} {{ person.citid__name }} {{ person.citid__lastname }} View Details {% endfor %} {{ img_list }} I am fairly new to django and excuse my idents as they don't show up like this in the files. This field 'filedoc__docimage' is in bytearray inside the database: I know it's not the best idea, but that's what found. With this setup, I can retrieve the image as base64enconded and pass it to the template, the problem is that if I use a for loop for the 2 ListView Records, the print() gives me a vertical list of every character: img_tag = '{0}'.format(img64) for kaku in img_tag: print(kaku) context['img_list'] = img_tag If I don't do a for loop and print(img_tag) the listview displays the first image to the 2 records. What can I do? to fix this?
has title: Django: Display thumbnails in ListView from Queryset
tagged with: django-views
has comment: http://stackoverflow.com/comment/86010836
tagged with: python
favorite count: 0
type: Question
upvote count: 4
score: 4
tagged with: for-loop
answer count: 0
tagged with: django-queryset

http://stackoverflow.com/comment/85801117
comment on: http://stackoverflow.com/q/49399658
has text: @Graipher Nope. Well, yes, but it's the same as `n` nested for loops instead of two. That's how we get `n**n` instead of `n**2`. And that should give you a nice clue on how to write this pythonically with `itertools`, or how to write a simple recursive version, but I wanted to write it differently, so… see my answer.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51574696
upvote count: 1
answers question: http://stackoverflow.com/q/49377436
type: Answer
score: 1
has body: I was also trying on google colab. i have tried every thing for 2 hours finally this worked for me. url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states' pd.read_html(url, flavor='html5lib`) Official document suggests: The default of None tries to use lxml to parse and if that fails it falls back on bs4 + html5lib. http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html
downvote count: 0

http://stackoverflow.com/q/49308534
tagged with: jinja2
favorite count: 0
type: Question
has body: I have a really annoying problem where "&lt;" is displayed on my templates. Right at the very top of the web page is this annoying "&lt;" symbol. Could anyone please tell me what the cause of it is.
possible better answer: http://stackoverflow.com/a/49308657
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49308657
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/85619504
tagged with: flask
accepted answer: http://stackoverflow.com/a/49314782
has answer: http://stackoverflow.com/a/49308712
has answer: http://stackoverflow.com/a/49314782
type: AnsweredQuestion
has title: Flask random less than symbol on page
answer count: 3
has comment: http://stackoverflow.com/comment/85619397
tagged with: http://stackoverflow.com/tag/html
tagged with: templates

http://stackoverflow.com/comment/85789707
comment on: http://stackoverflow.com/a/49372599
score: 0
has text: @TimB. make sure that you copy the complete function with the `return df`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85570092
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49283625
type: AnswerComment
has text: Thanks for the response! I've edited to add the code from my template, any idea why my form would be invalid? I'm not sure why it'd be the case.

http://stackoverflow.com/comment/86024659
score: 0
comment on: http://stackoverflow.com/q/49406100
type: Comment
type: QuestionComment
has text: @MichaelMacAskill When I am running separate code for openpyxl, there is no problem, but when I am running my main program with psychopy I am getting the same error. Do you have any suggestions to deal with this problem?

http://stackoverflow.com/comment/85844456
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49421301
score: 0
has text: @bro-grammer who knows? this edge case is not clear, the OP doesn't mention what should happen to [1,1,2], assuming it should be kept is a stretch, and if not I'm not sure why you say it's not working...

http://stackoverflow.com/comment/85687209
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49338464
has text: Accept the answer if you think It answer to your question
type: Comment

http://stackoverflow.com/q/49285006
has answer: http://stackoverflow.com/a/49285257
has comment: http://stackoverflow.com/comment/85573138
has comment: http://stackoverflow.com/comment/85572934
downvote count: 0
tagged with: loops
upvote count: 1
possible better answer: http://stackoverflow.com/a/49285305
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85573049
has answer: http://stackoverflow.com/a/49285305
has answer: http://stackoverflow.com/a/49285128
tagged with: exception
has comment: http://stackoverflow.com/comment/85573017
score: 1
tagged with: python
has title: How to ignore exceptions while looping?
accepted answer: http://stackoverflow.com/a/49285122
answer count: 4
type: AnsweredQuestion
has body: I am trying to execute a loop while ignoring exceptions. I think pass or continue will allow me to ignore exceptions in a loop. Where should I put the pass or continue? class KucoinAPIException(Exception): """Exception class to handle general API Exceptions `code` values `message` format """ def __init__(self, response): self.code = '' self.message = 'Unknown Error' try: json_res = response.json() except ValueError: self.message = response.content pass else: if 'error' in json_res: self.message = json_res['error'] if 'msg' in json_res: self.message = json_res['msg'] if 'message' in json_res and json_res['message'] != 'No message available': self.message += ' - {}'.format(json_res['message']) if 'code' in json_res: self.code = json_res['code'] if 'data' in json_res: try: self.message += " " + json.dumps(json_res['data']) except ValueError: pass self.status_code = response.status_code self.response = response self.request = getattr(response, 'request', None) def __str__(self): return 'KucoinAPIException {}: {}'.format(self.code, self.message) And this doesn't work: from kucoin.exceptions import KucoinAPIException, KucoinRequestException, KucoinResolutionException for i in range(10): # Do kucoin stuff, which might raise an exception. continue
has answer: http://stackoverflow.com/a/49285122

http://stackoverflow.com/comment/85576506
type: Comment
has text: You are placing the pairs themselves in your list. When you then append to them, you are permanently modifying them; if the same pair is randomly chosen later, it will already have one letter appended to it. One solution would be to put copies of the pairs in your list before modifying them: `list[0] = choice(pair)[:]` for example.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49286723

http://stackoverflow.com/q/49342769
upvote count: 6
has answer: http://stackoverflow.com/a/49342802
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49343022
possible better answer: http://stackoverflow.com/a/49342850
has body: I have a data frame input that looks like: col1 col2 col3 0 3 1 NaN 1 NaN 7 8 How to collapse all rows while concatenating the data in the rows with ', '? The desired data frame output: col1 col2 col3 0 3 1, 7 8 Sample input code: import pandas as pd import numpy as np d = {'col1': ["3", np.nan], 'col2': ["1", "7"], 'col3': [np.nan, "8"]} df = pd.DataFrame(data=d)
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49342850
has answer: http://stackoverflow.com/a/49342871
score: 5
accepted answer: http://stackoverflow.com/a/49342784
answer count: 5
has answer: http://stackoverflow.com/a/49342784
tagged with: dataframe
tagged with: python
has title: How to concatenate values of all rows in a dataframe into a single row without altering the columns?

http://stackoverflow.com/comment/85905278
has text: @zimmer I've added an edit to the answer with some more explicit syntax using `pyspark.sql.functions.col`.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49430020

http://stackoverflow.com/comment/85879344
type: Comment
type: AnswerComment
score: 0
has text: @Coding_Rabbit, It's definitely possible - I suggest you first search on SO, or ask as a separate question.
comment on: http://stackoverflow.com/a/49434430

http://stackoverflow.com/comment/85754698
has text: You probably want to denote what version of NumPy, Pandas, Python you are benchmarking on, as well as your computer specs. Otherwise this isn't really meaningful. For instance, w/ NumPy 1.14.1, Pandas 0.22.0, Python 3.6.4, also benchmarking with `%timeit`, `x.apply(str)` takes 18ms and `list(map(str, x))` takes 15ms for me with your sample data. The benchmark order is completely different.
comment on: http://stackoverflow.com/a/49375038
type: AnswerComment
score: 2
type: Comment

http://stackoverflow.com/q/49333123
tagged with: bots
has comment: http://stackoverflow.com/comment/85668080
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/19254765
tagged with: sublimetext3
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49337909
type: Question
has body: Question Hey I'm basically a noob at sublime text and just transitioned from Anaconda Spyder because I'm trying to make a bot for supreme I'm testing stuff out and I had two input lines which looked something like input("hola") and if I type in "hi" into the console the code would stop and would not run the rest of the code and I wasn't sure why that was?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85683921
tagged with: python
score: -1
has title: How to fix sublime text terminating after input from user?

http://stackoverflow.com/a/49422482
has body: In order for python to recognize the module, first enter the virtual environment using the script located at: venv\Scripts\activate
has comment: http://stackoverflow.com/comment/85845943
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49422369
accepted answer of: http://stackoverflow.com/q/49422369

http://stackoverflow.com/a/49426464
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49319885
score: 1
type: Answer
has body: The problem seems to have been in the Consumer() arguments. This doesn't work properly: self.kafka_consumer = confluent_kafka.Consumer({ 'group.id': 'mygroup', 'bootstrap.servers': 'kafka:9092', 'auto.offset.reset': 'earliest', }) But this does: self.kafka_consumer = confluent_kafka.Consumer({ 'group.id': 'mygroup', 'bootstrap.servers': 'kafka:9092', 'default.topic.config': { 'auto.offset.reset': 'earliest', }, })
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49319885

http://stackoverflow.com/comment/85871388
has text: @CharlesDuffy thank you so much. things are much more clear now. im asking my friend for info on the certificate authority
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49433496

http://stackoverflow.com/comment/85585421
score: 0
comment on: http://stackoverflow.com/q/49291317
type: Comment
type: QuestionComment
has text: what is a cluster?

http://stackoverflow.com/a/49769613
type: Answer
answers question: http://stackoverflow.com/q/49424015
has body: I am using select now to locate class with multiple tags container.select('div.a-fixed-left-grid-col.a-col-right') Many thanks for all your helps.
score: 0

http://stackoverflow.com/comment/85570828
has text: Matplotlib has a really good documentation. It also has a lot of examples on the page. You may always check the types of objects in use to find out which methods are available.
type: Comment
comment on: http://stackoverflow.com/q/49283546
type: QuestionComment
score: 0

youtube-dl
tags question: http://stackoverflow.com/q/49348921
tag name: youtube-dl
tags question: http://stackoverflow.com/q/49396489
type: Tag

http://stackoverflow.com/comment/85754282
has text: Correct, I just figured it out. No need to find the doc, it just slipped out of my mind that `__add__` would return `NotImplemented` (and not raise `NotImplementedError` if I am correct).
comment on: http://stackoverflow.com/a/49356663
type: Comment
score: 0
type: AnswerComment

connection
tag name: connection
type: Tag
tags question: http://stackoverflow.com/q/49342839
tags question: http://stackoverflow.com/q/49402203

http://stackoverflow.com/comment/85825671
has text: I just want to point out that this won't add `script_2` to `sys.modules`. If you do `import script_2` anywhere in the code, you'll have two different copies of the `script_2` module - one of them with the name `__main__` and one with the name `script_2`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49411674
type: Comment

http://stackoverflow.com/comment/85699073
comment on: http://stackoverflow.com/q/49320520
score: 0
has text: Created a [github repo](https://github.com/der-spaete-jo/CalculationGame) for the full `buildozer android logcat` log. @inclement
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85653216
comment on: http://stackoverflow.com/q/49325795
type: Comment
type: QuestionComment
score: 0
has text: Does Python not allow || or is that just a Python 3 thing?

http://stackoverflow.com/q/49334963
tagged with: python
accepted answer: http://stackoverflow.com/a/49338605
has answer: http://stackoverflow.com/a/49338605
type: AnsweredQuestion
tagged with: qwidget
score: 1
answer count: 1
tagged with: pyqt5
upvote count: 1
has title: Rezising QWidget afer expanding/collapsing it
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am trying to automatically resize the QWidget dependent on whether it is expanded/collapsed. I have tried few ways posted here and here. I did not manage to adopt these so that it worked the way I want: I would like the QWidget to resize itself when it is expanded (it works now) but after collapsing it (unchecking the QCheckBox) its size remains too big and does not change back to its original state. Here is my code: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class CheckableComboBox(QComboBox): def __init__(self, parent = None): super(CheckableComboBox, self).__init__(parent) self.view().pressed.connect(self.handleItemPressed) self.setModel(QStandardItemModel(self)) self.setStyleSheet("QComboBox{" "font-size:11px;" "color:black;" "background-color:white;" "border:1px solid black;" "padding:1px;""}") self.setEditable(True) self.lineEdit().setAlignment(Qt.AlignCenter) self.lineEdit().setReadOnly(True) self.setMinimumSize(150, 40) def handleItemPressed(self, index): item = self.model().itemFromIndex(index) if item.text() != ' ' and item.checkState() == Qt.Checked: item.setCheckState(Qt.Unchecked) if item.text() != ' ' and item.checkState() != Qt.Checked: item.setCheckState(Qt.Checked) class Example(QWidget): def __init__(self): super().__init__() ## self.setFixedSize(350, 280) self.init_UI() def init_UI(self): self.years = [' ', '2017', '2018', '2019', '2020'] self.months = [' ', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] self.metrics = [' ', 'Seller', 'Section', 'Store'] self.units = [' ', 'Number of Pieces Sold', 'Total Value'] self.setWindowTitle('Dialog') self.sMetric = QLabel('Select metric(s):') self.sUnit = QLabel('Select unit(s):') self.okButton = QPushButton('Ok') self.cancelButton = QPushButton('Cancel') self.okButton.clicked.connect(self.okClicked) self.cancelButton.clicked.connect(self.cancelClicked) for i in (self.sMetric, self.sUnit, self.okButton, self.cancelButton): i.setFixedHeigh…
tagged with: pyqt
downvote count: 0

http://stackoverflow.com/q/49304932
downvote count: 1
favorite count: 0
tagged with: ocaml
type: AnsweredQuestion
score: 0
has title: OCaml equivalent of Python DictReader
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/49305814
has answer: http://stackoverflow.com/a/49305814
type: Question
has body: I am aware of the existence of the Csv package in OCaml, but as far as I know, it does not enable me to load a csv file like a stream of dictionares (as DictReader allows me to do it in Python). Is there a way to read such files as a stream of dictionaries ?
answer count: 1
upvote count: 1

http://stackoverflow.com/q/49340776
tagged with: anaconda
answer count: 1
has body: When using Jupyter Notebook on Windows 10 and starting multiple notebooks, each would open on the next available port (the first would be on port 8888, the next on 8889, etc.). I installed Anaconda on Windows Subsystem for Linux (WSL) and have had no issues, except when I try to start another notebook, it opens the same page wherever my previous notebook was started. Manually setting the port on startup like jupyter notebook --port 8889 works, but now I'm spoiled with letting jupyter figure it out for me. I had to set an alias for the default browser, which is a Windows executable (export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'). Additionally, I've generated a notebook configuration file, but I haven't figured out if it's doing anything. Thank you!
tagged with: python
tagged with: jupyter-notebook
type: Question
type: UnansweredQuestion
tagged with: ubuntu
has answer: http://stackoverflow.com/a/53806689
tagged with: windows-subsystem-for-linux
has title: Additional Jupyter Notebooks do not start on next available port
score: 0

http://stackoverflow.com/q/49373620
tagged with: append
type: AnsweredQuestion
has title: Appending multiple rows in df2 to df1 based on datetime
tagged with: concatenation
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49373733
downvote count: 0
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49373733
has body: I have 2 data frames, df1 and df2, both have the same format. For example, df1 looks like this: Date A B C D E 2018-03-01 1 40 30 30 70 2018-03-02 3 60 70 50 55 2018-03-03 4 60 70 45 80 2018-03-04 5 80 90 30 47 2018-03-05 3 40 40 37 20 df2 may look like this: The only difference is the start date Date A B C D E 2018-03-03 4 60 70 45 80 2018-03-04 5 80 90 30 47 2018-03-05 3 40 40 37 20 2018-03-06 7 55 26 46 42 2018-03-07 2 73 46 33 25 I want to append all the rows from df2 to df1, in this case, all the rows from 2018-03-06 so that df1 becomes: Date A B C D E 2018-03-01 1 40 30 30 70 2018-03-02 3 60 70 50 55 2018-03-03 4 60 70 45 80 2018-03-04 5 80 90 30 47 2018-03-05 3 40 40 37 20 2018-03-06 7 55 26 46 42 2018-03-07 2 73 46 33 25 Note: df2 may skip 2018-03-06, so all rows from 2018-03-07 will be copied and appended if that's the case. My dtype for df['Date'] is datetime64. I got an error when I tried to index the last_date of df1 to find the next_date to copy from df2. &gt;&gt;&gt;&gt; last_date = df1['Date'].tail(1) &gt;&gt;&gt;&gt; next_date = datetime.datetime(last_date) + datetime.timedelta(days=1) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Timestamp' Alternatively, how would you copy all the rows in df2 (starting from the date after the last date of df1) and append them to df1? Thanks.
tagged with: python

http://stackoverflow.com/q/49399917
has answer: http://stackoverflow.com/a/49401169
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/85801372
answer count: 1
has body: I have a code that runs through each row/item in a series and turns it into a bigram/trigram. The code is the following def splitting(txt,gram=2): tx1 = txt.str.replace('[^\w\s]','').str.split().tolist()[0] if(len(tx1)==0): return np.nan txlis = [w for w in tx1 if w.lower() not in stop_wrds] if gram==2: return map(tuple,set(map(frozenset,list(nltk.bigrams(txlis))))) else: return map(tuple,set(map(frozenset,list(nltk.trigrams(txlis))))) #pdb.set_trace() print len(namedat) prop_data = pd.DataFrame(namedat.apply(splitting,axis=1)) The error comes in the last line when I apply to a series data called namedat that looks something like this: 0 inter-burgo ansan 1 dogo glory condo 2 w hotel 3 onyang grand hotel 4 onyang hot spring hotel 5 onyang cheil hotel (ex. onyang palace hotel) 6 springhill suites paso robles atascadero 7 best western plus colony inn 8 hesse 9 ibis styles aachen city 10 pullman aachen quellenhof 11 mercure aachen europaplatz 12 leonardo hotel aachen 13 aquis grana cityhotel 14 buschhausen ... ... [166295 rows x 1 columns] ValueError: could not broadcast input array from shape (2) into shape (1) when using df.apply I tried debugging and the txts and bigrams are all generated succesfully, there seems to be no issue with the function called splitting. I am out of ideas on how to go about solving this. Please help The complete error message: Traceback (most recent call last): File "data_playground.py", line 163, in &lt;module&gt; main() File "data_playground.py", line 156, in main createparams(db.hotelbeds_properties,"hotelbeds") File "data_playground.py", line 139, in createparams prop_params = analyze(prop_subdf) File "data_playground.py", line 110, in analyze prop_data = pd.DataFrame(namedat.apply(splitting,axis=1)) File "/home/shubhang/.virtualenvs/pa/local/lib/python2.7/site-packages/pandas/core/frame.py", line 4877, in apply ignore_failures=ignore_failures) File "/home/shubhang/.virtualenvs/pa/local/lib/python2.7/site-packages/pandas/core/frame.py",…
type: Question
has title: ValueError: could not broadcast input array from shape (2) into shape (1) when using df.apply
has comment: http://stackoverflow.com/comment/85801041
tagged with: python
accepted answer: http://stackoverflow.com/a/49401169
type: AnsweredQuestion

http://stackoverflow.com/q/49407565
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49407683
has title: Pandas sorting based on two paired columns
type: Question
has body: I have two columns, "before" and "after". We'll just call them Bf and Af here. Based on many other attached columns, they have been ranked as follows: Bf Af 3 5 0 2 1 4 5 3 2 0 4 1 Now, the way they need to be sorted is Bf Af 0* 2 2 0 ----- 1* 4 4 1 ----- 3* 5 5 3 So, going through Bf, the lowest value is 0. So we set 0 on top. So the top pair is now 0-2, and the reverse order 2-0 must follow right after. Then we move on to the next before-after pair, which is 1-4, as 1 is the lowest, and we've already sorted 2 from Bf. The reverse is 4-1, which follows right after. And finally, the next value to sort in Bf is 3-5, with the reverse 5-3 right after. Does anybody have an idea of how to sort this?
tagged with: pandas
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: sorting

http://stackoverflow.com/q/49436979
score: 0
answer count: 0
has body: I am trying to open a serial port connection and keep it open as long as data if communicating. I also want to respond if certain data is received. Below is an example of the python script. I am able to open the serial port send data and the script responds, it will not respond with the elif data. I am new to pyserial and have been working on python lately but not great by any means. Thank you import serial import time ser = serial.Serial('/dev/ttyUSB0', timeout=10) # open serial port print(ser.name) # check which port was really used response = ser.read() if response == (b'\r'): ser.write (b'ID=') elif response == (b'\r\r\x1bPG1\r'): ser.write (b'110 1.8&lt;CR&gt;&lt;ACK&gt;&lt;CR&gt;&lt;ESC&gt;[p&lt;CR&gt;') #time.sleep(5) #print () #ser.close() # close port
tagged with: pyserial
type: UnansweredQuestion
type: Question
has title: python pyserial read data and respond
tagged with: python
has comment: http://stackoverflow.com/comment/85876082
has comment: http://stackoverflow.com/comment/85876692

http://stackoverflow.com/q/49308372
tagged with: scipy
favorite count: 0
type: Question
has title: Differential evolution in SciPy
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49309844
upvote count: 1
tagged with: python
tagged with: differential-evolution
has body: I am trying to use differential_evolution from SciPy. I have three matrices: x, y and P - all of size (14,6). I have to use the following formula: z= np.log10(g)+ np.log10(c)*np.log10(P) to find the value of c (real number from 0 to 2) which minimize: numpy.median(z**2) this expression. What I try is this (I provide the data for the convenience): import numpy as np from scipy.optimize import differential_evolution def func(c, args): z = args[0] + np.log10(c)*np.log10(args[1]) return np.median(z**2) if __name__ == '__main__': bounds = [(0, 2)] x = np.array([[126581.94951205, 97601.85624482, 59659.00330833, 27646.48551627, 9202.50377458, 4840.25789068], [213571.84886437, 148750.52154776, 85979.81139937, 38757.37831212, 11775.99906427, 4619.32027948], [195684.50299021, 131818.78542437, 74376.55189913, 32793.21715377, 10288.70838873, 4042.58093119], [177598.13865746, 120942.50439911, 68866.09898276, 30819.5354775 , 10588.08746517, 5011.71808947], [126433.18311483, 85863.57788065, 48923.64502157, 21828.60950911, 7907.37639781, 4410.61819399], [103431.88029629, 67452.94418262, 37608.36861047, 16456.97701443, 6027.98704858, 3550.06927169], [100689.06813945, 64380.21348052, 34764.02910376, 14849.85472635, 5607.19256065, 3605.5709208 ], [ 96509.22946744, 63832.74512518, 36041.69174706, 15802.87650901, 6473.33232805, 4664.07058733], [113078.63455882, 73227.02362359, 40861.09037499, 17385.89127848, 7074.98444924, 5136.84232454], [121241.93118924, 78537.13681709, 44257.97654994, 18584.94999742, 7733.39219718, 5869.49536788], [115948.06368262, 73995.07204278, 41536.21315507, 16851.59724901, 6736.25125909, 4851.5738275 ], [115024.20359423, 72108.15245783, 40341.98473413, 15900.55422399, 6243.63777265, 4411.24859372], [108754.83802899, 66210.25952459, 36485.42905112, 14577.73925124, 5553.23702141, 3736.5217322 ], [ 95340.59125024, 58458.97552915, 32364.19705748, 13236.30114676, 4929.04023171, 3202.21731277]]) y = y=np.array([[118166.08 , 95784.692 , 68134.878 , 37119.959 , 17924.1…
has answer: http://stackoverflow.com/a/49309844
tagged with: optimization
type: AnsweredQuestion
tagged with: mathematical-optimization
score: 1

http://stackoverflow.com/q/49406625
has title: Can't Click an Element in Python Selenium After Successfully Finding It
tagged with: python
has comment: http://stackoverflow.com/comment/85814881
has comment: http://stackoverflow.com/comment/85826251
has comment: http://stackoverflow.com/comment/85816146
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/85814714
has comment: http://stackoverflow.com/comment/85818410
score: 0
has comment: http://stackoverflow.com/comment/85816205
has comment: http://stackoverflow.com/comment/85816412
tagged with: firefox
answer count: 1
tagged with: selenium
has body: I am using the following script to find elements called 'service_notes' and click the first of them: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import os driver = webdriver.Firefox(executable_path=r'geckodriver.exe') driver.get("https://.../sites/frontiersupport/servicenotes/Pages/default.aspx") os.system("java -jar sikulix.jar -r login.sikuli") driver.implicitly_wait(5) # service_notes = driver.find_elements(By.XPATH, '//*/a[starts-with(@href, "/sites/frontiersupport/servicenotes/Lists/SNotes/DispForm.aspx")]') print(str(service_notes[0]) + ' is the first service note') print(len(service_notes)) service_notes[0].click() According to the log, the element is found, but for some reason I can't click it: <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="7505cfd0-5f41-4a8c-af28-bca639e13332", element="c81518a8-5f6c-42fa-8089-5f9469423d7c")> is the first service note 10 Traceback (most recent call last): File "scraper.py", line 19, in <module> service_notes[0].click() File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute return self._parent.execute(command, params) File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrac…
tagged with: webdriver
has comment: http://stackoverflow.com/comment/85816713
has answer: http://stackoverflow.com/a/49420227
type: Question
has comment: http://stackoverflow.com/comment/85816008
type: UnansweredQuestion

http://stackoverflow.com/q/49355443
score: 6
upvote count: 7
has comment: http://stackoverflow.com/comment/85711393
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85717148
has comment: http://stackoverflow.com/comment/85711141
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
tagged with: fpdf
type: Question
has comment: http://stackoverflow.com/comment/85713066
has title: How to write output data into pdf?
has answer: http://stackoverflow.com/a/49367290
has body: I can't find a way how to write output data (lists or function return) into pdf in python. This is my simple code. I want to write the i of data list line by line in pdf. But the output shows only [1,2,3,4,5,6]. Which pdf module is would be better for me to use? import fpdf data=[1,2,3,4,5,6] pdf = fpdf.FPDF(format='letter') pdf.add_page() pdf.set_font("Arial", size=12) for i in str(data): pdf.write(5,i) pdf.output("testings.pdf")
accepted answer: http://stackoverflow.com/a/49367290
linked to: http://stackoverflow.com/q/45953770
answer count: 1

http://stackoverflow.com/comment/85818137
has text: Fix this `print "(you will get retire soon)"` to this `print("you will get retire soon")` and fix your code indentation as well.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49408445
score: 0

http://stackoverflow.com/comment/85852274
has text: There is a '-i' missing before https://pypi.python.org/simple. The full command should be `pip install --upgrade pyls -i https://pypi.python.org/simple`
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49334899

azure-cosmosdb
tag name: azure-cosmosdb
tags question: http://stackoverflow.com/q/49388162
type: Tag
tags question: http://stackoverflow.com/q/49324754

http://stackoverflow.com/comment/100223538
comment on: http://stackoverflow.com/a/49479548
has text: To clarify: open a terminal, and run the above command. If you omit the '--ignore-installed', you will get the same error that PyCharm emits.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49312476
has comment: http://stackoverflow.com/comment/85627265
type: AnsweredQuestion
has body: I have a list of pathnames to CSV files. I need to open each CSV file, take the data without the header and then merge it all together into a new CSV file. I have this code which gets me the list of CSV file pathnames: file_list = [] for folder_name, sub_folders, file_names in os.walk(wd): for file_name in file_names: file_extention = folder_name + '\\' + file_name if file_name.endswith('csv'): file_list.append(file_extention) An example of my list is: ['C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data1.csv', 'C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data2.csv', 'C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data3.csv'] I am struggling to figure out what to do, any help would be greatly appreciated. Thanks.
score: 1
accepted answer: http://stackoverflow.com/a/49312620
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85626777
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85626853
has comment: http://stackoverflow.com/comment/85626769
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49312620
linked to: http://stackoverflow.com/q/30528673
has title: How to open and iterate through a list of CSV files - Python
tagged with: python

http://stackoverflow.com/q/49433058
tagged with: python-itertools
tagged with: python
accepted answer: http://stackoverflow.com/a/49433307
tagged with: splat
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49433307
score: 0
answer count: 1
type: Question
tagged with: python-3.x
has title: zip_longest on Array with lists of the same length. Understanding
has body: I have an Array which contains a few lists all the same length. All those lists need to be written in a .csv-file. Using a piece of code i have found it works pretty well. Here the code: ag=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]] export_data = zip_longest(*ag, fillvalue = '') with open('motion_profile.csv', 'w', encoding="ISO-8859-1", newline='') as myfile: wr = csv.writer(myfile, delimiter=',') wr.writerow(("m","ax","ay","az","sx","sy","sz")) wr.writerows(export_data) myfile.close() I understand the basic concept of zip and zip_longest when i have two arrays which i use it on. But i just can't wrap my head around what it does with a single array like here export_data = zip_longest(*ag, fillvalue = '') What exactly happens to ag if i use zip or zip_longest on it? Since i don't have two arrays what does it zip against? zip_longest is being applied to each list in ag hence the *. That is how far I have gotten with it. Could anyone walk me through that?

http://stackoverflow.com/comment/85789540
type: QuestionComment
has text: done, thank you. But still fighting with this.
comment on: http://stackoverflow.com/q/49392896
score: 0
type: Comment

http://stackoverflow.com/comment/85567772
type: Comment
has text: `pip --user ...` does not work?
type: QuestionComment
comment on: http://stackoverflow.com/q/49282501
score: 0

http://stackoverflow.com/comment/86028376
type: Comment
has text: Really like this idea. Have you got any suggestions on how I may implement the code for this in views?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49508982

http://stackoverflow.com/comment/85685079
type: QuestionComment
has text: https://support.google.com/recaptcha/answer/6081888
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49342399

http://stackoverflow.com/comment/85859716
type: QuestionComment
has text: The reason is that the user needs to call the generation from a web page. The webserver has PHP enabled and using the original image the python script spit out the PDF and PHP passed it through as a file download.
comment on: http://stackoverflow.com/q/49426581
score: 0
type: Comment

http://stackoverflow.com/comment/85782509
has text: Are you getting any error when executing your python code? If yes, can you post your stack trace?
comment on: http://stackoverflow.com/q/49390221
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49313345
has body: import json first_list = st.replace('[', '/{"').replace(']', '}').replace('="', '": "').split('/') [item if not "{" in item else json.loads(item) for item in first_list] or using ast.literal_eval import ast [item if not "{" in item else ast.literal_eval(item) for item in first_list] out: ['data', 'policy', 'line', {'Type': 'BusinessOwners'}, 'risk', 'coverage', {'Type': 'FuelHeldForSale'}, 'id']
has comment: http://stackoverflow.com/comment/85628702
has comment: http://stackoverflow.com/comment/85628257
has comment: http://stackoverflow.com/comment/85628270
type: Answer
answers question: http://stackoverflow.com/q/49313125
accepted answer of: http://stackoverflow.com/q/49313125
has comment: http://stackoverflow.com/comment/85650460
has comment: http://stackoverflow.com/comment/85628792
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85628670
type: AcceptedAnswer

http://stackoverflow.com/comment/85667385
score: 0
type: Comment
type: AnswerComment
has text: Thanks for your answer. But in the final output, the Column2 is found as 'CD', 'C', 'D', 'S', 'N', 'SN'. If I want to get that as the same order of Column1 (i.e., 'C', 'CD', 'D', 'N', 'S', 'SN'), what should be done within reindex? Thanks again @Scott in advance.
comment on: http://stackoverflow.com/a/49331665

http://stackoverflow.com/comment/85665322
type: QuestionComment
has text: Possible duplicate of [Running Python scripts from using PHP exec()](https://stackoverflow.com/questions/22808517/running-python-scripts-from-using-php-exec)
comment on: http://stackoverflow.com/q/49331641
score: 0
type: Comment

http://stackoverflow.com/comment/85668783
comment on: http://stackoverflow.com/a/49333515
has text: In this example, since the top 2 records are itself the top of the entire dataset, so its getting displayed correctly - However, if lets say instead of A, x, q having 8 records, B, x, p had 8 records then it should display B,x,p instead, which is not happening
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49336427
has comment: http://stackoverflow.com/comment/85679300
has comment: http://stackoverflow.com/comment/85678394
score: 0
answers question: http://stackoverflow.com/q/49336064
has comment: http://stackoverflow.com/comment/85679595
has body: l1=[[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']] l2 = list(map(lambda x: [x[0],"{}, {}".format(x[1],x[2])],l1)) print(l2)
type: Answer

http://stackoverflow.com/comment/85584816
type: AnswerComment
has text: You don't need a loop if you use `plt.setp` by the way.
score: 0
comment on: http://stackoverflow.com/a/49290628
type: Comment

http://stackoverflow.com/q/49365009
has title: Meeting Error when I install scipy
answer count: 1
tagged with: scikit-learn
has body: The situations above is what i have faced with. Totally don`t get it
tagged with: scipy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49365492
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49365492
type: AnsweredQuestion
score: -5
upvote count: 0
has comment: http://stackoverflow.com/comment/85730550

http://stackoverflow.com/comment/85794860
type: AnswerComment
comment on: http://stackoverflow.com/a/49396397
score: 0
type: Comment
has text: This looks like it would be great! Except I get an error for "empty range for randrange()". Tried adding some extra parentheses to no avail.

http://stackoverflow.com/q/49411605
tagged with: dataframe
tagged with: python
score: 2
answer count: 2
has title: Iterate over multiple columns in Pandas dataframe and create new columns
upvote count: 2
type: UnansweredQuestion
has body: I have a dataframe with measure columns SalesMonth1 -- SalesMonth12 and another columns Index and price. I am trying to do the following but it does not work. Could you please suggest a better way? For i in range(12): DF['Newcol'] = np.where(DF["Index"] &gt;0, DF["SalesMonth[i]"] * DF["price"], DF["SalesMonth[i]"])
downvote count: 0
has answer: http://stackoverflow.com/a/49411665
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49411673
tagged with: pandas
has comment: http://stackoverflow.com/comment/85824942

http://stackoverflow.com/q/49327905
has comment: http://stackoverflow.com/comment/85657743
upvote count: 5
score: 5
tagged with: matplotlib
linked to: http://stackoverflow.com/q/8409095
tagged with: python
has title: How to plot overlapping series using line and markers?
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85659459
favorite count: 0
has comment: http://stackoverflow.com/comment/85659083
accepted answer: http://stackoverflow.com/a/49328902
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85659822
has body: Given the following data: df1 a b c 1/1/2017 -162 1525 -41 1/2/2017 192 1530 86 1/3/2017 33 1520 -124 1/4/2017 173 1502 -108 1/5/2017 194 1495 -31 1/6/2017 -15 1520 -46 1/7/2017 52 1525 181 1/8/2017 -2 1530 -135 1/9/2017 37 1540 65 1/10/2017 197 1530 73 df2 a 1/3/2017 33 1/6/2017 -15 1/7/2017 52 1/8/2017 -2 1/9/2017 37 How can I produce at chart using matplotlib, that plots 'b' column of df1 and on top of that, puts markers on same plot line, but using the index points from df2. The desired chart would look something like this: I looked at this answer but can't quite adapt it. The issue is that in the example they use the values, but in my case the part that is common between the two data-sets is the index This is code from the referenced question that I tried: xs = df1['b'] ys = df2['a'] # ---&gt; this doesn't make sense here.... markers_on = df2.index plt.plot(xs, ys, '-gD', markevery=markers_on) plt.show() But the chart comes back empty: TypeError: &lt;class 'NoneType'&gt; type object None I also tried xs = df1['b'] markers_on = list(df2.index) plt.plot(xs, '-gD', markevery=markers_on) plt.show() But I get ValueError: `markevery` is iterable but not a valid form of numpy fancy indexing
tagged with: time-series
has answer: http://stackoverflow.com/a/49328902
has comment: http://stackoverflow.com/comment/85659319

http://stackoverflow.com/comment/85735980
type: QuestionComment
has text: Can you rearrange your array so that it is the *last* axis that is being summed? This should improve the CPU's use of its cache. My timing improved, from about 2.5 seconds to 1.9 seconds. Not a huge gain, but it helps.
score: 2
comment on: http://stackoverflow.com/q/49367278
type: Comment

http://stackoverflow.com/q/49313604
has body: I'm using python3.6 in windows7 and django 1.9 I got this error when i run my code. In my code i'm parsing xml data to write a html page. I got that some character is unable to encode properly thats why its throwing an error. \u2264 this is the character(less than or equal) which is the root cause of the error. My question is how to encode this properly in python3 Detailed Error Log: Traceback (most recent call last): File "C:\Dev\EXE\TEMP\cookie\crumbs\views.py", line 1520, in parser html_file.write(html_text) File "C:\Users\Cookie1\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2264' in position 389078: character maps to &lt;undefined&gt;
score: 1
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: unicode
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85628820
has title: UnicodeEncodeError: 'charmap' codec can't encode character '\u2264'
tagged with: python
tagged with: character-encoding
accepted answer: http://stackoverflow.com/a/49314530
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49314530

http://stackoverflow.com/comment/85750251
has text: So basically, the `if ... else` in the example above should determine if you are going to create a ConfigParser object for the specified file, or you're just gonna assign all your configuration options from the values obtained through `parse_args()`.
comment on: http://stackoverflow.com/a/49374094
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49386283
upvote count: 3
downvote count: 0
has body: Yes. It's actually very easy. Because cgi doesn't care what language it's written it - it's just a script that the web server runs on demand, and passes parameters. You can even use compiled C as your cgi language if you want. All you need to do is be able to read the local environment (and pretty much every language can) and read STDIN - and pretty much every language can. You can comfortably run perl and python scripts along side each other - the server simply doesn't care. To get more complicated, you might want to preload/prefork your cgi scripts, and then it starts to be a little more complicated to use arbitrary languages. But for a basic run-on-demand cgi script, anything will suffice.
score: 3
has comment: http://stackoverflow.com/comment/85784678
answers question: http://stackoverflow.com/q/49386143
type: Answer

http://stackoverflow.com/a/49329668
has comment: http://stackoverflow.com/comment/85661329
upvote count: 7
answers question: http://stackoverflow.com/q/49329569
has body: Here's an alternative, but I'm not sure if it's more classy than your original solution: df2 = pd.DataFrame([df.pop(x) for x in ['c', 'd']]).T df3 = pd.DataFrame([df.pop(x) for x in ['a', 'b']]).T Output: print(df2) # c d #0 0 0 #1 1 1 print(df3) # a b #0 0 0 #1 1 1
has comment: http://stackoverflow.com/comment/122610936
type: Answer
has comment: http://stackoverflow.com/comment/85661278
score: 7
downvote count: 0

http://stackoverflow.com/q/49415557
type: Question
has comment: http://stackoverflow.com/comment/85833619
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85832918
has body: newbie here i am creating a button that will print out the button is on the button is running the button is off so far I have done the code below but it keeps saying the self is not defined... class FireAlarm(self): def __init__(self, ringing): self.ringing = True def firealarmringing self.ringing = True def firealarmisstopped self.ringing = False def firealarmisringing self.ringing = True print(str("the alarm is" + FireAlarm(self)))
has title: creating a button on and off and running
tagged with: python-3.x
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85833016

http://stackoverflow.com/comment/85698088
score: 0
has text: https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size This question might help. Is creating a list with "append" inefficient somehow?
type: QuestionComment
comment on: http://stackoverflow.com/q/49349096
type: Comment

http://stackoverflow.com/a/69462921
has body: This can happen if your certificate cannot be verified by whichever SSL libraries are used by Jupyter (I think the details have changed a bit over time). This is common if there certificate is self-signed - the default certificate stores may not be able to verify your issuer. I currently do something like this with my Jupyter setup script: cat mycert.crt | openssl x509 -inform DER &gt;&gt; &quot;$(python -c 'import certifi; print(certifi.where())')&quot; I believe if you already have the certificate in PEM form then you only need: cat mycert.pem &gt;&gt; &quot;$(python -c 'import certifi; print(certifi.where())')&quot; and then start it like this: SSL_CERT_FILE=$(python -c 'import certifi; print(certifi.where())') jupyter notebook &amp; and stop similarly: SSL_CERT_FILE=$(python -c 'import certifi; print(certifi.where())') jupyter notebook stop The reason I use the certifi location and environment variable is that certifi appears to be the most-favoured package, and the environment setting appears to be respected by other libraries (including requests and built-in SSL modules). The reason to also start the server with this updated file is so that notebooks can themselves connect to the server (e.g. for introspection).
answers question: http://stackoverflow.com/q/49291335
score: 0
type: Answer

http://stackoverflow.com/comment/85758143
comment on: http://stackoverflow.com/q/49378776
score: 3
type: Comment
type: QuestionComment
has text: # global count..... it is commented?

http://stackoverflow.com/a/58502357
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49306177
downvote count: 0
type: Answer
has body: I've tried Jay's solution and didn't work, but after some reseach, this did (Django 2.1.2) factory = RequestFactory() request = factory.post('/post/url/') request.data = {'id': 1}

http://stackoverflow.com/comment/85731589
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49303679
has text: First of all, sorry for the late response and thank you for all the helpful approaches. Unfortunately, I couldn't use any of them without modifying my initial problem. Some suggestions were to time consuming, whereas others were to memory consuming. Nevertheless I marked all answers as useful which I tried and generally worked for the proposed issue.
type: Comment

http://stackoverflow.com/a/49429936
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49429884
score: 1
has body: Unicode characters at codepoints above 0xffff can be entered as literals like this: "\U0001f44D". For characters bellow 0xffff, the four digit version uses the u character, like in \u2654. If you have your emoji code as numeric data during program runtime, not at coding time, you can use the chr build in - actually, you can use the chr builtin all along. The inconveninence is that it yields a single character string, always: chr(0x1f44d). Back to literals, it is also possible to use the official unicode name for the character inside a Python 3 literal string - for that, use the \N prefix and enclose the character name between {}: "\N{THUMBS UP SIGN}". If you want to fetch characters by name at runtime, use the unicodedata.lookup: import unicodedata; unicodedata.lookup("THUMBS UP SIGN")
type: Answer
accepted answer of: http://stackoverflow.com/q/49429884

google-contacts-api
type: Tag
tag name: google-contacts-api
tags question: http://stackoverflow.com/q/49300549

http://stackoverflow.com/a/49323469
has body: You can try using the geopy library. https://pypi.python.org/pypi/geopy Here's an example from the documentation. &gt;&gt;&gt; from geopy.distance import vincenty &gt;&gt;&gt; newport_ri = (41.49008, -71.312796) &gt;&gt;&gt; cleveland_oh = (41.499498, -81.695391) &gt;&gt;&gt; print(vincenty(newport_ri, cleveland_oh).miles) 538.3904451566326 where vincenty is vincenty distance https://en.wikipedia.org/wiki/Vincenty%27s_formulae
answers question: http://stackoverflow.com/q/49323171
has comment: http://stackoverflow.com/comment/85648387
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85649793
upvote count: 2

http://stackoverflow.com/comment/85715816
type: AnswerComment
has text: its because you are using `csh` but `os.system` uses `sh`. You might have to enclose it in quotes to tell `csh` to run everything. does `os.system(‘/bin/csh "dotcshrc; ikvalidate mycase"’)` work?
type: Comment
comment on: http://stackoverflow.com/a/49357558
score: 0

http://stackoverflow.com/q/49394773
type: Question
tagged with: metric
tagged with: portfolio
answer count: 1
has body: I would like to incorporate a particular performance metric into my portfolio managing software. This metric should be one where I can measure "how much of the potential gains from the selected assets have been captured by the selected portfolio composition". Consider the following table reporting a portfolio's performance with key metrics between dates 2017/10 and 2018/03 netpeq: net $ profit gained over the period aroc: annualized rate of change in asset's price over the period cagr: compounded annualized growth of portfolio over the period I need a metric which penalizes divergence between cagr (or netpeq) and aroc. Namely, positive aroc says these asset could have produced growth (as in BA, MSFT, CSCO) but the portfolio manager failed to make money out of these or even lost money. I would like to measure the extent the portfolio manager missed to capture a. the growth potential due to each asset in the portfolio b. the overall growth potential w.r.t portfolio as a whole. +---------+----------+----------+---------+-------+--------+--------+--------+ | name | netpeq | draw | aroa | cagr | sharpe | rvalue | aroc | +---------+----------+----------+---------+-------+--------+--------+--------+ | BA | -555.71 | 3439.15 | -36.54 | -1.25 | -0.17 | 0.42 | 64.58 | +---------+----------+----------+---------+-------+--------+--------+--------+ | DWDP | 0 | 0 | 0 | 0 | 0 | 0 | -13.18 | +---------+----------+----------+---------+-------+--------+--------+--------+ | CAT | -447.66 | 1361.54 | -74.36 | -1.01 | -0.66 | -0.17 | 39.91 | +---------+----------+----------+---------+-------+--------+--------+--------+ | WMT | 363.25 | 448.09 | 183.34 | 0.82 | 1.1 | 0.66 | 4.73 | +---------+----------+----------+---------+-------+--------+--------+--------+ | UTX | 0 | 0 | 0 | 0 | 0 | 0 | 18.96 | +---------+----------+----------+---------+-------+--------+--------+--------+ | NKE | 690.34 | 498.24 | 313.36 | 1.57 | 1.21 | 0.84 | 67.19 | +---------+----------+----------+---------+------…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49500435
accepted answer: http://stackoverflow.com/a/49500435
score: 0
tagged with: performance
tagged with: python
tagged with: attribution
has title: Portfolio Performance Attribution Metrics

http://stackoverflow.com/q/49396415
accepted answer: http://stackoverflow.com/a/49396539
type: AnsweredQuestion
tagged with: tkinter
answer count: 2
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49396539
possible better answer: http://stackoverflow.com/a/49396857
has answer: http://stackoverflow.com/a/49396857
tagged with: centering
tagged with: python
has body: I have everything I'd like my code to perform, but it is bugging me that the square is not centered. I've been searching the internet for hours...please help! I have tried using anchor = "center" and .place() but I just can't seem to get it right. from tkinter import * import random class draw(): def __init__(self, can, start_x, start_y, size): self.can = can self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red") self.can.tag_bind(self.id, "&lt;ButtonPress-1&gt;", self.set_color) self.color_change = True def set_color(self,event = None): self.color_change = not self.color_change colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"] self.can.itemconfigure(self.id, fill = random.choice(colors)) root = Tk() canvas = Canvas(root) canvas.grid(column=1, row=1) square = draw(canvas,1,1,90) root.mainloop()
has title: How can I center a tkinter rectangle?
tagged with: drawrectangle

http://stackoverflow.com/q/49325049
type: UnansweredQuestion
answer count: 1
has title: Pandas Iterate over dataframe columns
tagged with: python
has body: For my data in dictionary format to pandas, how do I flag datasets (column in my pandas dataframe) if any of the values are outside of the range of 68 &amp; 72? df = pd.DataFrame(dict(a=[71.5,72.8,79.3], b=[70.2,73.3,74.9], c=[63.1,64.9,65.9], d=[70.1,70.4,70.9])) What I am attempting to do is create a seperate pandas dataframe of column names if any data is outside of the range of 68 &amp; 72. Any tips? df_OutOfRange=df[(df.columns&lt;68) | (df.columns&gt;72)] df_OutOfRange
tagged with: pandas
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49325142
downvote count: 0

http://stackoverflow.com/comment/85717510
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49358354
has text: my code is results = Tracking.query. \ filter(Tracking.time >= datetime.strptime(date_1, '%d-%m-%Y')). \ filter(Tracking.time <= datetime.strptime(date_2, '%d-%m-%Y')). \ order_by(Tracking.device_id, Tracking.time.desc()). \ distinct(Tracking.device_id, func.date(Tracking.time))

http://stackoverflow.com/q/49392396
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45862778
tagged with: python
has body: Background: I've been completing a course in machine learning and neural networks, and in the following where I experienced a problem, we're required to compute the cost function. There are two ways to do so by applying a np.multiply and np.sum OR by np.dot. I've called these cost1 and cost2, respectively in the example. They produce the same result. Question: My issue is that the function (which is already completed for me) asserts that the cost is a float using isinstance(). The first method produces a value which passes this test, and the second does not. However, when I print both values, and their associated dtypes, they both appear to be floats, although cost2 has greater precision. Why does cost2 fail the assertion test? The Code: def compute_cost(A2, Y, parameters): """ Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) parameters -- python dictionary containing your parameters W1, b1, W2 and b2 Returns: cost -- cross-entropy cost given equation (13) """ m = Y.shape[1] # number of example # Compute the cross-entropy cost ### START CODE HERE ### (≈ 2 lines of code) logprobs = np.multiply(np.log(A2), Y) cost1 = -np.sum(logprobs) cost2 = -np.dot(np.log(A2), Y.T) ### END CODE HERE ### cost1 = np.squeeze(cost1) # makes sure cost is the dimension we expect. cost2 = np.squeeze(cost2) # E.g., turns [[17]] into 17 # Troubleshooting print(cost1.dtype,cost2.dtype) print(cost1,cost2) assert(isinstance(cost1, float)) assert(isinstance(cost2, float)) return cost1 A2, Y_assess, parameters = compute_cost_test_case() print("cost = " + str(compute_cost(A2, Y_assess, parameters))) Output: float64 float64 0.692685886972 0.6926858869721941 --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-84-92a25de13cb3&gt; in &lt;module&gt;() 1 A2…
linked to: http://stackoverflow.com/q/35157742
tagged with: isinstance
has answer: http://stackoverflow.com/a/51427985
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85786592
favorite count: 0
has comment: http://stackoverflow.com/comment/85786581
tagged with: precision
has comment: http://stackoverflow.com/comment/85786658
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85786448
tagged with: python-3.x
upvote count: 2
has title: Python isinstance() of float failing assertion test

http://stackoverflow.com/comment/85821351
type: Comment
score: 0
type: AnswerComment
has text: For the list option, I'd say it depends on what percentage of dictionaries contain "information". If it is a usual / *expected* key, then a `try` / `except` or `x.get(..., {}).get(..., None)` may be more appropriate. If it's not expected, then your method looks good.
comment on: http://stackoverflow.com/a/49409779

http://stackoverflow.com/comment/85837909
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49417841
type: QuestionComment
has text: @MystMan "all the modules" is one module that I happen to think will make your life easier. I also just asked for a traceback. I also didn't downvote. It can feel a bit brutal joining SO and, if in doubt, read comments as being objective rather than intending to be condescending/hurtful/etc.

http://stackoverflow.com/a/49327910
type: Answer
has comment: http://stackoverflow.com/comment/85690834
score: 0
answers question: http://stackoverflow.com/q/49327630
has body: You're confusing two different kinds of writing to file. sys.stdout pipes your output to the console/terminal. This can be written to file but it's very roundabout. Writing to file is different. In python you should look at the csv module if you're writing lists of values of all the same length (and maybe even if you're not, it's very easy to use). Open your file outside the loop. In the loop, write to file line by line. Close the file outside the loop. This is automatically done for you if you use the following "with" syntax: import csv with open('file.csv') as f: writer = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for loop: # tokenize tweet writer.writerow(tweet) Alternatively, loop through and save tokenized-tweets to a list-of-lists. Then, outside and after the loop, write the entire thing to a file: import csv tweets = [] for loop: # tokenize tweet tweets.append(tweet) with open('file.csv') as f: writer = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerows(tweets)

http://stackoverflow.com/comment/85729101
type: Comment
has text: Can you modify your example code to actually create and use a `test.db`? Very difficult to debug a problem in code that doesn't display the problem.
score: 1
comment on: http://stackoverflow.com/q/49334295
type: QuestionComment

http://stackoverflow.com/a/49345882
type: Answer
has body: I would try the following approach: start with a low threshold, for example: 1e-4 reduce your features using SelectFromModel fit &amp; transform compute metrics (accuracy, etc.) for your estimator (RandomForestClassifier in your case) for selected features increase threshold and repeat all steps starting from point 1. Using this approach you can estimate what is the best threshold for your particular data and your estimator
upvote count: 6
answers question: http://stackoverflow.com/q/49345578
accepted answer of: http://stackoverflow.com/q/49345578
downvote count: 1
score: 5
type: AcceptedAnswer

http://stackoverflow.com/a/54869077
downvote count: 1
has comment: http://stackoverflow.com/comment/108873864
upvote count: 30
has comment: http://stackoverflow.com/comment/108666780
type: Answer
has comment: http://stackoverflow.com/comment/124352873
has comment: http://stackoverflow.com/comment/106570203
score: 29
has body: Basically, if you want to use the Kaggle python API (the solution provided by @minh-triet is for the command line not for python) you have to do the following: import kaggle kaggle.api.authenticate() kaggle.api.dataset_download_files('The_name_of_the_dataset', path='the_path_you_want_to_download_the_files_to', unzip=True) I hope this helps.
answers question: http://stackoverflow.com/q/49386920

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

http://stackoverflow.com/a/49434822
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49434760
downvote count: 0
has body: Regular expressions alone cannot solve the problem, use a set to keep track of what you have already seen: pattern=re.compile(r'(1[6][2]\.[0-9][0]+)') seen = set() if pattern.search(line): if line not in seen: seen.add(line) print line
type: Answer

http://stackoverflow.com/comment/85685286
comment on: http://stackoverflow.com/q/49342151
type: Comment
type: QuestionComment
has text: OK, if you've already started installing things against the built-in Python 2, you're probably better off sticking with that. It may or may not have been the right decision from a clean start, but installing another 2.7 now when you've already got `pip` and things in `site-packages` is just going to cause major confusion. So never mind that part.
score: 0

http://stackoverflow.com/comment/85867136
score: 0
type: Comment
type: QuestionComment
has text: "'nvcc' is currently not installed". Since I don't have sudo-rights I ll have to wait until tomorrow to try this out. May that solve the problem? The code from the other answer returns also [] for the gpu-list.
comment on: http://stackoverflow.com/q/49432451

http://stackoverflow.com/comment/85621408
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49308678
has text: @Noctsol edited in an explanation and an expanded version of the function. Hope it helps.

http://stackoverflow.com/comment/85690866
comment on: http://stackoverflow.com/q/49345482
score: 0
type: Comment
type: QuestionComment
has text: Looks like [`savez`](https://github.com/numpy/numpy/blob/master/numpy/lib/npyio.py#L669) is a compressed file. This means that appending to it would require you to read from it first and then overwrite it.

initialization
tags question: http://stackoverflow.com/q/49372813
tags question: http://stackoverflow.com/q/49362219
tag name: initialization
tags question: http://stackoverflow.com/q/49424252
tags question: http://stackoverflow.com/q/49317933
type: Tag

http://stackoverflow.com/comment/120404786
type: AnswerComment
comment on: http://stackoverflow.com/a/49639324
has text: Can you say more about how this works? doctree-resolved is emitted *after* post-transforms are run, so your post-transforms are just ignored, as far as I can tell.
type: Comment
score: 0

http://stackoverflow.com/q/49390121
score: 5
downvote count: 0
tagged with: vpython
has comment: http://stackoverflow.com/comment/85781921
answer count: 1
has answer: http://stackoverflow.com/a/49398160
accepted answer: http://stackoverflow.com/a/49398160
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85781710
upvote count: 5
has body: When I run this code I get an error "Error: Property 'pos' must be a vector." Do I have to write another vector somewhere? Because I wrote vector at grav_force = vector(0,-object.mass*grav_field,0) This is my whole code GlowScript 2.7 VPython from visual import * display(width = 1300, height = 1000) projectile = sphere(pos = (-5,0,0), radius = 0.1, color = color.red, make_trail = True) projectile.speed = 3.2 # Initial speed. projectile.angle = 75*3.141459/180 # Initial angle, from the +x-axis. projectile.velocity = vector(projectile.speed*cos(projectile.angle), projectile.speed*sin(projectile.angle), 0) projectile.mass = 1.0 grav_field = 1.0 dt = 0.01 time = 0 while (projectile.pos.y &gt;=0): rate(100) # Calculate the force. grav_force = vector(0,-projectile.mass*grav_field,0) force = grav_force # Update velocity. projectile.velocity = projectile.velocity + force/projectile.mass * dt # Update position. projectile.pos = projectile.pos + projectile.velocity * dt # Update time. time = time + dt
tagged with: python
tagged with: glowscript
type: AnsweredQuestion
has title: "Property 'pos' must be a vector" Error when I run VPython Code

http://stackoverflow.com/q/49436756
answer count: 2
has body: This is actually for the thread on unknown error: call function result missing 'value' for Selenium Send Keys even after chromedriver upgrade but I guess my reputation isn't high enough to participate(lame). I got the error: WebDriverException: Message: unknown error: call function result missing 'value' (Session info: chrome=65.0.3325.162) (Driver info: chromedriver=2.33.506106 platform=Mac OS X 10.13.3 x86_64) when running this line: driver.execute_script('window.scrollTo(0, %s)' % scroll_to) I updated and everything else but that error still popped up, however the code actually executed before raising the error, so simply passing the exception allowed me to accomplish my goal, kinda sloppy so it'd be cool if I could make the error go away for real, but this is working for now: driver.get('https://www.azcentral.com/search/trump/') page_height = int(driver.get_window_size()['height']) scroll_to = 0 start_time = time.time() wait = 90 while True: scroll_to += page_height try: driver.execute_script('window.scrollTo(0, %s)' % scroll_to) except: time.sleep(1) pass end_time = time.time() uptime = timedelta(seconds=int(end_time - start_time)) if uptime > timedelta(seconds=wait): break
upvote count: 3
downvote count: 0
tagged with: selenium
favorite count: 0
has title: Python Selenium driver.execute_script WebDriverException: Message: unknown error: call function result missing 'value'
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/49162667
tagged with: python
possible better answer: http://stackoverflow.com/a/49437509
accepted answer: http://stackoverflow.com/a/49454550
tagged with: webdriver
has answer: http://stackoverflow.com/a/49437509
tagged with: selenium-webdriver
type: Question
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/49454550

http://stackoverflow.com/comment/85891299
comment on: http://stackoverflow.com/a/49440062
has text: If the list is not None or empty and i is less than the length of list then list[i] will be returned. In all other cases default value of {} will be returned.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49304446
score: 0
has comment: http://stackoverflow.com/comment/85611753
has body: you may use extend method: def doSomething(something): list = [] for a in something: list.append(a) # ....this loop for some definite number... return list allist = [] allist.extend(doSomething(smt1)) allist.extend(doSomething(smt2)) allist.extend(doSomething(smt3))
answers question: http://stackoverflow.com/q/49304002
type: Answer

http://stackoverflow.com/comment/85725538
has text: I guess this is slower according some other posts here in stackoverflow in similar questions.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49362506
type: Comment

http://stackoverflow.com/comment/85740415
type: Comment
has text: Honestly, I don't understand at all what you want me to do ... length N: isn't that my sdr.sample_rate? I have already tried: real_sig = np.fft.fft(signals[0], n=sdr.sample_rate) decibel = 10*log10(var(real_sig)) plt.plot(decibel) But that doesn't work as the length has to be an integer value. And even if I change it to an int value, I get an empty plot.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49369427

http://stackoverflow.com/comment/85794505
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49396311
has text: But meanwhile, I think what you want here is [`accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate), not `map`. You do want to add a starting value, but there are two easy ways to do that: (1) chain the starting value onto the input before calling `accumulate` then skip over it in the output, or (2) copy the "roughly equivalent to" code in the docs and write your own version that takes a start value as an additional parameter.

http://stackoverflow.com/comment/85689983
type: Comment
comment on: http://stackoverflow.com/a/49344882
has text: @clink; Sure. Updated snippet.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85828214
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49410007
has text: Thanks! It's supposed to be a square root function! I would have had a hard time figuring this out. Thanks for making it easy.

http://stackoverflow.com/comment/86282153
score: 0
has text: What do you mean by platform? I get the error both on Ubuntu 16.04 with required dependencies, and in a docker image that I can share in order to reproduce the issue.
comment on: http://stackoverflow.com/q/49433383
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49400431
tagged with: django-2.0
type: UnansweredQuestion
tagged with: django-channels
has title: Django 2 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
tagged with: python
has comment: http://stackoverflow.com/comment/85806874
has body: I currently have a django app running Django==2.0. I wasn't having this problem before but yesterday when I was running through some code I got the error from home.models import Notification ImportError: cannot import name 'Notification' This was from meetings/models.py which is an app at the same level as mange.py My apps are registered as following INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'meetings', ] If I simple import home and then print it out I see &lt;module 'home' from '&lt;relative_path&gt;/home/__init__.py'&gt; But if I try something like this from django.apps import apps print(apps.get_models()) I get the error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. After that I tried testing the same thing through python manage.py shell and I got completely different results. apps.get_models() returned all of the models I was expecting to see and that are in the database. &gt;&gt;&gt; apps.get_app_config('home').models['notification'] returned &lt;class 'home.models.Notification'&gt; I'm trying to figure out why I can't import Notification in my meetings models and why I'm getting different results when I run these commands in the shell. I also have django channels and storages as installed apps.
has comment: http://stackoverflow.com/comment/85818830
has comment: http://stackoverflow.com/comment/85802238
score: 2
answer count: 0
upvote count: 2
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/85819281
favorite count: 0
type: Question

http://stackoverflow.com/q/49414376
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85831005
has comment: http://stackoverflow.com/comment/85830720
tagged with: pyqt
has comment: http://stackoverflow.com/comment/85882393
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/85830972
has comment: http://stackoverflow.com/comment/85830957
has comment: http://stackoverflow.com/comment/85830730
has answer: http://stackoverflow.com/a/49475735
type: Question
has comment: http://stackoverflow.com/comment/85831519
has comment: http://stackoverflow.com/comment/85831597
has comment: http://stackoverflow.com/comment/85831933
has body: I am using python3 with PyQt5 and matplotlib FigureCanvasQTAgg. I need to update a plot every 1 second, so I use QTimer. The timer works properly, but the plot is not updated. Here is the code: main.py import UI_action from PyQt5.QtWidgets import QApplication import sys if __name__ == '__main__': app = QApplication(sys.argv) main_window = UI_action.Connection() main_window.show() sys.exit(app.exec_()) UI_action.py import UI_layout_test from PyQt5.QtWidgets import QWidget import mplwidget class Connection(QWidget): def __init__(self): super(Connection, self).__init__() self.my_widget_ui = UI_layout_test.Ui_MainWindow() self.my_widget_ui.setupUi(self) self.plot = mplwidget.Plot() self.my_widget_ui.pushButton_start.clicked.connect(self.__slot_start) def __slot_start(self): self.plot.plot() UI_layout_test.py (generated by Qt Designer) from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(692, 602) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.widget_fig = MplWidget(self.centralwidget) self.widget_fig.setGeometry(QtCore.QRect(30, 20, 631, 481)) self.widget_fig.setObjectName("widget_fig") self.pushButton_start = QtWidgets.QPushButton(self.centralwidget) self.pushButton_start.setGeometry(QtCore.QRect(550, 520, 113, 32)) self.pushButton_start.setObjectName("pushButton_start") self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate self.pushButton_start.setText(_translate("MainWindow", "Start")) from mplwidget import MplWidget mplwidget.py from PyQt5 import QtWidgets from PyQt5 import QtCore import matplotlib matplotlib.use('Qt5Agg') from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from numpy import * class MplCanvas(FigureCanvas): def _…
tagged with: qtimer
has comment: http://stackoverflow.com/comment/85831430
tagged with: python
has comment: http://stackoverflow.com/comment/85855752
has title: How to use QTimer to update a matplotlib FigureCanvas defined in another class?
accepted answer: http://stackoverflow.com/a/49475735
has comment: http://stackoverflow.com/comment/85830865

http://stackoverflow.com/q/49358750
tagged with: python
upvote count: 4
type: Question
linked to: http://stackoverflow.com/q/47236465
has body: I am converting some legacy code to use the Dataset API - this code uses feed_dict to feed one batch to the train operation (actually three times) and then recalculates the losses for display using the same batch. So I need to have an iterator that returns the exact same batch two (or several) times. Unfortunately, I can't seem to find a way of doing it with tensorflow datasets - is it possible?
accepted answer: http://stackoverflow.com/a/49367766
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85790705
has title: How can I return the same batch twice from a tensorflow dataset iterator?
score: 4
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49367766

http://stackoverflow.com/comment/85845273
type: QuestionComment
comment on: http://stackoverflow.com/q/49421764
score: 0
has text: Did you try using selectors, I saw the page and It's unique for each Cell. And if you get data using selector you wouldn't have to use `split` and all. You'd need to spent a little time but you'll get it eventually.
type: Comment

http://stackoverflow.com/comment/85723985
type: Comment
has text: How about this one ? print (out.groupby(out['Date'].dt.quarter)['tenure'].count()) Date 1 4429 2 431 3 252 4 242 Name: tenure, dtype: int64
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49359884

http://stackoverflow.com/a/49366670
has body: Regarding your issues you are installing cpu only and old MAC version of tensorflow which shouldn't work on windows. You could try using the following command python3 -m pip install https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0-cp35-cp35m-win_amd64.whl But I suggest you use Anaconda for the windows to install tensorflow and keras it has much less errors on windows, you can find a guide for it here https://github.com/antoniosehk/keras-tensorflow-windows-installation.
has comment: http://stackoverflow.com/comment/85734746
has comment: http://stackoverflow.com/comment/85734891
has comment: http://stackoverflow.com/comment/85734412
has comment: http://stackoverflow.com/comment/85734627
answers question: http://stackoverflow.com/q/49366046
type: Answer
has comment: http://stackoverflow.com/comment/85734688
score: 0

http://stackoverflow.com/a/49285756
upvote count: 2
answers question: http://stackoverflow.com/q/49285147
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49285147
has comment: http://stackoverflow.com/comment/85578628
has body: I'm pretty sure you need to explicitly declare which status code you want to return in your view function; the swagger description is just documentation that your API server doesn't actually care about. Something like this pseudo code: def image(): if request.method == 'POST': if not is_valid(request.form): return jsonify({'errors': [...]}), 400 # do stuff return jsonify({'description': 'created'}), 201

http://stackoverflow.com/comment/85730409
comment on: http://stackoverflow.com/a/49362574
type: Comment
type: AnswerComment
score: 0
has text: I have tried to perform the selection by the xpath but it steel doesn't work (see the 5th attempt)

binary-tree
tag name: binary-tree
tags question: http://stackoverflow.com/q/49391890
type: Tag
tags question: http://stackoverflow.com/q/49406653

http://stackoverflow.com/comment/85837495
score: 0
type: Comment
type: QuestionComment
has text: So, is there a different way to wait, where I know what these subprocesses are doing?
comment on: http://stackoverflow.com/q/49417780

http://stackoverflow.com/comment/85617305
comment on: http://stackoverflow.com/a/49306551
has text: @piRSquared appreciate the timing !! :-)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85785700
comment on: http://stackoverflow.com/q/49391838
has text: If you want to use pandas, df.groupby('id').first() will do the trick for you
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85863861
has text: @AbhijitBalaji not the opencv bits, because they'll switch back to the cpp implementation library very quickly (They want it to be fast in python too!). How you process the results may be faster in c++ than in python; but nothing's stopping you putting your processing of the results in c++ in a module if it's slow. (Just make sure that you have a module that abstracts that chunk away; and then you'll not have to re-write everything if you try that route)
type: AnswerComment
comment on: http://stackoverflow.com/a/49430367
score: 1
type: Comment

http://stackoverflow.com/a/49379304
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49378655
has comment: http://stackoverflow.com/comment/85801793
score: 2
type: Answer
has body: Looking at the response of the original URL, it only contains an HTML redirect to the new URL: <TITLE>Single Document Assuming response is always going to have the same format / content, you could easily capture the sub-URL from this response using RegEx, like so: re.search('CONTENT="1;URL=(.+)"', r.text).group(1) Then go to it. That all can be done by requests now, so you won't need to wait for Selenium! Here's your code after using the trick above: import time, requests, re from bs4 import BeautifulSoup start_time = time.time() root_url = "http://patft.uspto.gov" r = requests.get(root_url + "/netacgi/nph-Parser?patentnumber=3,930,293") r = requests.get(root_url + re.search('CONTENT="1;URL=(.+)"', r.text).group(1)) soup = BeautifulSoup(r.text, 'lxml') for tag in soup.find_all(string='Current U.S. Class:'): table = tag.findParent('table') result = table.find('tr').text print(result) print(time.time() - start_time) Output: Current U.S. Class: 29/428; 28/284; 28/297; 8/155 2.2239434719085693
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49378655

http://stackoverflow.com/q/49343087
has answer: http://stackoverflow.com/a/49343121
favorite count: 0
has body: I have one main folder, and there are 3 sub folders under the main folder. I want to plot the first few images from each sub folder in one single plot. How can I do that? So far, I am able to perform the two tasks separately: Print the first 5 images from each folder directory=os.listdir('main_folder') for each in directory: currentFolder = 'main_folder/' + each for file in os.listdir(currentFolder)[0:5]: fullpath = main_folder+ "/" + file print(fullpath) img=mpimg.imread(fullpath) plt.imshow(img) #this seems to be plotting the last image Plot several subplot on one plot for i in range(1, 7): plt.subplot(2, 3, i) How can I combine the two, so I can plot the first few images from each folder?
type: Question
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Matplotlib display the first {n} images from each folder
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49343121
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85652905
score: 0
has text: @DanielRoseman The docs simply say that this assertion: "Asserts that a Response instance produced the given status_code and that text appears in the content of the response." It just says a response, not seemingly precluding external API responses. Do you recommend not testing API connectivity in unit tests?
comment on: http://stackoverflow.com/q/49325478
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85699069
comment on: http://stackoverflow.com/q/49349644
score: 0
type: Comment
type: QuestionComment
has text: Is there any reason why you are using double preceding underscores instead of one (or none)? https://stackoverflow.com/a/7456865/8079103

http://stackoverflow.com/a/49281306
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/85567135
has comment: http://stackoverflow.com/comment/85566627
has comment: http://stackoverflow.com/comment/85565209
upvote count: 6
has comment: http://stackoverflow.com/comment/85566471
has comment: http://stackoverflow.com/comment/85568253
has comment: http://stackoverflow.com/comment/85686379
answers question: http://stackoverflow.com/q/49281051
downvote count: 0
has body: Strings are immutable, so you can’t literally remove characters from them, but you can create a new string that skips over those characters. The simplest way is: s = ''.join(ch for ch in s if not ch.isupper()) If you want to do this without for for some reason (like an assignment requirement), we can write this out as an explicit loop, and then convert it to a while. So: result = [] for ch in s: if not ch.isupper(): result.append(ch) s = ''.join(result) To change the loop, we have to manually setup and next the iterator, but it may be easier to understand with just a plain int as an index instead of an iterator: result = [] i = 0 while i &lt; len(s): ch = s[i] if not ch.isupper(): result.append(ch) i += 1 s = ''.join(result) Of course this is more verbose, slightly less efficient, and easier to get wrong, but otherwise it’s basically equivalent, and it meets your strange requirements. In real life, there might be better ways to do this—e.g., str.translate with a map from all caps to None should be pretty fast if you only care about ASCII caps—but I assume your teacher doesn’t want you thinking in those directions, they want you thinking about the loops explicitly. (Of course there is a loop in str.translate, or re.sub, etc., that loop is just hidden under the covers where you don’t see it.) If you need to do this to multiple strings in a list, you’d wrap it up in a function, and apply it to each string in the list, using a comprehension—or you can write it out as a loop statement, and convert it to a while loop, if you prefer, in exactly the same way. For example: def remove_caps(s): result = [] i = 0 while i &lt; len(s): ch = s[i] if not ch.isupper(): result.append(ch) i += 1 return ''.join(result) strings = ['aBC', 'Abc', 'abc', ''] new_strings = [] i = 0 while i &lt; len(strings): new_strings.append(remove_caps(strings[i])) i += 1
has comment: http://stackoverflow.com/comment/85686383
has comment: http://stackoverflow.com/comment/85566489
has comment: http://stackoverflow.com/comment/85686185
has comment: http://stackoverflow.com/comment/85686328
has comment: http://stackoverflow.com/comment/85686405
has comment: http://stackoverflow.com/comment/85565635
has comment: http://stackoverflow.com/comment/85566004
has comment: http://stackoverflow.com/comment/85686422
has comment: http://stackoverflow.com/comment/85565467
has comment: http://stackoverflow.com/comment/85566560

http://stackoverflow.com/comment/85573463
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49285277
has text: A plot needs x and y values. If you only provide y values, they won't have any x partner.
score: 1

http://stackoverflow.com/comment/85716753
type: QuestionComment
type: Comment
has text: Please add your `Dockerfile` to the question.
score: 0
comment on: http://stackoverflow.com/q/49357299

http://stackoverflow.com/a/49379997
has comment: http://stackoverflow.com/comment/85761304
type: Answer
accepted answer of: http://stackoverflow.com/q/49379448
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Without the data to run the code myself I have to guess. But the ValueError indicates that the dimension of your input from x_batch (100, 150, 70) does not match the shape of the placeholder (None, 150). If I understand your code correctly, each image you are trying to classify has 150x70 pixels. If that's true then I would flatten each of those into a vector and use that vector's length as the placeholder x's dimension (None, 150x70). Also, it seems, y doesn't have a specified shape. In this case it should be (None, 2). If there is no particular reason why you encode your two labels "fake" and "authentic" as two dimensional vectors, you could also use a just one dimensional vector.
answers question: http://stackoverflow.com/q/49379448

http://stackoverflow.com/comment/85687954
score: 0
has text: @StephenRauch the codes been reupdated.
comment on: http://stackoverflow.com/q/49343798
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49374816
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49372284
score: 1
answers question: http://stackoverflow.com/q/49372284
has body: the issue is with buffering of IO, in python after each print you should flush the buffer sys.stdout.flush()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49351194
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/49350445
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49350445
score: 29
upvote count: 30
has body: Calling .corr() on the entire DataFrame gives you a full correlation matrix: &gt;&gt;&gt; table.corr() Group Age Group 1.0000 -0.1533 Age -0.1533 1.0000 You can use the separate Series instead: &gt;&gt;&gt; table['Group'].corr(table['Age']) -0.15330486289034567 This should be faster than using the full matrix and indexing it (with df.corr().iat['Group', 'Age']). Also, this should work whether Group is bool or int dtype.

http://stackoverflow.com/a/49353788
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49353418
has body: You are using the Unicode of python File "C:\Users\hetle\Anaconda3\envs\untitled\lib\socket.py" Here \U is a kind of Unicode, you have used in C:\Users. So python treats is as Unicode, so just Transpose it as / you will get rid of this problem. File "C:/Users/hetle/Anaconda3/envs/untitled/lib/socket.py" Example : >> &gt;&gt;&gt; s = u'La Pe\xf1a' 1 &gt;&gt;&gt; print s 2 Traceback (innermost last): File "&lt;interactive input&gt;", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) &gt;&gt;&gt; print s.encode('latin-1') 3 La Peña Example 2:>> &gt;&gt;&gt; title 2 u'\u041f\u0440\u0435\u0434\u0438\u0441\u043b\u043e\u0432\u0438\u0435' &gt;&gt;&gt; print title 3 Traceback (innermost last): File "&lt;interactive input&gt;", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) &gt;&gt;&gt; convertedtitle = title.encode('koi8-r') 4 &gt;&gt;&gt; convertedtitle '\xf0\xd2\xc5\xc4\xc9\xd3\xcc\xcf\xd7\xc9\xc5' &gt;&gt;&gt; print convertedtitle 5 Предисловие

http://stackoverflow.com/a/49347759
accepted answer of: http://stackoverflow.com/q/49347442
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85696191
answers question: http://stackoverflow.com/q/49347442
score: 0
has body: high=[i for i, x in enumerate(Ice_Cream) if x == max(Ice_Cream)] for i in high: print ("Your favourite flavour of ice cream is", flavours[i]) variable high stores all the indices of max values of icecreams
type: Answer

http://stackoverflow.com/a/49366573
score: 0
has body: Depending on where your input strings come from, you might do with something like this, named whatever you would want to name it: import re def gen_nums(input_string): out = [] for item in re.split(r',\s*', input_string): if '-' in item: start, end = item.split('-') out.extend(range(int(start), int(end))) else: out.append(int(item)) return out
answers question: http://stackoverflow.com/q/49366161
type: Answer

http://stackoverflow.com/a/49406526
type: Answer
upvote count: 4
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/49406272
has body: Simply, use: model.predict() pred = model.predict(x_test) indices = [i for i,v in enumerate(pred) if pred[i]!=y_test[i]] subset_of_wrongly_predicted = [x_test[i] for i in indices ]

http://stackoverflow.com/q/49282199
has answer: http://stackoverflow.com/a/49282824
linked to: http://stackoverflow.com/q/1933720
tagged with: sqlite
downvote count: 0
has body: Why is the datetime type lost after inserting them in a Sqlite database? import sqlite3, datetime dbconn = sqlite3.connect(':memory:') c = dbconn.cursor() c.execute('create table mytable(title text, t timestamp)') c.execute('insert into mytable (title, t) values (?, ?)', ("hello2", datetime.datetime(2018,3,10,12,12,00))) c.execute("select * from mytable") for a in c.fetchall(): print a[0] # hello2 print type(a[0]) # &lt;type 'unicode'&gt; print a[1] # 2018-03-10 12:12:00 print type(a[1]) # &lt;type 'unicode'&gt; Shouldn't the datetime type remain after an insertion and a query? PS: I lost nearly one hour because of this problem, so I'll post the answer now with the "Answer your own question – share your knowledge, Q&amp;A-style" SO feature. Note: this is not a duplicate of this neighbour question because it doesn't deal about how datetimes are stored/retrieved.
favorite count: 0
has title: How to insert a Python datetime object in a Sqlite database, and retrieve it as datetime object when querying?
type: Question
tagged with: time
type: UnansweredQuestion
tagged with: datetime
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49282200
answer count: 2

http://stackoverflow.com/q/49391163
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49391287
has body: I tried making a simple "investing game". But for some reason the variable cash still says 1000 after the "investment". I also want to make this game continuous. Like the player can keep playing it and gaining/losing cash. The program is below! Thanks! import sys import random print "INVEST" cash = 1000 highlow = ["h", "l"] percentrand = random.randint(1,99) percentup = percentrand/100 + 1 percentdown = percentrand/100 - 1 randomhighlow = random.choice(highlow) print "You have 1000$ on you now." investquit = raw_input("Invest or quit?") if investquit.lower() == "quit": quit() elif investquit.lower() == "invest": if randomhighlow == "h": cash == cash*percentup print str(cash) + ",up," + str(percentrand) + "%" if randomhighlow == "l": cash == cash*percentdown print str(cash) + ",down," + str(percentrand) + "%"
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49391239
has answer: http://stackoverflow.com/a/49391391
has comment: http://stackoverflow.com/comment/85783901
has comment: http://stackoverflow.com/comment/85784583
tagged with: python-2.7
answer count: 3
score: 0
has title: Python Investing Program Error
upvote count: 1

http://stackoverflow.com/q/49433777
has comment: http://stackoverflow.com/comment/85869588
accepted answer: http://stackoverflow.com/a/49433907
downvote count: 0
has answer: http://stackoverflow.com/a/49433907
possible better answer: http://stackoverflow.com/a/49433921
favorite count: 0
has comment: http://stackoverflow.com/comment/85869498
tagged with: python-2.7
type: Question
has title: combine if condition with isnan statement
tagged with: if-statement
tagged with: pandas
score: 3
has answer: http://stackoverflow.com/a/49433916
has answer: http://stackoverflow.com/a/49434069
has body: I am trying to work with an if statement and check if the row values are NaN or not. It turns out to be more difficult that I thought here is an example: df = pd.DataFrame({'key': ['A', 'B', 'C', 'A', 'B', 'C'], 'data1': range(6), 'data2': ['A1', 'B1', 'NaN', 'A1', 'B1','NaN']}, columns = ['key', 'data1', 'data2']) def set_perf(row): if ("C" in row['key']) &amp; (row['data2']=="NaN"): return row['data1'] else: return 1 df['NewColumn'] = df.apply(set_perf, axis=1) the output is key data1 data2 NewColumn 0 A 0 A1 1 1 B 1 B1 1 2 C 2 NaN 2 3 A 3 A1 1 4 B 4 B1 1 5 C 5 NaN 5 The output gives me what I am looking for meaning that I am able to identify the NaN value by adding another condition in the if statement (row['data2']=="NaN") I have applied exactly the same logic in my original dataset but it didnt work. Here is a snapshot NewPerfColumn sec_type tran_type LDI Bucket Alpha vs Markit 0 1.000 GOVT BB NaN 3283.400526 1 1.000 GOVT BB NaN 6710.130364 2 1.000 GOVT BB NaN 3266.912122 3 1.000 GOVT BB NaN 113401.946471 4 1.000 GOVT BB NaN 1938.494818 5 1.000 GOVT BB NaN 9505.724498 6 1.000 GOVT BB NaN 192.196620 7 1.000 MUNITAX RRP NaN -97968.750000 when I add (row['LDI Bucket']=="NaN" ) in the if condition the value "NaN" is not recognizable. here are the distinct values of column "LDI Bucket" data['LDI Bucket'].unique() array([nan, u'0-3m', u'3-6m', u'6-9m', u'9m-1y'], dtype=object) Have I missed anything?
tagged with: python
has answer: http://stackoverflow.com/a/49433921
answer count: 4
type: AnsweredQuestion
upvote count: 3